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/plugins/org.jboss.tools.forge.ui.ext/src/org/jboss/tools/forge/ui/ext/control/CheckboxControlBuilder.java b/plugins/org.jboss.tools.forge.ui.ext/src/org/jboss/tools/forge/ui/ext/control/CheckboxControlBuilder.java
index 01fa0e72..95af130c 100644
--- a/plugins/org.jboss.tools.forge.ui.ext/src/org/jboss/tools/forge/ui/ext/control/CheckboxControlBuilder.java
+++ b/plugins/org.jboss.tools.forge.ui.ext/src/org/jboss/tools/forge/ui/ext/control/CheckboxControlBuilder.java
@@ -1,74 +1,74 @@
/*
* Copyright 2013 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.jboss.tools.forge.ui.ext.control;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.jboss.forge.convert.Converter;
import org.jboss.forge.convert.ConverterFactory;
import org.jboss.forge.ui.hints.InputType;
import org.jboss.forge.ui.hints.InputTypes;
import org.jboss.forge.ui.input.InputComponent;
import org.jboss.forge.ui.input.UIInput;
import org.jboss.forge.ui.util.InputComponents;
import org.jboss.tools.forge.ext.core.ForgeService;
import org.jboss.tools.forge.ui.ext.wizards.ForgeWizardPage;
public class CheckboxControlBuilder extends ControlBuilder {
@Override
public Control build(ForgeWizardPage page,
final InputComponent<?, Object> input, final Composite container) {
- GridData layoutData = new GridData(GridData.FILL_BOTH);
+ GridData layoutData = new GridData(GridData.FILL_HORIZONTAL);
layoutData.horizontalSpan = 2;
Button cmb = new Button(container, SWT.CHECK);
cmb.setLayoutData(layoutData);
cmb.setText(input.getLabel() == null ? input.getName() : input
.getLabel());
// Set Default Value
final ConverterFactory converterFactory = ForgeService.INSTANCE
.getConverterFactory();
if (converterFactory != null) {
Converter<Object, Boolean> converter = converterFactory
.getConverter(input.getValueType(), Boolean.class);
Boolean value = converter.convert(InputComponents
.getValueFor(input));
cmb.setSelection(value == null ? false : value);
}
// cmd.setSelection(value == null ? false : value);
cmb.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
boolean selection = ((Button) e.widget).getSelection();
InputComponents.setValueFor(converterFactory, input, selection);
}
});
return cmb;
}
@Override
protected Class<Boolean> getProducedType() {
return Boolean.class;
}
@Override
protected InputType getSupportedInputType() {
return InputTypes.CHECKBOX;
}
@Override
protected Class<?>[] getSupportedInputComponentTypes() {
return new Class<?>[] { UIInput.class };
}
}
| true | true | public Control build(ForgeWizardPage page,
final InputComponent<?, Object> input, final Composite container) {
GridData layoutData = new GridData(GridData.FILL_BOTH);
layoutData.horizontalSpan = 2;
Button cmb = new Button(container, SWT.CHECK);
cmb.setLayoutData(layoutData);
cmb.setText(input.getLabel() == null ? input.getName() : input
.getLabel());
// Set Default Value
final ConverterFactory converterFactory = ForgeService.INSTANCE
.getConverterFactory();
if (converterFactory != null) {
Converter<Object, Boolean> converter = converterFactory
.getConverter(input.getValueType(), Boolean.class);
Boolean value = converter.convert(InputComponents
.getValueFor(input));
cmb.setSelection(value == null ? false : value);
}
// cmd.setSelection(value == null ? false : value);
cmb.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
boolean selection = ((Button) e.widget).getSelection();
InputComponents.setValueFor(converterFactory, input, selection);
}
});
return cmb;
}
| public Control build(ForgeWizardPage page,
final InputComponent<?, Object> input, final Composite container) {
GridData layoutData = new GridData(GridData.FILL_HORIZONTAL);
layoutData.horizontalSpan = 2;
Button cmb = new Button(container, SWT.CHECK);
cmb.setLayoutData(layoutData);
cmb.setText(input.getLabel() == null ? input.getName() : input
.getLabel());
// Set Default Value
final ConverterFactory converterFactory = ForgeService.INSTANCE
.getConverterFactory();
if (converterFactory != null) {
Converter<Object, Boolean> converter = converterFactory
.getConverter(input.getValueType(), Boolean.class);
Boolean value = converter.convert(InputComponents
.getValueFor(input));
cmb.setSelection(value == null ? false : value);
}
// cmd.setSelection(value == null ? false : value);
cmb.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
boolean selection = ((Button) e.widget).getSelection();
InputComponents.setValueFor(converterFactory, input, selection);
}
});
return cmb;
}
|
diff --git a/src/com/android/mms/dom/smil/SmilPlayer.java b/src/com/android/mms/dom/smil/SmilPlayer.java
index 9bf1508..c81c544 100644
--- a/src/com/android/mms/dom/smil/SmilPlayer.java
+++ b/src/com/android/mms/dom/smil/SmilPlayer.java
@@ -1,762 +1,770 @@
/*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.dom.smil;
import org.w3c.dom.NodeList;
import org.w3c.dom.events.DocumentEvent;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventTarget;
import org.w3c.dom.smil.ElementParallelTimeContainer;
import org.w3c.dom.smil.ElementSequentialTimeContainer;
import org.w3c.dom.smil.ElementTime;
import org.w3c.dom.smil.Time;
import org.w3c.dom.smil.TimeList;
import android.util.Config;
import android.util.Log;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
/**
* The SmilPlayer is responsible for playing, stopping, pausing and resuming a SMIL tree.
* <li>It creates a whole timeline before playing.</li>
* <li>The player runs in a different thread which intends not to block the main thread.</li>
*/
public class SmilPlayer implements Runnable {
private static final String TAG = "Mms/smil";
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = DEBUG ? Config.LOGD : Config.LOGV;
private static final int TIMESLICE = 200;
private static enum SmilPlayerState {
INITIALIZED,
PLAYING,
PLAYED,
PAUSED,
STOPPED,
}
private static enum SmilPlayerAction {
NO_ACTIVE_ACTION,
RELOAD,
STOP,
PAUSE,
START,
NEXT,
PREV
}
public static final String MEDIA_TIME_UPDATED_EVENT = "mediaTimeUpdated";
private static final Comparator<TimelineEntry> sTimelineEntryComparator =
new Comparator<TimelineEntry>() {
public int compare(TimelineEntry o1, TimelineEntry o2) {
return Double.compare(o1.getOffsetTime(), o2.getOffsetTime());
}
};
private static SmilPlayer sPlayer;
private long mCurrentTime;
private int mCurrentElement;
private int mCurrentSlide;
private ArrayList<TimelineEntry> mAllEntries;
private ElementTime mRoot;
private Thread mPlayerThread;
private SmilPlayerState mState = SmilPlayerState.INITIALIZED;
private SmilPlayerAction mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
private ArrayList<ElementTime> mActiveElements;
private Event mMediaTimeUpdatedEvent;
private static ArrayList<TimelineEntry> getParTimeline(
ElementParallelTimeContainer par, double offset, double maxOffset) {
ArrayList<TimelineEntry> timeline = new ArrayList<TimelineEntry>();
// Set my begin at first
TimeList myBeginList = par.getBegin();
/*
* Begin list only contain 1 begin time which has been resolved.
* @see com.android.mms.dom.smil.ElementParallelTimeContainerImpl#getBegin()
*/
Time begin = myBeginList.item(0);
double beginOffset = begin.getResolvedOffset() + offset;
if (beginOffset > maxOffset) {
// This element can't be started.
return timeline;
}
TimelineEntry myBegin = new TimelineEntry(beginOffset, par, TimelineEntry.ACTION_BEGIN);
timeline.add(myBegin);
TimeList myEndList = par.getEnd();
/*
* End list only contain 1 end time which has been resolved.
* @see com.android.mms.dom.smil.ElementParallelTimeContainerImpl#getEnd()
*/
Time end = myEndList.item(0);
double endOffset = end.getResolvedOffset() + offset;
if (endOffset > maxOffset) {
endOffset = maxOffset;
}
TimelineEntry myEnd = new TimelineEntry(endOffset, par, TimelineEntry.ACTION_END);
maxOffset = endOffset;
NodeList children = par.getTimeChildren();
for (int i = 0; i < children.getLength(); ++i) {
ElementTime child = (ElementTime) children.item(i);
ArrayList<TimelineEntry> childTimeline = getTimeline(child, offset, maxOffset);
timeline.addAll(childTimeline);
}
Collections.sort(timeline, sTimelineEntryComparator);
// Add end-event to timeline for all active children
NodeList activeChildrenAtEnd = par.getActiveChildrenAt(
(float) (endOffset - offset) * 1000);
for (int i = 0; i < activeChildrenAtEnd.getLength(); ++i) {
timeline.add(new TimelineEntry(endOffset,
(ElementTime) activeChildrenAtEnd.item(i),
TimelineEntry.ACTION_END));
}
// Set my end at last
timeline.add(myEnd);
return timeline;
}
private static ArrayList<TimelineEntry> getSeqTimeline(
ElementSequentialTimeContainer seq, double offset, double maxOffset) {
ArrayList<TimelineEntry> timeline = new ArrayList<TimelineEntry>();
double orgOffset = offset;
// Set my begin at first
TimeList myBeginList = seq.getBegin();
/*
* Begin list only contain 1 begin time which has been resolved.
* @see com.android.mms.dom.smil.ElementSequentialTimeContainerImpl#getBegin()
*/
Time begin = myBeginList.item(0);
double beginOffset = begin.getResolvedOffset() + offset;
if (beginOffset > maxOffset) {
// This element can't be started.
return timeline;
}
TimelineEntry myBegin = new TimelineEntry(beginOffset, seq, TimelineEntry.ACTION_BEGIN);
timeline.add(myBegin);
TimeList myEndList = seq.getEnd();
/*
* End list only contain 1 end time which has been resolved.
* @see com.android.mms.dom.smil.ElementSequentialTimeContainerImpl#getEnd()
*/
Time end = myEndList.item(0);
double endOffset = end.getResolvedOffset() + offset;
if (endOffset > maxOffset) {
endOffset = maxOffset;
}
TimelineEntry myEnd = new TimelineEntry(endOffset, seq, TimelineEntry.ACTION_END);
maxOffset = endOffset;
// Get children's timelines
NodeList children = seq.getTimeChildren();
for (int i = 0; i < children.getLength(); ++i) {
ElementTime child = (ElementTime) children.item(i);
ArrayList<TimelineEntry> childTimeline = getTimeline(child, offset, maxOffset);
timeline.addAll(childTimeline);
// Since the child timeline has been sorted, the offset of the last one is the biggest.
offset = childTimeline.get(childTimeline.size() - 1).getOffsetTime();
}
// Add end-event to timeline for all active children
NodeList activeChildrenAtEnd = seq.getActiveChildrenAt(
(float) (endOffset - orgOffset));
for (int i = 0; i < activeChildrenAtEnd.getLength(); ++i) {
timeline.add(new TimelineEntry(endOffset,
(ElementTime) activeChildrenAtEnd.item(i),
TimelineEntry.ACTION_END));
}
// Set my end at last
timeline.add(myEnd);
return timeline;
}
private static ArrayList<TimelineEntry> getTimeline(ElementTime element,
double offset, double maxOffset) {
if (element instanceof ElementParallelTimeContainer) {
return getParTimeline((ElementParallelTimeContainer) element, offset, maxOffset);
} else if (element instanceof ElementSequentialTimeContainer) {
return getSeqTimeline((ElementSequentialTimeContainer) element, offset, maxOffset);
} else {
// Not ElementTimeContainer here
ArrayList<TimelineEntry> timeline = new ArrayList<TimelineEntry>();
TimeList beginList = element.getBegin();
for (int i = 0; i < beginList.getLength(); ++i) {
Time begin = beginList.item(i);
if (begin.getResolved()) {
double beginOffset = begin.getResolvedOffset() + offset;
if (beginOffset <= maxOffset) {
TimelineEntry entry = new TimelineEntry(beginOffset,
element, TimelineEntry.ACTION_BEGIN);
timeline.add(entry);
}
}
}
TimeList endList = element.getEnd();
for (int i = 0; i < endList.getLength(); ++i) {
Time end = endList.item(i);
if (end.getResolved()) {
double endOffset = end.getResolvedOffset() + offset;
if (endOffset <= maxOffset) {
TimelineEntry entry = new TimelineEntry(endOffset,
element, TimelineEntry.ACTION_END);
timeline.add(entry);
}
}
}
Collections.sort(timeline, sTimelineEntryComparator);
return timeline;
}
}
private SmilPlayer() {
// Private constructor
}
public static SmilPlayer getPlayer() {
if (sPlayer == null) {
sPlayer = new SmilPlayer();
}
return sPlayer;
}
public synchronized boolean isPlayingState() {
return mState == SmilPlayerState.PLAYING;
}
public synchronized boolean isPlayedState() {
return mState == SmilPlayerState.PLAYED;
}
public synchronized boolean isPausedState() {
return mState == SmilPlayerState.PAUSED;
}
public synchronized boolean isStoppedState() {
return mState == SmilPlayerState.STOPPED;
}
private synchronized boolean isPauseAction() {
return mAction == SmilPlayerAction.PAUSE;
}
private synchronized boolean isStartAction() {
return mAction == SmilPlayerAction.START;
}
private synchronized boolean isStopAction() {
return mAction == SmilPlayerAction.STOP;
}
private synchronized boolean isReloadAction() {
return mAction == SmilPlayerAction.RELOAD;
}
private synchronized boolean isNextAction() {
return mAction == SmilPlayerAction.NEXT;
}
private synchronized boolean isPrevAction() {
return mAction == SmilPlayerAction.PREV;
}
public synchronized void init(ElementTime root) {
mRoot = root;
mAllEntries = getTimeline(mRoot, 0, Long.MAX_VALUE);
mMediaTimeUpdatedEvent = ((DocumentEvent) mRoot).createEvent("Event");
mMediaTimeUpdatedEvent.initEvent(MEDIA_TIME_UPDATED_EVENT, false, false);
mActiveElements = new ArrayList<ElementTime>();
}
public synchronized void play() {
if (!isPlayingState()) {
mCurrentTime = 0;
mCurrentElement = 0;
mCurrentSlide = 0;
mPlayerThread = new Thread(this);
mState = SmilPlayerState.PLAYING;
mPlayerThread.start();
} else {
Log.w(TAG, "Error State: Playback is playing!");
}
}
public synchronized void pause() {
if (isPlayingState()) {
mAction = SmilPlayerAction.PAUSE;
notifyAll();
} else {
Log.w(TAG, "Error State: Playback is not playing!");
}
}
public synchronized void start() {
if (isPausedState()) {
resumeActiveElements();
mAction = SmilPlayerAction.START;
notifyAll();
} else if (isPlayedState()) {
play();
} else {
Log.w(TAG, "Error State: Playback can not be started!");
}
}
public synchronized void stop() {
if (isPlayingState() || isPausedState()) {
mAction = SmilPlayerAction.STOP;
notifyAll();
} else if (isPlayedState()) {
actionStop();
}
}
public synchronized void stopWhenReload() {
endActiveElements();
}
public synchronized void reload() {
if (isPlayingState() || isPausedState()) {
mAction = SmilPlayerAction.RELOAD;
notifyAll();
} else if (isPlayedState()) {
actionReload();
}
}
public synchronized void next() {
if (isPlayingState() || isPausedState()) {
mAction = SmilPlayerAction.NEXT;
notifyAll();
}
}
public synchronized void prev() {
if (isPlayingState() || isPausedState()) {
mAction = SmilPlayerAction.PREV;
notifyAll();
}
}
private synchronized boolean isBeginOfSlide(TimelineEntry entry) {
return (TimelineEntry.ACTION_BEGIN == entry.getAction())
&& (entry.getElement() instanceof SmilParElementImpl);
}
private synchronized void reloadActiveSlide() {
mActiveElements.clear();
beginSmilDocument();
for (int i = mCurrentSlide; i < mCurrentElement; i++) {
TimelineEntry entry = mAllEntries.get(i);
actionEntry(entry);
}
seekActiveMedia();
}
private synchronized void beginSmilDocument() {
TimelineEntry entry = mAllEntries.get(0);
actionEntry(entry);
}
private synchronized double getOffsetTime(ElementTime element) {
for (int i = mCurrentSlide; i < mCurrentElement; i++) {
TimelineEntry entry = mAllEntries.get(i);
if (element.equals(entry.getElement())) {
return entry.getOffsetTime() * 1000; // in ms
}
}
return -1;
}
private synchronized void seekActiveMedia() {
for (int i = mActiveElements.size() - 1; i >= 0; i--) {
ElementTime element = mActiveElements.get(i);
if (element instanceof SmilParElementImpl) {
return;
}
double offset = getOffsetTime(element);
if ((offset >= 0) && (offset <= mCurrentTime)) {
if (LOCAL_LOGV) {
Log.v(TAG, "[SEEK] " + " at " + mCurrentTime
+ " " + element);
}
element.seekElement( (float) (mCurrentTime - offset) );
}
}
}
private synchronized void waitForEntry(long interval)
throws InterruptedException {
if (LOCAL_LOGV) {
Log.v(TAG, "Waiting for " + interval + "ms.");
}
long overhead = 0;
while (interval > 0) {
long startAt = System.currentTimeMillis();
long sleep = Math.min(interval, TIMESLICE);
if (overhead < sleep) {
wait(sleep - overhead);
mCurrentTime += sleep;
} else {
sleep = 0;
mCurrentTime += overhead;
}
if (isStopAction() || isReloadAction() || isPauseAction() || isNextAction() ||
isPrevAction()) {
return;
}
((EventTarget) mRoot).dispatchEvent(mMediaTimeUpdatedEvent);
interval -= TIMESLICE;
overhead = System.currentTimeMillis() - startAt - sleep;
}
}
public synchronized int getDuration() {
if ((mAllEntries != null) && !mAllEntries.isEmpty()) {
return (int) mAllEntries.get(mAllEntries.size() - 1).mOffsetTime * 1000;
}
return 0;
}
public synchronized int getCurrentPosition() {
return (int) mCurrentTime;
}
private synchronized void endActiveElements() {
for (int i = mActiveElements.size() - 1; i >= 0; i--) {
ElementTime element = mActiveElements.get(i);
if (LOCAL_LOGV) {
Log.v(TAG, "[STOP] " + " at " + mCurrentTime
+ " " + element);
}
element.endElement();
}
}
private synchronized void pauseActiveElements() {
for (int i = mActiveElements.size() - 1; i >= 0; i--) {
ElementTime element = mActiveElements.get(i);
if (LOCAL_LOGV) {
Log.v(TAG, "[PAUSE] " + " at " + mCurrentTime
+ " " + element);
}
element.pauseElement();
}
}
private synchronized void resumeActiveElements() {
int size = mActiveElements.size();
for (int i = 0; i < size; i++) {
ElementTime element = mActiveElements.get(i);
if (LOCAL_LOGV) {
Log.v(TAG, "[RESUME] " + " at " + mCurrentTime
+ " " + element);
}
element.resumeElement();
}
}
private synchronized void waitForWakeUp() {
try {
while ( !(isStartAction() || isStopAction() || isReloadAction() ||
isNextAction() || isPrevAction()) ) {
wait(TIMESLICE);
}
if (isStartAction()) {
mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
mState = SmilPlayerState.PLAYING;
}
} catch (InterruptedException e) {
Log.e(TAG, "Unexpected InterruptedException.", e);
}
}
private synchronized void actionEntry(TimelineEntry entry) {
switch (entry.getAction()) {
case TimelineEntry.ACTION_BEGIN:
if (LOCAL_LOGV) {
Log.v(TAG, "[START] " + " at " + mCurrentTime + " "
+ entry.getElement());
}
entry.getElement().beginElement();
mActiveElements.add(entry.getElement());
break;
case TimelineEntry.ACTION_END:
if (LOCAL_LOGV) {
Log.v(TAG, "[STOP] " + " at " + mCurrentTime + " "
+ entry.getElement());
}
entry.getElement().endElement();
mActiveElements.remove(entry.getElement());
break;
default:
break;
}
}
private synchronized TimelineEntry reloadCurrentEntry() {
// Check if the position is less than size of all entries
if (mCurrentElement < mAllEntries.size()) {
return mAllEntries.get(mCurrentElement);
} else {
return null;
}
}
private void stopCurrentSlide() {
HashSet<TimelineEntry> skippedEntries = new HashSet<TimelineEntry>();
int totalEntries = mAllEntries.size();
for (int i = mCurrentElement; i < totalEntries; i++) {
// Stop any started entries, and skip the not started entries until
// meeting the end of slide
TimelineEntry entry = mAllEntries.get(i);
int action = entry.getAction();
if (entry.getElement() instanceof SmilParElementImpl &&
action == TimelineEntry.ACTION_END) {
actionEntry(entry);
mCurrentElement = i;
break;
} else if (action == TimelineEntry.ACTION_END && !skippedEntries.contains(entry)) {
actionEntry(entry);
} else if (action == TimelineEntry.ACTION_BEGIN) {
skippedEntries.add(entry);
}
}
}
private TimelineEntry loadNextSlide() {
TimelineEntry entry;
int totalEntries = mAllEntries.size();
for (int i = mCurrentElement; i < totalEntries; i++) {
entry = mAllEntries.get(i);
if (isBeginOfSlide(entry)) {
mCurrentElement = i;
mCurrentSlide = i;
mCurrentTime = (long)(entry.getOffsetTime() * 1000);
return entry;
}
}
// No slide, finish play back
mCurrentElement++;
entry = null;
if (mCurrentElement < totalEntries) {
entry = mAllEntries.get(mCurrentElement);
mCurrentTime = (long)(entry.getOffsetTime() * 1000);
}
return entry;
}
private TimelineEntry loadPrevSlide() {
int skippedSlides = 1;
int latestBeginEntryIndex = -1;
for (int i = mCurrentSlide; i >= 0; i--) {
TimelineEntry entry = mAllEntries.get(i);
if (isBeginOfSlide(entry)) {
latestBeginEntryIndex = i;
if (0 == skippedSlides-- ) {
mCurrentElement = i;
mCurrentSlide = i;
mCurrentTime = (long)(entry.getOffsetTime() * 1000);
return entry;
}
}
}
if (latestBeginEntryIndex != -1) {
mCurrentElement = latestBeginEntryIndex;
mCurrentSlide = latestBeginEntryIndex;
return mAllEntries.get(mCurrentElement);
}
return null;
}
private synchronized TimelineEntry actionNext() {
stopCurrentSlide();
return loadNextSlide();
}
private synchronized TimelineEntry actionPrev() {
stopCurrentSlide();
return loadPrevSlide();
}
private synchronized void actionPause() {
pauseActiveElements();
mState = SmilPlayerState.PAUSED;
mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
}
private synchronized void actionStop() {
endActiveElements();
mCurrentTime = 0;
mCurrentElement = 0;
mCurrentSlide = 0;
mState = SmilPlayerState.STOPPED;
mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
}
private synchronized void actionReload() {
reloadActiveSlide();
mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
}
public void run() {
+ long lastbeg = 0;
if (isStoppedState()) {
return;
}
if (LOCAL_LOGV) {
dumpAllEntries();
}
// Play the Element by following the timeline
int size = mAllEntries.size();
for (mCurrentElement = 0; mCurrentElement < size; mCurrentElement++) {
TimelineEntry entry = mAllEntries.get(mCurrentElement);
+ long offset = (long) (entry.getOffsetTime() * 1000); // in ms.
if (isBeginOfSlide(entry)) {
+ lastbeg = offset;
mCurrentSlide = mCurrentElement;
+ } else if (offset == lastbeg
+ && (entry.getElement() instanceof SmilParElementImpl)) {
+ /* If entry has zero duration, pause it */
+ mAction = SmilPlayerAction.PAUSE;
+ actionPause();
+ waitForWakeUp();
}
- long offset = (long) (entry.getOffsetTime() * 1000); // in ms.
while (offset > mCurrentTime) {
try {
waitForEntry(offset - mCurrentTime);
} catch (InterruptedException e) {
Log.e(TAG, "Unexpected InterruptedException.", e);
}
while (isPauseAction() || isStopAction() || isReloadAction() || isNextAction() ||
isPrevAction()) {
if (isPauseAction()) {
actionPause();
waitForWakeUp();
}
if (isStopAction()) {
actionStop();
return;
}
if (isReloadAction()) {
actionReload();
entry = reloadCurrentEntry();
if (entry == null)
return;
if (isPausedState()) {
mAction = SmilPlayerAction.PAUSE;
}
}
if (isNextAction()) {
TimelineEntry nextEntry = actionNext();
if (nextEntry != null) {
entry = nextEntry;
}
if (mState == SmilPlayerState.PAUSED) {
mAction = SmilPlayerAction.PAUSE;
actionEntry(entry);
} else {
mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
}
offset = mCurrentTime;
}
if (isPrevAction()) {
TimelineEntry prevEntry = actionPrev();
if (prevEntry != null) {
entry = prevEntry;
}
if (mState == SmilPlayerState.PAUSED) {
mAction = SmilPlayerAction.PAUSE;
actionEntry(entry);
} else {
mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
}
offset = mCurrentTime;
}
}
}
mCurrentTime = offset;
actionEntry(entry);
}
mState = SmilPlayerState.PLAYED;
}
private static final class TimelineEntry {
final static int ACTION_BEGIN = 0;
final static int ACTION_END = 1;
private final double mOffsetTime;
private final ElementTime mElement;
private final int mAction;
public TimelineEntry(double offsetTime, ElementTime element, int action) {
mOffsetTime = offsetTime;
mElement = element;
mAction = action;
}
public double getOffsetTime() {
return mOffsetTime;
}
public ElementTime getElement() {
return mElement;
}
public int getAction() {
return mAction;
}
public String toString() {
return "Type = " + mElement + " offset = " + getOffsetTime() + " action = " + getAction();
}
}
private void dumpAllEntries() {
if (LOCAL_LOGV) {
for (TimelineEntry entry : mAllEntries) {
Log.v(TAG, "[Entry] "+ entry);
}
}
}
}
| false | true | public void run() {
if (isStoppedState()) {
return;
}
if (LOCAL_LOGV) {
dumpAllEntries();
}
// Play the Element by following the timeline
int size = mAllEntries.size();
for (mCurrentElement = 0; mCurrentElement < size; mCurrentElement++) {
TimelineEntry entry = mAllEntries.get(mCurrentElement);
if (isBeginOfSlide(entry)) {
mCurrentSlide = mCurrentElement;
}
long offset = (long) (entry.getOffsetTime() * 1000); // in ms.
while (offset > mCurrentTime) {
try {
waitForEntry(offset - mCurrentTime);
} catch (InterruptedException e) {
Log.e(TAG, "Unexpected InterruptedException.", e);
}
while (isPauseAction() || isStopAction() || isReloadAction() || isNextAction() ||
isPrevAction()) {
if (isPauseAction()) {
actionPause();
waitForWakeUp();
}
if (isStopAction()) {
actionStop();
return;
}
if (isReloadAction()) {
actionReload();
entry = reloadCurrentEntry();
if (entry == null)
return;
if (isPausedState()) {
mAction = SmilPlayerAction.PAUSE;
}
}
if (isNextAction()) {
TimelineEntry nextEntry = actionNext();
if (nextEntry != null) {
entry = nextEntry;
}
if (mState == SmilPlayerState.PAUSED) {
mAction = SmilPlayerAction.PAUSE;
actionEntry(entry);
} else {
mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
}
offset = mCurrentTime;
}
if (isPrevAction()) {
TimelineEntry prevEntry = actionPrev();
if (prevEntry != null) {
entry = prevEntry;
}
if (mState == SmilPlayerState.PAUSED) {
mAction = SmilPlayerAction.PAUSE;
actionEntry(entry);
} else {
mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
}
offset = mCurrentTime;
}
}
}
mCurrentTime = offset;
actionEntry(entry);
}
mState = SmilPlayerState.PLAYED;
}
| public void run() {
long lastbeg = 0;
if (isStoppedState()) {
return;
}
if (LOCAL_LOGV) {
dumpAllEntries();
}
// Play the Element by following the timeline
int size = mAllEntries.size();
for (mCurrentElement = 0; mCurrentElement < size; mCurrentElement++) {
TimelineEntry entry = mAllEntries.get(mCurrentElement);
long offset = (long) (entry.getOffsetTime() * 1000); // in ms.
if (isBeginOfSlide(entry)) {
lastbeg = offset;
mCurrentSlide = mCurrentElement;
} else if (offset == lastbeg
&& (entry.getElement() instanceof SmilParElementImpl)) {
/* If entry has zero duration, pause it */
mAction = SmilPlayerAction.PAUSE;
actionPause();
waitForWakeUp();
}
while (offset > mCurrentTime) {
try {
waitForEntry(offset - mCurrentTime);
} catch (InterruptedException e) {
Log.e(TAG, "Unexpected InterruptedException.", e);
}
while (isPauseAction() || isStopAction() || isReloadAction() || isNextAction() ||
isPrevAction()) {
if (isPauseAction()) {
actionPause();
waitForWakeUp();
}
if (isStopAction()) {
actionStop();
return;
}
if (isReloadAction()) {
actionReload();
entry = reloadCurrentEntry();
if (entry == null)
return;
if (isPausedState()) {
mAction = SmilPlayerAction.PAUSE;
}
}
if (isNextAction()) {
TimelineEntry nextEntry = actionNext();
if (nextEntry != null) {
entry = nextEntry;
}
if (mState == SmilPlayerState.PAUSED) {
mAction = SmilPlayerAction.PAUSE;
actionEntry(entry);
} else {
mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
}
offset = mCurrentTime;
}
if (isPrevAction()) {
TimelineEntry prevEntry = actionPrev();
if (prevEntry != null) {
entry = prevEntry;
}
if (mState == SmilPlayerState.PAUSED) {
mAction = SmilPlayerAction.PAUSE;
actionEntry(entry);
} else {
mAction = SmilPlayerAction.NO_ACTIVE_ACTION;
}
offset = mCurrentTime;
}
}
}
mCurrentTime = offset;
actionEntry(entry);
}
mState = SmilPlayerState.PLAYED;
}
|
diff --git a/src/java/org/jamwiki/servlets/JAMWikiServlet.java b/src/java/org/jamwiki/servlets/JAMWikiServlet.java
index 5280bdad..94411414 100644
--- a/src/java/org/jamwiki/servlets/JAMWikiServlet.java
+++ b/src/java/org/jamwiki/servlets/JAMWikiServlet.java
@@ -1,469 +1,469 @@
/**
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, version 2.1, dated February 1999.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the latest version of the GNU Lesser General
* Public License 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program (LICENSE.txt); if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.jamwiki.servlets;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.jamwiki.Environment;
import org.jamwiki.WikiBase;
import org.jamwiki.WikiException;
import org.jamwiki.WikiMessage;
import org.jamwiki.model.Category;
import org.jamwiki.model.Topic;
import org.jamwiki.model.VirtualWiki;
import org.jamwiki.model.WikiUser;
import org.jamwiki.parser.ParserInput;
import org.jamwiki.parser.ParserOutput;
import org.jamwiki.utils.LinkUtil;
import org.jamwiki.utils.Utilities;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
/**
*
*/
public abstract class JAMWikiServlet extends AbstractController {
private static final Logger logger = Logger.getLogger(JAMWikiServlet.class);
public static final String PARAMETER_PAGE_INFO = "pageInfo";
public static final String PARAMETER_TOPIC = "topic";
public static final String PARAMETER_TOPIC_OBJECT = "topicObject";
public static final String PARAMETER_USER = "user";
public static final String PARAMETER_VIRTUAL_WIKI = "virtualWiki";
public static final String USER_COOKIE = "user-cookie";
public static final String USER_COOKIE_DELIMITER = "|";
// FIXME - make configurable
public static final int USER_COOKIE_EXPIRES = 60 * 60 * 24 * 14; // 14 days
private static LinkedHashMap cachedContents = new LinkedHashMap();
/**
*
*/
protected void redirect(String destination, HttpServletResponse response) {
String url = response.encodeRedirectURL(destination);
try {
response.sendRedirect(url);
} catch (Exception e) {
logger.error(e);
}
}
/**
*
*/
private static void buildLayout(HttpServletRequest request, ModelAndView next) throws Exception {
String virtualWikiName = JAMWikiServlet.getVirtualWikiFromURI(request);
if (virtualWikiName == null) {
logger.error("No virtual wiki available for page request " + request.getRequestURI());
virtualWikiName = WikiBase.DEFAULT_VWIKI;
}
VirtualWiki virtualWiki = WikiBase.getHandler().lookupVirtualWiki(virtualWikiName);
if (virtualWiki == null) {
logger.error("No virtual wiki found for " + virtualWikiName);
virtualWikiName = WikiBase.DEFAULT_VWIKI;
virtualWiki = WikiBase.getHandler().lookupVirtualWiki(virtualWikiName);
}
// build the layout contents
String leftMenu = JAMWikiServlet.getCachedContent(request, virtualWikiName, WikiBase.SPECIAL_PAGE_LEFT_MENU, true);
next.addObject("leftMenu", leftMenu);
next.addObject("defaultTopic", virtualWiki.getDefaultTopicName());
next.addObject("logo", Environment.getValue(Environment.PROP_BASE_LOGO_IMAGE));
String bottomArea = JAMWikiServlet.getCachedContent(request, virtualWikiName, WikiBase.SPECIAL_PAGE_BOTTOM_AREA, true);
next.addObject("bottomArea", bottomArea);
next.addObject(PARAMETER_VIRTUAL_WIKI, virtualWikiName);
}
/**
*
*/
protected Topic getRedirectTarget(Topic parent, int attempts) throws Exception {
if (parent.getTopicType() != Topic.TYPE_REDIRECT || !StringUtils.hasText(parent.getRedirectTo())) {
logger.error("getRedirectTarget() called for non-redirect topic " + parent.getName());
return parent;
}
// avoid infinite redirection
attempts++;
if (attempts > 10) {
throw new WikiException(new WikiMessage("topic.redirect.infinite"));
}
// get the topic that is being redirected to
Topic child = WikiBase.getHandler().lookupTopic(parent.getVirtualWiki(), parent.getRedirectTo());
if (child == null) {
// child being redirected to doesn't exist, return parent
return parent;
}
if (!StringUtils.hasText(child.getRedirectTo())) {
// found a topic that is not a redirect, return
return child;
}
if (WikiBase.getHandler().lookupTopic(child.getVirtualWiki(), child.getRedirectTo()) == null) {
}
// topic is a redirect, keep looking
return this.getRedirectTarget(child, attempts);
}
/**
*
*/
public static String getTopicFromURI(HttpServletRequest request) throws Exception {
String uri = request.getRequestURI().trim();
// FIXME - needs testing on other platforms
uri = Utilities.convertEncoding(uri, "ISO-8859-1", "UTF-8");
if (uri == null || uri.length() <= 0) {
throw new Exception("URI string is empty");
}
int slashIndex = uri.lastIndexOf('/');
if (slashIndex == -1) {
throw new Exception("No topic in URL: " + uri);
}
String topic = uri.substring(slashIndex + 1);
topic = Utilities.decodeURL(topic);
return topic;
}
/**
*
*/
public static String getTopicFromRequest(HttpServletRequest request) throws Exception {
String topic = request.getParameter(JAMWikiServlet.PARAMETER_TOPIC);
if (topic == null) {
topic = (String)request.getAttribute(JAMWikiServlet.PARAMETER_TOPIC);
}
if (topic == null) return null;
topic = Utilities.decodeURL(topic);
return topic;
}
/**
*
*/
public static String getVirtualWikiFromURI(HttpServletRequest request) {
String uri = request.getRequestURI().trim();
// FIXME - needs testing on other platforms
uri = Utilities.convertEncoding(uri, "ISO-8859-1", "UTF-8");
String contextPath = request.getContextPath().trim();
String virtualWiki = null;
if (!StringUtils.hasText(uri) || contextPath == null) {
return null;
}
uri = uri.substring(contextPath.length() + 1);
int slashIndex = uri.indexOf('/');
if (slashIndex == -1) {
return null;
}
virtualWiki = uri.substring(0, slashIndex);
return virtualWiki;
}
/**
*
*/
protected static boolean isTopic(HttpServletRequest request, String value) {
try {
String topic = JAMWikiServlet.getTopicFromURI(request);
if (!StringUtils.hasText(topic)) {
return false;
}
if (value != null && topic.equals(value)) {
return true;
}
} catch (Exception e) {}
return false;
}
/**
*
*/
public static String getCachedContent(HttpServletRequest request, String virtualWiki, String topicName, boolean cook) {
String content = (String)cachedContents.get(virtualWiki + "-" + topicName);
if (content == null) {
try {
Topic topic = WikiBase.getHandler().lookupTopic(virtualWiki, topicName);
content = topic.getTopicContent();
if (cook) {
ParserInput parserInput = new ParserInput();
parserInput.setContext(request.getContextPath());
parserInput.setLocale(request.getLocale());
parserInput.setVirtualWiki(virtualWiki);
parserInput.setTopicName(topicName);
ParserOutput parserOutput = Utilities.parse(parserInput, content, topicName);
content = parserOutput.getContent();
}
cachedContents.put(virtualWiki + "-" + topicName, content);
} catch (Exception e) {
logger.warn("error getting cached page " + virtualWiki + " / " + topicName, e);
return null;
}
}
return content;
}
/**
* Utility method for adding category content to the ModelAndView object.
*/
protected void loadCategoryContent(ModelAndView next, String virtualWiki, String topicName) throws Exception {
String categoryName = topicName.substring(WikiBase.NAMESPACE_CATEGORY.length());
next.addObject("categoryName", categoryName);
Collection categoryTopics = WikiBase.getHandler().lookupCategoryTopics(virtualWiki, topicName, Topic.TYPE_ARTICLE);
next.addObject("categoryTopics", categoryTopics);
next.addObject("numCategoryTopics", new Integer(categoryTopics.size()));
Collection categoryImages = WikiBase.getHandler().lookupCategoryTopics(virtualWiki, topicName, Topic.TYPE_IMAGE);
next.addObject("categoryImages", categoryImages);
next.addObject("numCategoryImages", new Integer(categoryImages.size()));
Collection tempSubcategories = WikiBase.getHandler().lookupCategoryTopics(virtualWiki, topicName, Topic.TYPE_CATEGORY);
LinkedHashMap subCategories = new LinkedHashMap();
for (Iterator iterator = tempSubcategories.iterator(); iterator.hasNext();) {
Category category = (Category)iterator.next();
String value = category.getChildTopicName().substring(WikiBase.NAMESPACE_CATEGORY.length());
subCategories.put(category.getChildTopicName(), value);
}
next.addObject("subCategories", subCategories);
next.addObject("numSubCategories", new Integer(subCategories.size()));
}
/**
*
*/
protected void loadDefaults(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) {
// load cached top area, nav bar, etc.
try {
this.buildLayout(request, next);
} catch (Exception e) {
logger.error("Unable to build default page layout", e);
}
// add link to user page and comments page
WikiUser user = Utilities.currentUser(request);
if (user != null) {
next.addObject("userpage", WikiBase.NAMESPACE_USER + user.getLogin());
next.addObject("usercomments", WikiBase.NAMESPACE_USER_COMMENTS + user.getLogin());
next.addObject("adminUser", new Boolean(user.getAdmin()));
- if (Environment.getBooleanValue(Environment.PROP_TOPIC_NON_ADMIN_TOPIC_MOVE) || user.getAdmin()) {
- pageInfo.setCanMove(true);
- }
+ }
+ if (Environment.getBooleanValue(Environment.PROP_TOPIC_NON_ADMIN_TOPIC_MOVE) || (user != null && user.getAdmin())) {
+ pageInfo.setCanMove(true);
}
if (!pageInfo.getSpecial()) {
// FIXME - this is really ugly
String article = pageInfo.getTopicName();
String comments = WikiBase.NAMESPACE_COMMENTS + article;
if (article != null && article.startsWith(WikiBase.NAMESPACE_COMMENTS)) {
int pos = WikiBase.NAMESPACE_COMMENTS.length();
article = article.substring(pos);
comments = WikiBase.NAMESPACE_COMMENTS + article;
} else if (article != null && article.startsWith(WikiBase.NAMESPACE_SPECIAL)) {
int pos = WikiBase.NAMESPACE_SPECIAL.length();
article = article.substring(pos);
comments = WikiBase.NAMESPACE_COMMENTS + article;
} else if (article != null && article.startsWith(WikiBase.NAMESPACE_USER_COMMENTS)) {
int pos = WikiBase.NAMESPACE_USER_COMMENTS.length();
comments = article;
article = WikiBase.NAMESPACE_USER + article.substring(pos);
} else if (article != null && article.startsWith(WikiBase.NAMESPACE_USER)) {
int pos = WikiBase.NAMESPACE_USER.length();
comments = WikiBase.NAMESPACE_USER_COMMENTS + article.substring(pos);
} else if (article != null && article.startsWith(WikiBase.NAMESPACE_IMAGE_COMMENTS)) {
int pos = WikiBase.NAMESPACE_IMAGE_COMMENTS.length();
comments = article;
article = WikiBase.NAMESPACE_IMAGE + article.substring(pos);
} else if (article != null && article.startsWith(WikiBase.NAMESPACE_IMAGE)) {
int pos = WikiBase.NAMESPACE_IMAGE.length();
comments = WikiBase.NAMESPACE_IMAGE_COMMENTS + article.substring(pos);
}
next.addObject("article", article);
next.addObject("comments", comments);
String editLink = "Special:Edit?topic=" + Utilities.encodeURL(pageInfo.getTopicName());
if (StringUtils.hasText(request.getParameter("topicVersionId"))) {
editLink += "&topicVersionId=" + request.getParameter("topicVersionId");
}
next.addObject("edit", editLink);
}
if (!StringUtils.hasText(pageInfo.getTopicName())) {
try {
pageInfo.setTopicName(JAMWikiServlet.getTopicFromURI(request));
} catch (Exception e) {
logger.error("Unable to load topic value in JAMWikiServlet", e);
}
}
next.addObject(PARAMETER_PAGE_INFO, pageInfo);
}
/**
* Clears cached contents including the top area, left nav, bottom area, etc.
* This method should be called when the contents of these areas may have been
* modified.
*/
public static void removeCachedContents() {
cachedContents.clear();
}
/**
* Action used when redirecting to an error page.
*
* @param request The servlet request object.
* @param next The Spring ModelAndView object.
* @param e The exception that is the source of the error.
*/
protected ModelAndView viewError(HttpServletRequest request, Exception e) {
if (!(e instanceof WikiException)) {
logger.error("Servlet error", e);
}
ModelAndView next = new ModelAndView("wiki");
WikiPageInfo pageInfo = new WikiPageInfo();
pageInfo.setPageTitle(new WikiMessage("error.title"));
pageInfo.setAction(WikiPageInfo.ACTION_ERROR);
pageInfo.setSpecial(true);
if (e instanceof WikiException) {
WikiException we = (WikiException)e;
next.addObject("errorMessage", we.getWikiMessage());
} else {
next.addObject("errorMessage", new WikiMessage("error.unknown", e.getMessage()));
}
loadDefaults(request, next, pageInfo);
return next;
}
/**
* Action used when redirecting to a login page.
*
* @param request The servlet request object.
* @param next The Spring ModelAndView object.
* @param topic The topic to be redirected to. Valid examples are "Special:Admin",
* "StartingPoints", etc.
*/
protected ModelAndView viewLogin(HttpServletRequest request, String topic, WikiMessage errorMessage) throws Exception {
ModelAndView next = new ModelAndView("wiki");
WikiPageInfo pageInfo = new WikiPageInfo();
String virtualWikiName = JAMWikiServlet.getVirtualWikiFromURI(request);
String redirect = request.getParameter("redirect");
if (!StringUtils.hasText(redirect)) {
if (!StringUtils.hasText(topic)) {
VirtualWiki virtualWiki = WikiBase.getHandler().lookupVirtualWiki(virtualWikiName);
topic = virtualWiki.getDefaultTopicName();
}
redirect = LinkUtil.buildInternalLinkUrl(request.getContextPath(), virtualWikiName, topic, null, request.getQueryString());
}
next.addObject("redirect", redirect);
pageInfo.setPageTitle(new WikiMessage("login.title"));
pageInfo.setAction(WikiPageInfo.ACTION_LOGIN);
pageInfo.setSpecial(true);
if (errorMessage != null) {
next.addObject("errorMessage", errorMessage);
}
loadDefaults(request, next, pageInfo);
return next;
}
/**
* Action used when viewing a topic.
*
* @param request The servlet request object.
* @param next The Spring ModelAndView object.
* @param topicName The topic being viewed. This value must be a valid topic that
* can be loaded as a org.jamwiki.model.Topic object.
*/
protected void viewTopic(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo, String topicName) throws Exception {
if (!Utilities.validateName(topicName)) {
throw new WikiException(new WikiMessage("common.exception.name", topicName));
}
String virtualWiki = JAMWikiServlet.getVirtualWikiFromURI(request);
if (!StringUtils.hasText(virtualWiki)) {
virtualWiki = WikiBase.DEFAULT_VWIKI;
}
Topic topic = WikiBase.getHandler().lookupTopic(virtualWiki, topicName);
if (topic == null) {
// topic does not exist, display empty page
topic = new Topic();
topic.setName(topicName);
topic.setVirtualWiki(virtualWiki);
next.addObject("notopic", new WikiMessage("topic.notcreated", topicName));
}
WikiMessage pageTitle = new WikiMessage("topic.title", topicName);
viewTopic(request, next, pageInfo, pageTitle, topic, true, false);
}
/**
* Action used when viewing a topic.
*
* @param request The servlet request object.
* @param next The Spring ModelAndView object.
* @param topicName The topic being viewed. This value must be a valid topic that
* can be loaded as a org.jamwiki.model.Topic object.
*/
protected void viewTopic(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo, WikiMessage pageTitle, Topic topic, boolean sectionEdit, boolean preview) throws Exception {
// FIXME - what should the default be for topics that don't exist?
String contents = "";
if (topic == null) {
throw new WikiException(new WikiMessage("common.exception.notopic"));
}
if (!Utilities.validateName(topic.getName())) {
throw new WikiException(new WikiMessage("common.exception.name", topic.getName()));
}
if (topic.getTopicType() == Topic.TYPE_REDIRECT && (request.getParameter("redirect") == null || !request.getParameter("redirect").equalsIgnoreCase("no"))) {
Topic child = this.getRedirectTarget(topic, 0);
if (!child.getName().equals(topic.getName())) {
pageInfo.setRedirectName(topic.getName());
pageTitle = new WikiMessage("topic.title", child.getName());
topic = child;
}
}
String virtualWiki = topic.getVirtualWiki();
String topicName = topic.getName();
String displayName = request.getRemoteAddr();
WikiUser user = Utilities.currentUser(request);
ParserInput parserInput = new ParserInput();
parserInput.setContext(request.getContextPath());
parserInput.setLocale(request.getLocale());
parserInput.setWikiUser(user);
parserInput.setTopicName(topicName);
parserInput.setUserIpAddress(request.getRemoteAddr());
parserInput.setVirtualWiki(virtualWiki);
parserInput.setAllowSectionEdit(sectionEdit);
if (preview) {
parserInput.setMode(ParserInput.MODE_PREVIEW);
}
ParserOutput parserOutput = Utilities.parse(parserInput, topic.getTopicContent(), topicName);
if (parserOutput != null) {
if (parserOutput.getCategories().size() > 0) {
LinkedHashMap categories = new LinkedHashMap();
for (Iterator iterator = parserOutput.getCategories().keySet().iterator(); iterator.hasNext();) {
String key = (String)iterator.next();
String value = key.substring(WikiBase.NAMESPACE_CATEGORY.length());
categories.put(key, value);
}
next.addObject("categories", categories);
}
topic.setTopicContent(parserOutput.getContent());
}
if (topic.getTopicType() == Topic.TYPE_CATEGORY) {
loadCategoryContent(next, virtualWiki, topic.getName());
}
if (topic.getTopicType() == Topic.TYPE_IMAGE) {
Collection fileVersions = WikiBase.getHandler().getAllWikiFileVersions(virtualWiki, topicName, true);
next.addObject("fileVersions", fileVersions);
}
pageInfo.setSpecial(false);
pageInfo.setTopicName(topicName);
next.addObject(JAMWikiServlet.PARAMETER_TOPIC_OBJECT, topic);
if (pageTitle != null) {
pageInfo.setPageTitle(pageTitle);
}
}
}
| true | true | protected void loadDefaults(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) {
// load cached top area, nav bar, etc.
try {
this.buildLayout(request, next);
} catch (Exception e) {
logger.error("Unable to build default page layout", e);
}
// add link to user page and comments page
WikiUser user = Utilities.currentUser(request);
if (user != null) {
next.addObject("userpage", WikiBase.NAMESPACE_USER + user.getLogin());
next.addObject("usercomments", WikiBase.NAMESPACE_USER_COMMENTS + user.getLogin());
next.addObject("adminUser", new Boolean(user.getAdmin()));
if (Environment.getBooleanValue(Environment.PROP_TOPIC_NON_ADMIN_TOPIC_MOVE) || user.getAdmin()) {
pageInfo.setCanMove(true);
}
}
if (!pageInfo.getSpecial()) {
// FIXME - this is really ugly
String article = pageInfo.getTopicName();
String comments = WikiBase.NAMESPACE_COMMENTS + article;
if (article != null && article.startsWith(WikiBase.NAMESPACE_COMMENTS)) {
int pos = WikiBase.NAMESPACE_COMMENTS.length();
article = article.substring(pos);
comments = WikiBase.NAMESPACE_COMMENTS + article;
} else if (article != null && article.startsWith(WikiBase.NAMESPACE_SPECIAL)) {
int pos = WikiBase.NAMESPACE_SPECIAL.length();
article = article.substring(pos);
comments = WikiBase.NAMESPACE_COMMENTS + article;
} else if (article != null && article.startsWith(WikiBase.NAMESPACE_USER_COMMENTS)) {
int pos = WikiBase.NAMESPACE_USER_COMMENTS.length();
comments = article;
article = WikiBase.NAMESPACE_USER + article.substring(pos);
} else if (article != null && article.startsWith(WikiBase.NAMESPACE_USER)) {
int pos = WikiBase.NAMESPACE_USER.length();
comments = WikiBase.NAMESPACE_USER_COMMENTS + article.substring(pos);
} else if (article != null && article.startsWith(WikiBase.NAMESPACE_IMAGE_COMMENTS)) {
int pos = WikiBase.NAMESPACE_IMAGE_COMMENTS.length();
comments = article;
article = WikiBase.NAMESPACE_IMAGE + article.substring(pos);
} else if (article != null && article.startsWith(WikiBase.NAMESPACE_IMAGE)) {
int pos = WikiBase.NAMESPACE_IMAGE.length();
comments = WikiBase.NAMESPACE_IMAGE_COMMENTS + article.substring(pos);
}
next.addObject("article", article);
next.addObject("comments", comments);
String editLink = "Special:Edit?topic=" + Utilities.encodeURL(pageInfo.getTopicName());
if (StringUtils.hasText(request.getParameter("topicVersionId"))) {
editLink += "&topicVersionId=" + request.getParameter("topicVersionId");
}
next.addObject("edit", editLink);
}
if (!StringUtils.hasText(pageInfo.getTopicName())) {
try {
pageInfo.setTopicName(JAMWikiServlet.getTopicFromURI(request));
} catch (Exception e) {
logger.error("Unable to load topic value in JAMWikiServlet", e);
}
}
next.addObject(PARAMETER_PAGE_INFO, pageInfo);
}
| protected void loadDefaults(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) {
// load cached top area, nav bar, etc.
try {
this.buildLayout(request, next);
} catch (Exception e) {
logger.error("Unable to build default page layout", e);
}
// add link to user page and comments page
WikiUser user = Utilities.currentUser(request);
if (user != null) {
next.addObject("userpage", WikiBase.NAMESPACE_USER + user.getLogin());
next.addObject("usercomments", WikiBase.NAMESPACE_USER_COMMENTS + user.getLogin());
next.addObject("adminUser", new Boolean(user.getAdmin()));
}
if (Environment.getBooleanValue(Environment.PROP_TOPIC_NON_ADMIN_TOPIC_MOVE) || (user != null && user.getAdmin())) {
pageInfo.setCanMove(true);
}
if (!pageInfo.getSpecial()) {
// FIXME - this is really ugly
String article = pageInfo.getTopicName();
String comments = WikiBase.NAMESPACE_COMMENTS + article;
if (article != null && article.startsWith(WikiBase.NAMESPACE_COMMENTS)) {
int pos = WikiBase.NAMESPACE_COMMENTS.length();
article = article.substring(pos);
comments = WikiBase.NAMESPACE_COMMENTS + article;
} else if (article != null && article.startsWith(WikiBase.NAMESPACE_SPECIAL)) {
int pos = WikiBase.NAMESPACE_SPECIAL.length();
article = article.substring(pos);
comments = WikiBase.NAMESPACE_COMMENTS + article;
} else if (article != null && article.startsWith(WikiBase.NAMESPACE_USER_COMMENTS)) {
int pos = WikiBase.NAMESPACE_USER_COMMENTS.length();
comments = article;
article = WikiBase.NAMESPACE_USER + article.substring(pos);
} else if (article != null && article.startsWith(WikiBase.NAMESPACE_USER)) {
int pos = WikiBase.NAMESPACE_USER.length();
comments = WikiBase.NAMESPACE_USER_COMMENTS + article.substring(pos);
} else if (article != null && article.startsWith(WikiBase.NAMESPACE_IMAGE_COMMENTS)) {
int pos = WikiBase.NAMESPACE_IMAGE_COMMENTS.length();
comments = article;
article = WikiBase.NAMESPACE_IMAGE + article.substring(pos);
} else if (article != null && article.startsWith(WikiBase.NAMESPACE_IMAGE)) {
int pos = WikiBase.NAMESPACE_IMAGE.length();
comments = WikiBase.NAMESPACE_IMAGE_COMMENTS + article.substring(pos);
}
next.addObject("article", article);
next.addObject("comments", comments);
String editLink = "Special:Edit?topic=" + Utilities.encodeURL(pageInfo.getTopicName());
if (StringUtils.hasText(request.getParameter("topicVersionId"))) {
editLink += "&topicVersionId=" + request.getParameter("topicVersionId");
}
next.addObject("edit", editLink);
}
if (!StringUtils.hasText(pageInfo.getTopicName())) {
try {
pageInfo.setTopicName(JAMWikiServlet.getTopicFromURI(request));
} catch (Exception e) {
logger.error("Unable to load topic value in JAMWikiServlet", e);
}
}
next.addObject(PARAMETER_PAGE_INFO, pageInfo);
}
|
diff --git a/src/drafto/hmi/DraftDisplay.java b/src/drafto/hmi/DraftDisplay.java
index 8e59f32..330851f 100644
--- a/src/drafto/hmi/DraftDisplay.java
+++ b/src/drafto/hmi/DraftDisplay.java
@@ -1,321 +1,321 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package drafto.hmi;
import drafto.Console;
import drafto.CustomCellRenderer;
import drafto.CustomModel;
import drafto.CustomTable;
import drafto.DraftoMachine;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JFileChooser;
import javax.swing.table.JTableHeader;
/**
*
* @author cbachich
*/
public class DraftDisplay extends javax.swing.JFrame {
// Static Values
private static String START = "Start";
private static String END = "End";
private static String RESUME = "Resume";
private static String PAUSE = "Pause";
// Error Text
private static String BAD_TABLE =
"There is bad data in the table. Please correct!";
// Global Values
private Console console;
private DraftoMachine drafto;
private Thread draftoThread;
/**
* Creates new form DraftDisplay
*/
public DraftDisplay() {
initComponents();
// Setup the console
console = new Console(consoleTextArea);
// Create a custom table
CustomTable pickTable = new CustomTable();
// Create a custom model and allocate it to the pickTable
pickModel = new CustomModel(console);
pickTable.setModel(pickModel);
pickTable.resizeColumns();
// Turn on basic header sorting
pickTable.setAutoCreateRowSorter(true);
// Change the header colors
JTableHeader header = pickTable.getTableHeader();
header.setBackground(new Color(193,205,193));
header.setForeground(new Color(25,25,112));
header.setFont(new Font("Dialog", Font.BOLD, 14));
// Set the custom cell renderer
pickCellRenderer = new CustomCellRenderer();
pickTable.setDefaultRenderer(Object.class, pickCellRenderer);
// Finally set the scroll pane to include the pickTable
pickScrollPane.setViewportView(pickTable);
}
/**
* 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() {
buttonPanel = new javax.swing.JPanel();
startButton = new javax.swing.JButton();
resumeButton = new javax.swing.JButton();
pauseButton = new javax.swing.JButton();
endButton = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
pickPanel = new javax.swing.JPanel();
pickScrollPane = new javax.swing.JScrollPane();
draftoScrollPane = new javax.swing.JScrollPane();
consoleTextArea = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
buttonPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 40, 5));
startButton.setText("Start");
startButton.setPreferredSize(new java.awt.Dimension(80, 30));
startButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startDrafto(evt);
}
});
buttonPanel.add(startButton);
resumeButton.setText("Resume");
resumeButton.setEnabled(false);
- resumeButton.setPreferredSize(new java.awt.Dimension(80, 30));
+ resumeButton.setPreferredSize(new java.awt.Dimension(100, 30));
resumeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
resumeDrafto(evt);
}
});
buttonPanel.add(resumeButton);
pauseButton.setText("Pause");
pauseButton.setEnabled(false);
pauseButton.setPreferredSize(new java.awt.Dimension(80, 30));
pauseButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pauseDrafto(evt);
}
});
buttonPanel.add(pauseButton);
endButton.setText("End");
endButton.setEnabled(false);
endButton.setPreferredSize(new java.awt.Dimension(80, 30));
endButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
endDrafto(evt);
}
});
buttonPanel.add(endButton);
jButton1.setText("Load");
jButton1.setPreferredSize(new java.awt.Dimension(80, 30));
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LoadPicks(evt);
}
});
buttonPanel.add(jButton1);
javax.swing.GroupLayout pickPanelLayout = new javax.swing.GroupLayout(pickPanel);
pickPanel.setLayout(pickPanelLayout);
pickPanelLayout.setHorizontalGroup(
pickPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 710, Short.MAX_VALUE)
.addGroup(pickPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pickScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 710, Short.MAX_VALUE))
);
pickPanelLayout.setVerticalGroup(
pickPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 234, Short.MAX_VALUE)
.addGroup(pickPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pickScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 234, Short.MAX_VALUE))
);
consoleTextArea.setColumns(20);
consoleTextArea.setRows(5);
draftoScrollPane.setViewportView(consoleTextArea);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(draftoScrollPane)
- .addComponent(buttonPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .addComponent(buttonPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addComponent(pickPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(buttonPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(pickPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(draftoScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(30, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void startDrafto(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startDrafto
// Check that the table contains good values. If not, inform the user and do
// not continue
if(!pickModel.isTableGood()) {
console.write(BAD_TABLE);
return;
}
// Toggle the buttons
toggleButtons(START);
// Lock the fields
pickModel.lockCells();
// Create a new pick panel
PickPanel pickPanel = new PickPanel();
draftoScrollPane.setViewportView(pickPanel);
// Start Drafto
drafto = new DraftoMachine(pickPanel, pickModel);
draftoThread = new Thread(drafto);
draftoThread.start();
}//GEN-LAST:event_startDrafto
private void pauseDrafto(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pauseDrafto
// Toggle the buttons
toggleButtons(PAUSE);
// Pause Drafto
drafto.pause();
}//GEN-LAST:event_pauseDrafto
private void resumeDrafto(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resumeDrafto
// Toggle the buttons
toggleButtons(RESUME);
// Resume Drafto
drafto.resume();
}//GEN-LAST:event_resumeDrafto
private void endDrafto(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_endDrafto
// Toggle the buttons
toggleButtons(END);
// Unlock the fields
pickModel.unlockCells();
}//GEN-LAST:event_endDrafto
final JFileChooser fc = new JFileChooser();
private void LoadPicks(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LoadPicks
System.out.println("LoadPicks selected");
int returnVal = fc.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
pickModel.loadPicks(fc.getSelectedFile());
pickModel.fireTableDataChanged();
}
}//GEN-LAST:event_LoadPicks
// Toggle the buttons
private void toggleButtons(String cmd) {
if (cmd.matches(START) || cmd.matches(RESUME)) {
startButton.setEnabled(false);
resumeButton.setEnabled(false);
pauseButton.setEnabled(true);
endButton.setEnabled(false);
} else if (cmd.matches(PAUSE)) {
startButton.setEnabled(false);
resumeButton.setEnabled(true);
pauseButton.setEnabled(false);
endButton.setEnabled(true);
} else if (cmd.matches(END)) {
startButton.setEnabled(true);
resumeButton.setEnabled(false);
pauseButton.setEnabled(false);
endButton.setEnabled(false);
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(DraftDisplay.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DraftDisplay.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DraftDisplay.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DraftDisplay.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new DraftDisplay().setVisible(true);
}
});
}
// Variables decleration - can modify
private CustomModel pickModel;
private CustomCellRenderer pickCellRenderer;
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel buttonPanel;
private javax.swing.JTextArea consoleTextArea;
private javax.swing.JScrollPane draftoScrollPane;
private javax.swing.JButton endButton;
private javax.swing.JButton jButton1;
private javax.swing.JButton pauseButton;
private javax.swing.JPanel pickPanel;
private javax.swing.JScrollPane pickScrollPane;
private javax.swing.JButton resumeButton;
private javax.swing.JButton startButton;
// End of variables declaration//GEN-END:variables
}
| false | true | private void initComponents() {
buttonPanel = new javax.swing.JPanel();
startButton = new javax.swing.JButton();
resumeButton = new javax.swing.JButton();
pauseButton = new javax.swing.JButton();
endButton = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
pickPanel = new javax.swing.JPanel();
pickScrollPane = new javax.swing.JScrollPane();
draftoScrollPane = new javax.swing.JScrollPane();
consoleTextArea = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
buttonPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 40, 5));
startButton.setText("Start");
startButton.setPreferredSize(new java.awt.Dimension(80, 30));
startButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startDrafto(evt);
}
});
buttonPanel.add(startButton);
resumeButton.setText("Resume");
resumeButton.setEnabled(false);
resumeButton.setPreferredSize(new java.awt.Dimension(80, 30));
resumeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
resumeDrafto(evt);
}
});
buttonPanel.add(resumeButton);
pauseButton.setText("Pause");
pauseButton.setEnabled(false);
pauseButton.setPreferredSize(new java.awt.Dimension(80, 30));
pauseButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pauseDrafto(evt);
}
});
buttonPanel.add(pauseButton);
endButton.setText("End");
endButton.setEnabled(false);
endButton.setPreferredSize(new java.awt.Dimension(80, 30));
endButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
endDrafto(evt);
}
});
buttonPanel.add(endButton);
jButton1.setText("Load");
jButton1.setPreferredSize(new java.awt.Dimension(80, 30));
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LoadPicks(evt);
}
});
buttonPanel.add(jButton1);
javax.swing.GroupLayout pickPanelLayout = new javax.swing.GroupLayout(pickPanel);
pickPanel.setLayout(pickPanelLayout);
pickPanelLayout.setHorizontalGroup(
pickPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 710, Short.MAX_VALUE)
.addGroup(pickPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pickScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 710, Short.MAX_VALUE))
);
pickPanelLayout.setVerticalGroup(
pickPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 234, Short.MAX_VALUE)
.addGroup(pickPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pickScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 234, Short.MAX_VALUE))
);
consoleTextArea.setColumns(20);
consoleTextArea.setRows(5);
draftoScrollPane.setViewportView(consoleTextArea);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(draftoScrollPane)
.addComponent(buttonPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(pickPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(buttonPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(pickPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(draftoScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(30, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
buttonPanel = new javax.swing.JPanel();
startButton = new javax.swing.JButton();
resumeButton = new javax.swing.JButton();
pauseButton = new javax.swing.JButton();
endButton = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
pickPanel = new javax.swing.JPanel();
pickScrollPane = new javax.swing.JScrollPane();
draftoScrollPane = new javax.swing.JScrollPane();
consoleTextArea = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
buttonPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 40, 5));
startButton.setText("Start");
startButton.setPreferredSize(new java.awt.Dimension(80, 30));
startButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startDrafto(evt);
}
});
buttonPanel.add(startButton);
resumeButton.setText("Resume");
resumeButton.setEnabled(false);
resumeButton.setPreferredSize(new java.awt.Dimension(100, 30));
resumeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
resumeDrafto(evt);
}
});
buttonPanel.add(resumeButton);
pauseButton.setText("Pause");
pauseButton.setEnabled(false);
pauseButton.setPreferredSize(new java.awt.Dimension(80, 30));
pauseButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pauseDrafto(evt);
}
});
buttonPanel.add(pauseButton);
endButton.setText("End");
endButton.setEnabled(false);
endButton.setPreferredSize(new java.awt.Dimension(80, 30));
endButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
endDrafto(evt);
}
});
buttonPanel.add(endButton);
jButton1.setText("Load");
jButton1.setPreferredSize(new java.awt.Dimension(80, 30));
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LoadPicks(evt);
}
});
buttonPanel.add(jButton1);
javax.swing.GroupLayout pickPanelLayout = new javax.swing.GroupLayout(pickPanel);
pickPanel.setLayout(pickPanelLayout);
pickPanelLayout.setHorizontalGroup(
pickPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 710, Short.MAX_VALUE)
.addGroup(pickPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pickScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 710, Short.MAX_VALUE))
);
pickPanelLayout.setVerticalGroup(
pickPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 234, Short.MAX_VALUE)
.addGroup(pickPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pickScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 234, Short.MAX_VALUE))
);
consoleTextArea.setColumns(20);
consoleTextArea.setRows(5);
draftoScrollPane.setViewportView(consoleTextArea);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(draftoScrollPane)
.addComponent(buttonPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addComponent(pickPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(buttonPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(pickPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(draftoScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(30, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/org/apache/xerces/impl/xs/traversers/XSDHandler.java b/src/org/apache/xerces/impl/xs/traversers/XSDHandler.java
index 090dfad2..4b946aee 100644
--- a/src/org/apache/xerces/impl/xs/traversers/XSDHandler.java
+++ b/src/org/apache/xerces/impl/xs/traversers/XSDHandler.java
@@ -1,2091 +1,2091 @@
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xerces.impl.xs.traversers;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Stack;
import java.util.Vector;
import org.apache.xerces.impl.Constants;
import org.apache.xerces.impl.XMLEntityManager;
import org.apache.xerces.impl.XMLErrorReporter;
import org.apache.xerces.impl.xs.SchemaGrammar;
import org.apache.xerces.impl.xs.SchemaNamespaceSupport;
import org.apache.xerces.impl.xs.SchemaSymbols;
import org.apache.xerces.impl.xs.XMLSchemaException;
import org.apache.xerces.impl.xs.XMLSchemaLoader;
import org.apache.xerces.impl.xs.XSComplexTypeDecl;
import org.apache.xerces.impl.xs.XSDDescription;
import org.apache.xerces.impl.xs.XSDeclarationPool;
import org.apache.xerces.impl.xs.XSElementDecl;
import org.apache.xerces.impl.xs.XSGrammarBucket;
import org.apache.xerces.impl.xs.XSMessageFormatter;
import org.apache.xerces.impl.xs.XSParticleDecl;
import org.apache.xerces.impl.xs.dom.ElementNSImpl;
import org.apache.xerces.impl.xs.opti.ElementImpl;
import org.apache.xerces.impl.xs.opti.SchemaParsingConfig;
import org.apache.xerces.impl.xs.util.SimpleLocator;
import org.apache.xerces.util.DOMUtil;
import org.apache.xerces.util.SymbolTable;
import org.apache.xerces.util.XMLSymbols;
import org.apache.xerces.xni.QName;
import org.apache.xerces.xni.grammars.XMLGrammarPool;
import org.apache.xerces.xni.parser.XMLEntityResolver;
import org.apache.xerces.xni.parser.XMLErrorHandler;
import org.apache.xerces.xni.parser.XMLInputSource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* The purpose of this class is to co-ordinate the construction of a
* grammar object corresponding to a schema. To do this, it must be
* prepared to parse several schema documents (for instance if the
* schema document originally referred to contains <include> or
* <redefined> information items). If any of the schemas imports a
* schema, other grammars may be constructed as a side-effect.
*
* @author Neil Graham, IBM
* @author Pavani Mukthipudi, Sun Microsystems
* @version $Id$
*/
public class XSDHandler {
/** Feature identifier: allow java encodings */
protected static final String ALLOW_JAVA_ENCODINGS =
Constants.XERCES_FEATURE_PREFIX + Constants.ALLOW_JAVA_ENCODINGS_FEATURE;
/** Feature identifier: continue after fatal error */
protected static final String CONTINUE_AFTER_FATAL_ERROR =
Constants.XERCES_FEATURE_PREFIX + Constants.CONTINUE_AFTER_FATAL_ERROR_FEATURE;
/** Feature identifier: allow java encodings */
protected static final String STANDARD_URI_CONFORMANT_FEATURE =
Constants.XERCES_FEATURE_PREFIX + Constants.STANDARD_URI_CONFORMANT_FEATURE;
/** Property identifier: error handler. */
protected static final String ERROR_HANDLER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_HANDLER_PROPERTY;
/** Property identifier: JAXP schema source. */
protected static final String JAXP_SCHEMA_SOURCE =
Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_SOURCE;
/** Property identifier: entity resolver. */
public static final String ENTITY_RESOLVER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_RESOLVER_PROPERTY;
protected static final boolean DEBUG_NODE_POOL = false;
// Data
// different sorts of declarations; should make lookup and
// traverser calling more efficient/less bulky.
final static int ATTRIBUTE_TYPE = 1;
final static int ATTRIBUTEGROUP_TYPE = 2;
final static int ELEMENT_TYPE = 3;
final static int GROUP_TYPE = 4;
final static int IDENTITYCONSTRAINT_TYPE = 5;
final static int NOTATION_TYPE = 6;
final static int TYPEDECL_TYPE = 7;
// this string gets appended to redefined names; it's purpose is to be
// as unlikely as possible to cause collisions.
public final static String REDEF_IDENTIFIER = "_fn3dktizrknc9pi";
//
//protected data that can be accessable by any traverser
// stores <notation> decl
protected Hashtable fNotationRegistry = new Hashtable();
protected XSDeclarationPool fDeclPool = null;
// are java encodings allowed?
private boolean fAllowJavaEncodings = false;
// enforcing strict uri?
private boolean fStrictURI = false;
// These tables correspond to the symbol spaces defined in the
// spec.
// They are keyed with a QName (that is, String("URI,localpart) and
// their values are nodes corresponding to the given name's decl.
// By asking the node for its ownerDocument and looking in
// XSDocumentInfoRegistry we can easily get the corresponding
// XSDocumentInfo object.
private Hashtable fUnparsedAttributeRegistry = new Hashtable();
private Hashtable fUnparsedAttributeGroupRegistry = new Hashtable();
private Hashtable fUnparsedElementRegistry = new Hashtable();
private Hashtable fUnparsedGroupRegistry = new Hashtable();
private Hashtable fUnparsedIdentityConstraintRegistry = new Hashtable();
private Hashtable fUnparsedNotationRegistry = new Hashtable();
private Hashtable fUnparsedTypeRegistry = new Hashtable();
// this is keyed with a documentNode (or the schemaRoot nodes
// contained in the XSDocumentInfo objects) and its value is the
// XSDocumentInfo object corresponding to that document.
// Basically, the function of this registry is to be a link
// between the nodes we fetch from calls to the fUnparsed*
// arrays and the XSDocumentInfos they live in.
private Hashtable fXSDocumentInfoRegistry = new Hashtable();
// this hashtable is keyed on by XSDocumentInfo objects. Its values
// are Vectors containing the XSDocumentInfo objects <include>d,
// <import>ed or <redefine>d by the key XSDocumentInfo.
private Hashtable fDependencyMap = new Hashtable();
// this hashtable is keyed on by a target namespace. Its values
// are Vectors containing namespaces imported by schema documents
// with the key target namespace.
// if an imprted schema has absent namespace, the value "null" is stored.
private Hashtable fImportMap = new Hashtable();
// all namespaces that imports other namespaces
// if the importing schema has absent namespace, empty string is stored.
// (because the key of a hashtable can't be null.)
private Vector fAllTNSs = new Vector();
// stores instance document mappings between namespaces and schema hints
private Hashtable fLocationPairs = null;
// convenience methods
private String null2EmptyString(String ns) {
return ns == null ? XMLSymbols.EMPTY_STRING : ns;
}
private String emptyString2Null(String ns) {
return ns == XMLSymbols.EMPTY_STRING ? null : ns;
}
// This vector stores strings which are combinations of the
// publicId and systemId of the inputSource corresponding to a
// schema document. This combination is used so that the user's
// EntityResolver can provide a consistent way of identifying a
// schema document that is included in multiple other schemas.
private Hashtable fTraversed = new Hashtable();
// this hashtable contains a mapping from Document to its systemId
// this is useful to resolve a uri relative to the referring document
private Hashtable fDoc2SystemId = new Hashtable();
// the primary XSDocumentInfo we were called to parse
private XSDocumentInfo fRoot = null;
// This hashtable's job is to act as a link between the document
// node at the root of the parsed schema's tree and its
// XSDocumentInfo object.
private Hashtable fDoc2XSDocumentMap = new Hashtable();
// map between <redefine> elements and the XSDocumentInfo
// objects that correspond to the documents being redefined.
private Hashtable fRedefine2XSDMap = new Hashtable();
// map between <redefine> elements and the namespace support
private Hashtable fRedefine2NSSupport = new Hashtable();
// these objects store a mapping between the names of redefining
// groups/attributeGroups and the groups/AttributeGroups which
// they redefine by restriction (implicitly). It is up to the
// Group and AttributeGroup traversers to check these restrictions for
// validity.
private Hashtable fRedefinedRestrictedAttributeGroupRegistry = new Hashtable();
private Hashtable fRedefinedRestrictedGroupRegistry = new Hashtable();
// a variable storing whether the last schema document
// processed (by getSchema) was a duplicate.
private boolean fLastSchemaWasDuplicate;
// the XMLErrorReporter
private XMLErrorReporter fErrorReporter;
private XMLEntityResolver fEntityResolver;
// the XSAttributeChecker
private XSAttributeChecker fAttributeChecker;
// the symbol table
private SymbolTable fSymbolTable;
// the GrammarResolver
private XSGrammarBucket fGrammarBucket;
// the Grammar description
private XSDDescription fSchemaGrammarDescription;
// the Grammar Pool
private XMLGrammarPool fGrammarPool;
//************ Traversers **********
XSDAttributeGroupTraverser fAttributeGroupTraverser;
XSDAttributeTraverser fAttributeTraverser;
XSDComplexTypeTraverser fComplexTypeTraverser;
XSDElementTraverser fElementTraverser;
XSDGroupTraverser fGroupTraverser;
XSDKeyrefTraverser fKeyrefTraverser;
XSDNotationTraverser fNotationTraverser;
XSDSimpleTypeTraverser fSimpleTypeTraverser;
XSDUniqueOrKeyTraverser fUniqueOrKeyTraverser;
XSDWildcardTraverser fWildCardTraverser;
//DOMParser fSchemaParser;
SchemaParsingConfig fSchemaParser;
// these data members are needed for the deferred traversal
// of local elements.
// the initial size of the array to store deferred local elements
private static final int INIT_STACK_SIZE = 30;
// the incremental size of the array to store deferred local elements
private static final int INC_STACK_SIZE = 10;
// current position of the array (# of deferred local elements)
private int fLocalElemStackPos = 0;
private XSParticleDecl[] fParticle = new XSParticleDecl[INIT_STACK_SIZE];
private Element[] fLocalElementDecl = new Element[INIT_STACK_SIZE];
private int[] fAllContext = new int[INIT_STACK_SIZE];
private XSComplexTypeDecl[] fEnclosingCT = new XSComplexTypeDecl[INIT_STACK_SIZE];
private String [][] fLocalElemNamespaceContext = new String [INIT_STACK_SIZE][1];
// these data members are needed for the deferred traversal
// of keyrefs.
// the initial size of the array to store deferred keyrefs
private static final int INIT_KEYREF_STACK = 2;
// the incremental size of the array to store deferred keyrefs
private static final int INC_KEYREF_STACK_AMOUNT = 2;
// current position of the array (# of deferred keyrefs)
private int fKeyrefStackPos = 0;
private Element [] fKeyrefs = new Element[INIT_KEYREF_STACK];
private XSElementDecl [] fKeyrefElems = new XSElementDecl [INIT_KEYREF_STACK];
private String [][] fKeyrefNamespaceContext = new String[INIT_KEYREF_STACK][1];
// Constructors
// it should be possible to use the same XSDHandler to parse
// multiple schema documents; this will allow one to be
// constructed.
public XSDHandler (XSGrammarBucket gBucket) {
fGrammarBucket = gBucket;
// Note: don't use SchemaConfiguration internally
// we will get stack overflaw because
// XMLSchemaValidator will be instantiating XSDHandler...
fSchemaGrammarDescription = new XSDDescription();
} // end constructor
// This method initiates the parse of a schema. It will likely be
// called from the Validator and it will make the
// resulting grammar available; it returns a reference to this object just
// in case. An ErrorHandler, EntityResolver, XSGrammarBucket and SymbolTable must
// already have been set; the last thing this method does is reset
// this object (i.e., clean the registries, etc.).
public SchemaGrammar parseSchema(XMLInputSource is, XSDDescription desc,
Hashtable locationPairs)
throws IOException {
fLocationPairs = locationPairs;
// first try to find it in the bucket/pool, return if one is found
SchemaGrammar grammar = findGrammar(desc);
if (grammar != null)
return grammar;
if (fSchemaParser != null) {
fSchemaParser.resetNodePool();
}
short referType = desc.getContextType();
String schemaNamespace = desc.getTargetNamespace();
// handle empty string URI as null
if (schemaNamespace != null) {
schemaNamespace = fSymbolTable.addSymbol(schemaNamespace);
}
// before parsing a schema, need to clear registries associated with
// parsing schemas
prepareForParse();
// first phase: construct trees.
Document schemaRoot = getSchema(schemaNamespace, is,
referType == XSDDescription.CONTEXT_PREPARSE,
referType, null);
if (schemaRoot == null) {
// something went wrong right off the hop
return null;
}
if ( schemaNamespace == null && referType == XSDDescription.CONTEXT_PREPARSE) {
Element schemaElem = DOMUtil.getRoot(schemaRoot);
schemaNamespace = DOMUtil.getAttrValue(schemaElem, SchemaSymbols.ATT_TARGETNAMESPACE);
if(schemaNamespace != null && schemaNamespace.length() > 0) {
schemaNamespace = fSymbolTable.addSymbol(schemaNamespace);
desc.setTargetNamespace(schemaNamespace);
String schemaId = XMLEntityManager.expandSystemId(desc.getLiteralSystemId(), desc.getBaseSystemId(), false);
XSDKey key = new XSDKey(schemaId, referType, schemaNamespace);
fTraversed.put(key, schemaRoot );
if (schemaId != null) {
fDoc2SystemId.put(schemaRoot, schemaId );
}
}
}
// before constructing trees and traversing a schema, need to reset
// all traversers and clear all registries
prepareForTraverse();
fRoot = constructTrees(schemaRoot, is.getSystemId(), desc);
if (fRoot == null) {
return null;
}
// second phase: fill global registries.
buildGlobalNameRegistries();
// third phase: call traversers
traverseSchemas();
// fourth phase: handle local element decls
traverseLocalElements();
// fifth phase: handle Keyrefs
resolveKeyRefs();
// sixth phase: validate attribute of non-schema namespaces
// REVISIT: skip this for now. we really don't want to do it.
//fAttributeChecker.checkNonSchemaAttributes(fGrammarBucket);
// seventh phase: store imported grammars
// for all grammars with <import>s
for (int i = fAllTNSs.size() - 1; i >= 0; i--) {
// get its target namespace
String tns = (String)fAllTNSs.elementAt(i);
// get all namespaces it imports
Vector ins = (Vector)fImportMap.get(tns);
// get the grammar
SchemaGrammar sg = fGrammarBucket.getGrammar(emptyString2Null(tns));
if (sg == null)
continue;
SchemaGrammar isg;
// for imported namespace
int count = 0;
for (int j = 0; j < ins.size(); j++) {
// get imported grammar
isg = fGrammarBucket.getGrammar((String)ins.elementAt(j));
// reuse the same vector
if (isg != null)
ins.setElementAt(isg, count++);
}
ins.setSize(count);
// set the imported grammars
sg.setImportedGrammars(ins);
}
// and return.
return fGrammarBucket.getGrammar(fRoot.fTargetNamespace);
} // end parseSchema
/**
* First try to find a grammar in the bucket, if failed, consult the
* grammar pool. If a grammar is found in the pool, then add it (and all
* imported ones) into the bucket.
*/
protected SchemaGrammar findGrammar(XSDDescription desc) {
SchemaGrammar sg = fGrammarBucket.getGrammar(desc.getTargetNamespace());
if (sg == null) {
if (fGrammarPool != null) {
sg = (SchemaGrammar)fGrammarPool.retrieveGrammar(desc);
if (sg != null) {
// put this grammar into the bucket, along with grammars
// imported by it (directly or indirectly)
if (!fGrammarBucket.putGrammar(sg, true)) {
// REVISIT: a conflict between new grammar(s) and grammars
// in the bucket. What to do? A warning? An exception?
reportSchemaWarning("GrammarConflict", null, null);
sg = null;
}
}
}
}
return sg;
}
// may wish to have setter methods for ErrorHandler,
// EntityResolver...
private static final String[][] NS_ERROR_CODES = {
{"src-include.2.1", "src-include.2.1"},
{"src-redefine.3.1", "src-redefine.3.1"},
{"src-import.3.1", "src-import.3.2"},
null,
{"TargetNamespace.1", "TargetNamespace.2"},
{"TargetNamespace.1", "TargetNamespace.2"},
{"TargetNamespace.1", "TargetNamespace.2"},
{"TargetNamespace.1", "TargetNamespace.2"}
};
private static final String[] ELE_ERROR_CODES = {
"src-include.1", "src-redefine.2", "src-import.2", "schema_reference.4",
"schema_reference.4", "schema_reference.4", "schema_reference.4", "schema_reference.4"
};
// This method does several things:
// It constructs an instance of an XSDocumentInfo object using the
// schemaRoot node. Then, for each <include>,
// <redefine>, and <import> children, it attempts to resolve the
// requested schema document, initiates a DOM parse, and calls
// itself recursively on that document's root. It also records in
// the DependencyMap object what XSDocumentInfo objects its XSDocumentInfo
// depends on.
// It also makes sure the targetNamespace of the schema it was
// called to parse is correct.
protected XSDocumentInfo constructTrees(Document schemaRoot, String locationHint, XSDDescription desc) {
if (schemaRoot == null) return null;
String callerTNS = desc.getTargetNamespace();
short referType = desc.getContextType();
XSDocumentInfo currSchemaInfo = null;
try {
currSchemaInfo = new XSDocumentInfo(schemaRoot, fAttributeChecker, fSymbolTable);
} catch (XMLSchemaException se) {
reportSchemaError(ELE_ERROR_CODES[referType],
new Object[]{locationHint},
DOMUtil.getRoot(schemaRoot));
return null;
}
// targetNamespace="" is not valid, issue a warning, and ignore it
if (currSchemaInfo.fTargetNamespace != null &&
currSchemaInfo.fTargetNamespace.length() == 0) {
reportSchemaWarning("EmptyTargetNamespace",
new Object[]{locationHint},
DOMUtil.getRoot(schemaRoot));
currSchemaInfo.fTargetNamespace = null;
}
if (callerTNS != null) {
// the second index to the NS_ERROR_CODES array
// if the caller/expected NS is not absent, we use the first column
int secondIdx = 0;
// for include and redefine
if (referType == XSDDescription.CONTEXT_INCLUDE ||
referType == XSDDescription.CONTEXT_REDEFINE) {
// if the referred document has no targetNamespace,
// it's a chameleon schema
if (currSchemaInfo.fTargetNamespace == null) {
currSchemaInfo.fTargetNamespace = callerTNS;
currSchemaInfo.fIsChameleonSchema = true;
}
// if the referred document has a target namespace differing
// from the caller, it's an error
else if (callerTNS != currSchemaInfo.fTargetNamespace) {
reportSchemaError(NS_ERROR_CODES[referType][secondIdx],
new Object [] {callerTNS, currSchemaInfo.fTargetNamespace},
DOMUtil.getRoot(schemaRoot));
return null;
}
}
// for instance and import, the two NS's must be the same
else if (referType != XSDDescription.CONTEXT_PREPARSE && callerTNS != currSchemaInfo.fTargetNamespace) {
reportSchemaError(NS_ERROR_CODES[referType][secondIdx],
new Object [] {callerTNS, currSchemaInfo.fTargetNamespace},
DOMUtil.getRoot(schemaRoot));
return null;
}
}
// now there is no caller/expected NS, it's an error for the referred
// document to have a target namespace, unless we are preparsing a schema
else if (currSchemaInfo.fTargetNamespace != null) {
// set the target namespace of the description
if (referType == XSDDescription.CONTEXT_PREPARSE) {
desc.setTargetNamespace(currSchemaInfo.fTargetNamespace);
callerTNS = currSchemaInfo.fTargetNamespace;
}
else {
// the second index to the NS_ERROR_CODES array
// if the caller/expected NS is absent, we use the second column
int secondIdx = 1;
reportSchemaError(NS_ERROR_CODES[referType][secondIdx],
new Object [] {callerTNS, currSchemaInfo.fTargetNamespace},
DOMUtil.getRoot(schemaRoot));
return null;
}
}
// the other cases (callerTNS == currSchemaInfo.fTargetNamespce == null)
// are valid
// a schema document can always access it's own target namespace
currSchemaInfo.addAllowedNS(currSchemaInfo.fTargetNamespace);
SchemaGrammar sg = null;
if (referType == XSDDescription.CONTEXT_INCLUDE ||
referType == XSDDescription.CONTEXT_REDEFINE) {
sg = fGrammarBucket.getGrammar(currSchemaInfo.fTargetNamespace);
}
else {
sg = new SchemaGrammar(currSchemaInfo.fTargetNamespace, desc.makeClone());
fGrammarBucket.putGrammar(sg);
}
// store the document and its location
// REVISIT: don't expose the DOM tree
//sg.addDocument(currSchemaInfo.fSchemaDoc, (String)fDoc2SystemId.get(currSchemaInfo));
- sg.addDocument(null, (String)fDoc2SystemId.get(currSchemaInfo));
+ sg.addDocument(null, (String)fDoc2SystemId.get(currSchemaInfo.fSchemaDoc));
fDoc2XSDocumentMap.put(schemaRoot, currSchemaInfo);
Vector dependencies = new Vector();
Element rootNode = DOMUtil.getRoot(schemaRoot);
Document newSchemaRoot = null;
for (Element child = DOMUtil.getFirstChildElement(rootNode);
child != null;
child = DOMUtil.getNextSiblingElement(child)) {
String schemaNamespace=null;
String schemaHint=null;
String localName = DOMUtil.getLocalName(child);
short refType = -1;
if (localName.equals(SchemaSymbols.ELT_ANNOTATION))
continue;
else if (localName.equals(SchemaSymbols.ELT_IMPORT)) {
refType = XSDDescription.CONTEXT_IMPORT;
// have to handle some validation here too!
// call XSAttributeChecker to fill in attrs
Object[] includeAttrs = fAttributeChecker.checkAttributes(child, true, currSchemaInfo);
schemaHint = (String)includeAttrs[XSAttributeChecker.ATTIDX_SCHEMALOCATION];
schemaNamespace = (String)includeAttrs[XSAttributeChecker.ATTIDX_NAMESPACE];
if (schemaNamespace != null)
schemaNamespace = fSymbolTable.addSymbol(schemaNamespace);
// a document can't import another document with the same namespace
if (schemaNamespace == currSchemaInfo.fTargetNamespace) {
reportSchemaError("src-import.1.1", new Object [] {schemaNamespace}, child);
}
fAttributeChecker.returnAttrArray(includeAttrs, currSchemaInfo);
// if this namespace has been imported by this document,
// ignore the <import> statement
if (currSchemaInfo.isAllowedNS(schemaNamespace))
continue;
// a schema document can access it's imported namespaces
currSchemaInfo.addAllowedNS(schemaNamespace);
// also record the fact that one namespace imports another one
// convert null to ""
String tns = null2EmptyString(currSchemaInfo.fTargetNamespace);
// get all namespaces imported by this one
Vector ins = (Vector)fImportMap.get(tns);
// if no namespace was imported, create new Vector
if (ins == null) {
// record that this one imports other(s)
fAllTNSs.addElement(tns);
ins = new Vector();
fImportMap.put(tns, ins);
ins.addElement(schemaNamespace);
}
else if (!ins.contains(schemaNamespace)){
ins.addElement(schemaNamespace);
}
fSchemaGrammarDescription.reset();
fSchemaGrammarDescription.setContextType(XSDDescription.CONTEXT_IMPORT);
fSchemaGrammarDescription.setBaseSystemId((String)fDoc2SystemId.get(schemaRoot));
fSchemaGrammarDescription.setLocationHints(new String[]{schemaHint});
fSchemaGrammarDescription.setTargetNamespace(schemaNamespace);
// if a grammar with the same namespace exists (or being
// built), ignore this one (don't traverse it).
if (findGrammar(fSchemaGrammarDescription) != null)
continue;
newSchemaRoot = getSchema(fSchemaGrammarDescription, false, child);
}
else if ((localName.equals(SchemaSymbols.ELT_INCLUDE)) ||
(localName.equals(SchemaSymbols.ELT_REDEFINE))) {
// validation for redefine/include will be the same here; just
// make sure TNS is right (don't care about redef contents
// yet).
Object[] includeAttrs = fAttributeChecker.checkAttributes(child, true, currSchemaInfo);
schemaHint = (String)includeAttrs[XSAttributeChecker.ATTIDX_SCHEMALOCATION];
// store the namespace decls of the redefine element
if (localName.equals(SchemaSymbols.ELT_REDEFINE)) {
fRedefine2NSSupport.put(child, new SchemaNamespaceSupport(currSchemaInfo.fNamespaceSupport));
}
fAttributeChecker.returnAttrArray(includeAttrs, currSchemaInfo);
// schemaLocation is required on <include> and <redefine>
if (schemaHint == null) {
reportSchemaError("s4s-att-must-appear", new Object [] {
"<include> or <redefine>", "schemaLocation"},
child);
}
// pass the systemId of the current document as the base systemId
boolean mustResolve = false;
refType = XSDDescription.CONTEXT_INCLUDE;
if(localName.equals(SchemaSymbols.ELT_REDEFINE)) {
mustResolve = nonAnnotationContent(child);
refType = XSDDescription.CONTEXT_REDEFINE;
}
fSchemaGrammarDescription.reset();
fSchemaGrammarDescription.setContextType(refType);
fSchemaGrammarDescription.setBaseSystemId((String)fDoc2SystemId.get(schemaRoot));
fSchemaGrammarDescription.setLocationHints(new String[]{schemaHint});
fSchemaGrammarDescription.setTargetNamespace(callerTNS);
newSchemaRoot = getSchema(fSchemaGrammarDescription, mustResolve, child);
schemaNamespace = currSchemaInfo.fTargetNamespace;
}
else {
// no more possibility of schema references in well-formed
// schema...
break;
}
// If the schema is duplicate, we needn't call constructTrees() again.
// To handle mutual <include>s
XSDocumentInfo newSchemaInfo = null;
if (fLastSchemaWasDuplicate) {
newSchemaInfo = (XSDocumentInfo)fDoc2XSDocumentMap.get(newSchemaRoot);
}
else {
newSchemaInfo = constructTrees(newSchemaRoot, schemaHint, fSchemaGrammarDescription);
}
if (localName.equals(SchemaSymbols.ELT_REDEFINE) &&
newSchemaInfo != null) {
// must record which schema we're redefining so that we can
// rename the right things later!
fRedefine2XSDMap.put(child, newSchemaInfo);
}
if (newSchemaRoot != null) {
if (newSchemaInfo != null)
dependencies.addElement(newSchemaInfo);
newSchemaRoot = null;
}
}
fDependencyMap.put(currSchemaInfo, dependencies);
return currSchemaInfo;
} // end constructTrees
// This method builds registries for all globally-referenceable
// names. A registry will be built for each symbol space defined
// by the spec. It is also this method's job to rename redefined
// components, and to record which components redefine others (so
// that implicit redefinitions of groups and attributeGroups can be handled).
protected void buildGlobalNameRegistries() {
/* Starting with fRoot, we examine each child of the schema
* element. Skipping all imports and includes, we record the names
* of all other global components (and children of <redefine>). We
* also put <redefine> names in a registry that we look through in
* case something needs renaming. Once we're done with a schema we
* set its Document node to hidden so that we don't try to traverse
* it again; then we look to its Dependency map entry. We keep a
* stack of schemas that we haven't yet finished processing; this
* is a depth-first traversal.
*/
Stack schemasToProcess = new Stack();
schemasToProcess.push(fRoot);
while (!schemasToProcess.empty()) {
XSDocumentInfo currSchemaDoc =
(XSDocumentInfo)schemasToProcess.pop();
Document currDoc = currSchemaDoc.fSchemaDoc;
if (DOMUtil.isHidden(currDoc)) {
// must have processed this already!
continue;
}
Element currRoot = DOMUtil.getRoot(currDoc);
// process this schema's global decls
boolean dependenciesCanOccur = true;
for (Element globalComp =
DOMUtil.getFirstChildElement(currRoot);
globalComp != null;
globalComp = DOMUtil.getNextSiblingElement(globalComp)) {
// this loop makes sure the <schema> element ordering is
// also valid.
if (DOMUtil.getLocalName(globalComp).equals(SchemaSymbols.ELT_ANNOTATION)) {
//skip it; traverse it later
continue;
}
else if (DOMUtil.getLocalName(globalComp).equals(SchemaSymbols.ELT_INCLUDE) ||
DOMUtil.getLocalName(globalComp).equals(SchemaSymbols.ELT_IMPORT)) {
if (!dependenciesCanOccur) {
reportSchemaError("sch-props-correct.1", new Object [] {DOMUtil.getLocalName(globalComp)}, globalComp);
}
// we've dealt with this; mark as traversed
DOMUtil.setHidden(globalComp);
}
else if (DOMUtil.getLocalName(globalComp).equals(SchemaSymbols.ELT_REDEFINE)) {
if (!dependenciesCanOccur) {
reportSchemaError("sch-props-correct.1", new Object [] {DOMUtil.getLocalName(globalComp)}, globalComp);
}
for (Element redefineComp = DOMUtil.getFirstChildElement(globalComp);
redefineComp != null;
redefineComp = DOMUtil.getNextSiblingElement(redefineComp)) {
String lName = DOMUtil.getAttrValue(redefineComp, SchemaSymbols.ATT_NAME);
if (lName.length() == 0) // an error we'll catch later
continue;
String qName = currSchemaDoc.fTargetNamespace == null ?
","+lName:
currSchemaDoc.fTargetNamespace +","+lName;
String componentType = DOMUtil.getLocalName(redefineComp);
if (componentType.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) {
checkForDuplicateNames(qName, fUnparsedAttributeGroupRegistry, redefineComp, currSchemaDoc);
// the check will have changed our name;
String targetLName = DOMUtil.getAttrValue(redefineComp, SchemaSymbols.ATT_NAME)+REDEF_IDENTIFIER;
// and all we need to do is error-check+rename our kkids:
renameRedefiningComponents(currSchemaDoc, redefineComp, SchemaSymbols.ELT_ATTRIBUTEGROUP,
lName, targetLName);
}
else if ((componentType.equals(SchemaSymbols.ELT_COMPLEXTYPE)) ||
(componentType.equals(SchemaSymbols.ELT_SIMPLETYPE))) {
checkForDuplicateNames(qName, fUnparsedTypeRegistry, redefineComp, currSchemaDoc);
// the check will have changed our name;
String targetLName = DOMUtil.getAttrValue(redefineComp, SchemaSymbols.ATT_NAME) + REDEF_IDENTIFIER;
// and all we need to do is error-check+rename our kkids:
if (componentType.equals(SchemaSymbols.ELT_COMPLEXTYPE)) {
renameRedefiningComponents(currSchemaDoc, redefineComp, SchemaSymbols.ELT_COMPLEXTYPE,
lName, targetLName);
}
else { // must be simpleType
renameRedefiningComponents(currSchemaDoc, redefineComp, SchemaSymbols.ELT_SIMPLETYPE,
lName, targetLName);
}
}
else if (componentType.equals(SchemaSymbols.ELT_GROUP)) {
checkForDuplicateNames(qName, fUnparsedGroupRegistry, redefineComp, currSchemaDoc);
// the check will have changed our name;
String targetLName = DOMUtil.getAttrValue(redefineComp, SchemaSymbols.ATT_NAME)+REDEF_IDENTIFIER;
// and all we need to do is error-check+rename our kids:
renameRedefiningComponents(currSchemaDoc, redefineComp, SchemaSymbols.ELT_GROUP,
lName, targetLName);
}
} // end march through <redefine> children
// and now set as traversed
//DOMUtil.setHidden(globalComp);
}
else {
dependenciesCanOccur = false;
String lName = DOMUtil.getAttrValue(globalComp, SchemaSymbols.ATT_NAME);
if (lName.length() == 0) // an error we'll catch later
continue;
String qName = currSchemaDoc.fTargetNamespace == null?
","+lName:
currSchemaDoc.fTargetNamespace +","+lName;
String componentType = DOMUtil.getLocalName(globalComp);
if (componentType.equals(SchemaSymbols.ELT_ATTRIBUTE)) {
checkForDuplicateNames(qName, fUnparsedAttributeRegistry, globalComp, currSchemaDoc);
}
else if (componentType.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) {
checkForDuplicateNames(qName, fUnparsedAttributeGroupRegistry, globalComp, currSchemaDoc);
}
else if ((componentType.equals(SchemaSymbols.ELT_COMPLEXTYPE)) ||
(componentType.equals(SchemaSymbols.ELT_SIMPLETYPE))) {
checkForDuplicateNames(qName, fUnparsedTypeRegistry, globalComp, currSchemaDoc);
}
else if (componentType.equals(SchemaSymbols.ELT_ELEMENT)) {
checkForDuplicateNames(qName, fUnparsedElementRegistry, globalComp, currSchemaDoc);
}
else if (componentType.equals(SchemaSymbols.ELT_GROUP)) {
checkForDuplicateNames(qName, fUnparsedGroupRegistry, globalComp, currSchemaDoc);
}
else if (componentType.equals(SchemaSymbols.ELT_NOTATION)) {
checkForDuplicateNames(qName, fUnparsedNotationRegistry, globalComp, currSchemaDoc);
}
}
} // end for
// now we're done with this one!
DOMUtil.setHidden(currDoc);
// now add the schemas this guy depends on
Vector currSchemaDepends = (Vector)fDependencyMap.get(currSchemaDoc);
for (int i = 0; i < currSchemaDepends.size(); i++) {
schemasToProcess.push(currSchemaDepends.elementAt(i));
}
} // while
} // end buildGlobalNameRegistries
// Beginning at the first schema processing was requested for
// (fRoot), this method
// examines each child (global schema information item) of each
// schema document (and of each <redefine> element)
// corresponding to an XSDocumentInfo object. If the
// readOnly field on that node has not been set, it calls an
// appropriate traverser to traverse it. Once all global decls in
// an XSDocumentInfo object have been traversed, it marks that object
// as traversed (or hidden) in order to avoid infinite loops. It completes
// when it has visited all XSDocumentInfo objects in the
// DependencyMap and marked them as traversed.
protected void traverseSchemas() {
// the process here is very similar to that in
// buildGlobalRegistries, except we can't set our schemas as
// hidden for a second time; so make them all visible again
// first!
setSchemasVisible(fRoot);
Stack schemasToProcess = new Stack();
schemasToProcess.push(fRoot);
while (!schemasToProcess.empty()) {
XSDocumentInfo currSchemaDoc =
(XSDocumentInfo)schemasToProcess.pop();
Document currDoc = currSchemaDoc.fSchemaDoc;
SchemaGrammar currSG = fGrammarBucket.getGrammar(currSchemaDoc.fTargetNamespace);
if (DOMUtil.isHidden(currDoc)) {
// must have processed this already!
continue;
}
Element currRoot = DOMUtil.getRoot(currDoc);
// traverse this schema's global decls
for (Element globalComp =
DOMUtil.getFirstVisibleChildElement(currRoot);
globalComp != null;
globalComp = DOMUtil.getNextVisibleSiblingElement(globalComp)) {
// We'll always want to set this as hidden!
DOMUtil.setHidden(globalComp);
String componentType = DOMUtil.getLocalName(globalComp);
// includes and imports will not show up here!
if (DOMUtil.getLocalName(globalComp).equals(SchemaSymbols.ELT_REDEFINE)) {
// use the namespace decls for the redefine, instead of for the parent <schema>
currSchemaDoc.backupNSSupport((SchemaNamespaceSupport)fRedefine2NSSupport.get(globalComp));
for (Element redefinedComp = DOMUtil.getFirstVisibleChildElement(globalComp);
redefinedComp != null;
redefinedComp = DOMUtil.getNextVisibleSiblingElement(redefinedComp)) {
String redefinedComponentType = DOMUtil.getLocalName(redefinedComp);
DOMUtil.setHidden(redefinedComp);
if (redefinedComponentType.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) {
fAttributeGroupTraverser.traverseGlobal(redefinedComp, currSchemaDoc, currSG);
}
else if (redefinedComponentType.equals(SchemaSymbols.ELT_COMPLEXTYPE)) {
fComplexTypeTraverser.traverseGlobal(redefinedComp, currSchemaDoc, currSG);
}
else if (redefinedComponentType.equals(SchemaSymbols.ELT_GROUP)) {
fGroupTraverser.traverseGlobal(redefinedComp, currSchemaDoc, currSG);
}
else if (redefinedComponentType.equals(SchemaSymbols.ELT_SIMPLETYPE)) {
fSimpleTypeTraverser.traverseGlobal(redefinedComp, currSchemaDoc, currSG);
}
else if (redefinedComponentType.equals(SchemaSymbols.ELT_ANNOTATION)) {
// REVISIT: according to 3.13.2 the PSVI needs the parent's attributes;
// thus this should be done in buildGlobalNameRegistries not here...
fElementTraverser.traverseAnnotationDecl(redefinedComp, null, true, currSchemaDoc);
}
else {
reportSchemaError("src-redefine", new Object [] {componentType}, redefinedComp);
}
} // end march through <redefine> children
currSchemaDoc.restoreNSSupport();
}
else if (componentType.equals(SchemaSymbols.ELT_ATTRIBUTE)) {
fAttributeTraverser.traverseGlobal(globalComp, currSchemaDoc, currSG);
}
else if (componentType.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) {
fAttributeGroupTraverser.traverseGlobal(globalComp, currSchemaDoc, currSG);
}
else if (componentType.equals(SchemaSymbols.ELT_COMPLEXTYPE)) {
fComplexTypeTraverser.traverseGlobal(globalComp, currSchemaDoc, currSG);
}
else if (componentType.equals(SchemaSymbols.ELT_ELEMENT)) {
fElementTraverser.traverseGlobal(globalComp, currSchemaDoc, currSG);
}
else if (componentType.equals(SchemaSymbols.ELT_GROUP)) {
fGroupTraverser.traverseGlobal(globalComp, currSchemaDoc, currSG);
}
else if (componentType.equals(SchemaSymbols.ELT_NOTATION)) {
fNotationTraverser.traverse(globalComp, currSchemaDoc, currSG);
}
else if (componentType.equals(SchemaSymbols.ELT_SIMPLETYPE)) {
fSimpleTypeTraverser.traverseGlobal(globalComp, currSchemaDoc, currSG);
}
else if (componentType.equals(SchemaSymbols.ELT_ANNOTATION)) {
// REVISIT: according to 3.13.2 the PSVI needs the parent's attributes;
// thus this should be done in buildGlobalNameRegistries not here...
fElementTraverser.traverseAnnotationDecl(globalComp, null, true, currSchemaDoc);
}
else {
reportSchemaError("sch-props-correct.1", new Object [] {DOMUtil.getLocalName(globalComp)}, globalComp);
}
} // end for
// now we're done with this one!
DOMUtil.setHidden(currDoc);
// now add the schemas this guy depends on
Vector currSchemaDepends = (Vector)fDependencyMap.get(currSchemaDoc);
for (int i = 0; i < currSchemaDepends.size(); i++) {
schemasToProcess.push(currSchemaDepends.elementAt(i));
}
} // while
} // end traverseSchemas
// store whether we have reported an error about that no grammar
// is found for the given namespace uri
private Vector fReportedTNS = null;
// check whether we need to report an error against the given uri.
// if we have reported an error, then we don't need to report again;
// otherwise we reported the error, and remember this fact.
private final boolean needReportTNSError(String uri) {
if (fReportedTNS == null)
fReportedTNS = new Vector();
else if (fReportedTNS.contains(uri))
return false;
fReportedTNS.addElement(uri);
return true;
}
private static final String[] COMP_TYPE = {
null, // index 0
"attribute declaration",
"attribute group",
"element declaration",
"group",
"identity constraint",
"notation",
"type definition",
};
private static final String[] CIRCULAR_CODES = {
"Internal-Error",
"Internal-Error",
"src-attribute_group.3",
"e-props-correct.6",
"mg-props-correct.2",
"Internal-Error",
"Internal-Error",
"st-props-correct.2", //or ct-props-correct.3
};
// since it is forbidden for traversers to talk to each other
// directly (except wen a traverser encounters a local declaration),
// this provides a generic means for a traverser to call
// for the traversal of some declaration. An XSDocumentInfo is
// required because the XSDocumentInfo that the traverser is traversing
// may bear no relation to the one the handler is operating on.
// This method will:
// 1. See if a global definition matching declToTraverse exists;
// 2. if so, determine if there is a path from currSchema to the
// schema document where declToTraverse lives (i.e., do a lookup
// in DependencyMap);
// 3. depending on declType (which will be relevant to step 1 as
// well), call the appropriate traverser with the appropriate
// XSDocumentInfo object.
// This method returns whatever the traverser it called returned;
// this will be an Object of some kind
// that lives in the Grammar.
protected Object getGlobalDecl(XSDocumentInfo currSchema,
int declType,
QName declToTraverse,
Element elmNode) {
if (DEBUG_NODE_POOL) {
System.out.println("TRAVERSE_GL: "+declToTraverse.toString());
}
// from the schema spec, all built-in types are present in all schemas,
// so if the requested component is a type, and could be found in the
// default schema grammar, we should return that type.
// otherwise (since we would support user-defined schema grammar) we'll
// use the normal way to get the decl
if (declToTraverse.uri != null &&
declToTraverse.uri == SchemaSymbols.URI_SCHEMAFORSCHEMA) {
if (declType == TYPEDECL_TYPE) {
Object retObj = SchemaGrammar.SG_SchemaNS.getGlobalTypeDecl(declToTraverse.localpart);
if (retObj != null)
return retObj;
}
}
// now check whether this document can access the requsted namespace
if (!currSchema.isAllowedNS(declToTraverse.uri)) {
// cannot get to this schema from the one containing the requesting decl
if (currSchema.needReportTNSError(declToTraverse.uri)) {
String code = declToTraverse.uri == null ? "src-resolve.4.1" : "src-resolve.4.2";
reportSchemaError(code, new Object[]{fDoc2SystemId.get(currSchema.fSchemaDoc), declToTraverse.uri}, elmNode);
}
return null;
}
// check whether there is grammar for the requested namespace
SchemaGrammar sGrammar = fGrammarBucket.getGrammar(declToTraverse.uri);
if (sGrammar == null) {
if (needReportTNSError(declToTraverse.uri))
reportSchemaError("src-resolve", new Object[]{declToTraverse.rawname, COMP_TYPE[declType]}, elmNode);
return null;
}
// if there is such grammar, check whether the requested component is in the grammar
Object retObj = null;
switch (declType) {
case ATTRIBUTE_TYPE :
retObj = sGrammar.getGlobalAttributeDecl(declToTraverse.localpart);
break;
case ATTRIBUTEGROUP_TYPE :
retObj = sGrammar.getGlobalAttributeGroupDecl(declToTraverse.localpart);
break;
case ELEMENT_TYPE :
retObj = sGrammar.getGlobalElementDecl(declToTraverse.localpart);
break;
case GROUP_TYPE :
retObj = sGrammar.getGlobalGroupDecl(declToTraverse.localpart);
break;
case IDENTITYCONSTRAINT_TYPE :
retObj = sGrammar.getIDConstraintDecl(declToTraverse.localpart);
break;
case NOTATION_TYPE :
retObj = sGrammar.getGlobalNotationDecl(declToTraverse.localpart);
break;
case TYPEDECL_TYPE :
retObj = sGrammar.getGlobalTypeDecl(declToTraverse.localpart);
break;
}
// if the component is parsed, return it
if (retObj != null)
return retObj;
XSDocumentInfo schemaWithDecl = null;
Element decl = null;
// the component is not parsed, try to find a DOM element for it
String declKey = declToTraverse.uri == null? ","+declToTraverse.localpart:
declToTraverse.uri+","+declToTraverse.localpart;
switch (declType) {
case ATTRIBUTE_TYPE :
decl = (Element)fUnparsedAttributeRegistry.get(declKey);
break;
case ATTRIBUTEGROUP_TYPE :
decl = (Element)fUnparsedAttributeGroupRegistry.get(declKey);
break;
case ELEMENT_TYPE :
decl = (Element)fUnparsedElementRegistry.get(declKey);
break;
case GROUP_TYPE :
decl = (Element)fUnparsedGroupRegistry.get(declKey);
break;
case IDENTITYCONSTRAINT_TYPE :
decl = (Element)fUnparsedIdentityConstraintRegistry.get(declKey);
break;
case NOTATION_TYPE :
decl = (Element)fUnparsedNotationRegistry.get(declKey);
break;
case TYPEDECL_TYPE :
decl = (Element)fUnparsedTypeRegistry.get(declKey);
break;
default:
reportSchemaError("Internal-Error", new Object [] {"XSDHandler asked to locate component of type " + declType + "; it does not recognize this type!"}, elmNode);
}
// no DOM element found, so the component can't be located
if (decl == null) {
reportSchemaError("src-resolve", new Object[]{declToTraverse.rawname, COMP_TYPE[declType]}, elmNode);
return null;
}
// get the schema doc containing the component to be parsed
// it should always return non-null value, but since null-checking
// comes for free, let's be safe and check again
schemaWithDecl = findXSDocumentForDecl(currSchema, decl);
if (schemaWithDecl == null) {
// cannot get to this schema from the one containing the requesting decl
String code = declToTraverse.uri == null ? "src-resolve.4.1" : "src-resolve.4.2";
reportSchemaError(code, new Object[]{fDoc2SystemId.get(currSchema.fSchemaDoc), declToTraverse.uri}, elmNode);
return null;
}
// a component is hidden, meaning either it's traversed, or being traversed.
// but we didn't find it in the grammar, so it's the latter case, and
// a circular reference. error!
if (DOMUtil.isHidden(decl)) {
String code = CIRCULAR_CODES[declType];
if (declType == TYPEDECL_TYPE) {
if (SchemaSymbols.ELT_COMPLEXTYPE.equals(DOMUtil.getLocalName(decl)))
code = "ct-props-correct.3";
}
// decl must not be null if we're here...
reportSchemaError(code, new Object [] {declToTraverse.prefix+":"+declToTraverse.localpart}, elmNode);
return null;
}
// hide the element node before traversing it
DOMUtil.setHidden(decl);
SchemaNamespaceSupport nsSupport = null;
// if the parent is <redefine> use the namespace delcs for it.
Element parent = DOMUtil.getParent(decl);
if (DOMUtil.getLocalName(parent).equals(SchemaSymbols.ELT_REDEFINE))
nsSupport = (SchemaNamespaceSupport)fRedefine2NSSupport.get(parent);
// back up the current SchemaNamespaceSupport, because we need to provide
// a fresh one to the traverseGlobal methods.
schemaWithDecl.backupNSSupport(nsSupport);
// traverse the referenced global component
switch (declType) {
case ATTRIBUTE_TYPE :
retObj = fAttributeTraverser.traverseGlobal(decl, schemaWithDecl, sGrammar);
break;
case ATTRIBUTEGROUP_TYPE :
retObj = fAttributeGroupTraverser.traverseGlobal(decl, schemaWithDecl, sGrammar);
break;
case ELEMENT_TYPE :
retObj = fElementTraverser.traverseGlobal(decl, schemaWithDecl, sGrammar);
break;
case GROUP_TYPE :
retObj = fGroupTraverser.traverseGlobal(decl, schemaWithDecl, sGrammar);
break;
case IDENTITYCONSTRAINT_TYPE :
// identity constraints should have been parsed already...
// we should never get here
retObj = null;
break;
case NOTATION_TYPE :
retObj = fNotationTraverser.traverse(decl, schemaWithDecl, sGrammar);
break;
case TYPEDECL_TYPE :
if (DOMUtil.getLocalName(decl).equals(SchemaSymbols.ELT_COMPLEXTYPE))
retObj = fComplexTypeTraverser.traverseGlobal(decl, schemaWithDecl, sGrammar);
else
retObj = fSimpleTypeTraverser.traverseGlobal(decl, schemaWithDecl, sGrammar);
}
// restore the previous SchemaNamespaceSupport, so that the caller can get
// proper namespace binding.
schemaWithDecl.restoreNSSupport();
return retObj;
} // getGlobalDecl(XSDocumentInfo, int, QName): Object
// This method determines whether there is a group
// (attributeGroup) which the given one has redefined by
// restriction. If so, it returns it; else it returns null.
// @param type: whether what's been redefined is an
// attributeGroup or a group;
// @param name: the QName of the component doing the redefining.
// @param currSchema: schema doc in which the redefining component lives.
// @return: Object representing decl redefined if present, null
// otherwise.
Object getGrpOrAttrGrpRedefinedByRestriction(int type, QName name, XSDocumentInfo currSchema, Element elmNode) {
String realName = name.uri != null?name.uri+","+name.localpart:
","+name.localpart;
String nameToFind = null;
switch (type) {
case ATTRIBUTEGROUP_TYPE:
nameToFind = (String)fRedefinedRestrictedAttributeGroupRegistry.get(realName);
break;
case GROUP_TYPE:
nameToFind = (String)fRedefinedRestrictedGroupRegistry.get(realName);
break;
default:
return null;
}
if (nameToFind == null) return null;
int commaPos = nameToFind.indexOf(",");
QName qNameToFind = new QName(XMLSymbols.EMPTY_STRING, nameToFind.substring(commaPos+1),
nameToFind.substring(commaPos), (commaPos == 0)? null : nameToFind.substring(0, commaPos));
Object retObj = getGlobalDecl(currSchema, type, qNameToFind, elmNode);
if(retObj == null) {
switch (type) {
case ATTRIBUTEGROUP_TYPE:
reportSchemaError("src-redefine.7.2.1", new Object []{name.localpart}, elmNode);
break;
case GROUP_TYPE:
reportSchemaError("src-redefine.6.2.1", new Object []{name.localpart}, elmNode);
break;
}
return null;
}
return retObj;
} // getGrpOrAttrGrpRedefinedByRestriction(int, QName, XSDocumentInfo): Object
// Since ID constraints can occur in local elements, unless we
// wish to completely traverse all our DOM trees looking for ID
// constraints while we're building our global name registries,
// which seems terribly inefficient, we need to resolve keyrefs
// after all parsing is complete. This we can simply do by running through
// fIdentityConstraintRegistry and calling traverseKeyRef on all
// of the KeyRef nodes. This unfortunately removes this knowledge
// from the elementTraverser class (which must ignore keyrefs),
// but there seems to be no efficient way around this...
protected void resolveKeyRefs() {
for (int i=0; i<fKeyrefStackPos; i++) {
Document keyrefDoc = DOMUtil.getDocument(fKeyrefs[i]);
XSDocumentInfo keyrefSchemaDoc = (XSDocumentInfo)fDoc2XSDocumentMap.get(keyrefDoc);
keyrefSchemaDoc.fNamespaceSupport.makeGlobal();
keyrefSchemaDoc.fNamespaceSupport.setEffectiveContext( fKeyrefNamespaceContext[i] );
SchemaGrammar keyrefGrammar = fGrammarBucket.getGrammar(keyrefSchemaDoc.fTargetNamespace);
// need to set <keyref> to hidden before traversing it,
// because it has global scope
DOMUtil.setHidden(fKeyrefs[i]);
fKeyrefTraverser.traverse(fKeyrefs[i], fKeyrefElems[i], keyrefSchemaDoc, keyrefGrammar);
}
} // end resolveKeyRefs
// an accessor method. Just makes sure callers
// who want the Identity constraint registry vaguely know what they're about.
protected Hashtable getIDRegistry() {
return fUnparsedIdentityConstraintRegistry;
}
// This method squirrels away <keyref> declarations--along with the element
// decls and namespace bindings they might find handy.
protected void storeKeyRef (Element keyrefToStore, XSDocumentInfo schemaDoc,
XSElementDecl currElemDecl) {
String keyrefName = DOMUtil.getAttrValue(keyrefToStore, SchemaSymbols.ATT_NAME);
if (keyrefName.length() != 0) {
String keyrefQName = schemaDoc.fTargetNamespace == null?
"," + keyrefName: schemaDoc.fTargetNamespace+","+keyrefName;
checkForDuplicateNames(keyrefQName, fUnparsedIdentityConstraintRegistry, keyrefToStore, schemaDoc);
}
// now set up all the registries we'll need...
// check array sizes
if (fKeyrefStackPos == fKeyrefs.length) {
Element [] elemArray = new Element [fKeyrefStackPos + INC_KEYREF_STACK_AMOUNT];
System.arraycopy(fKeyrefs, 0, elemArray, 0, fKeyrefStackPos);
fKeyrefs = elemArray;
XSElementDecl [] declArray = new XSElementDecl [fKeyrefStackPos + INC_KEYREF_STACK_AMOUNT];
System.arraycopy(fKeyrefElems, 0, declArray, 0, fKeyrefStackPos);
fKeyrefElems = declArray;
String[][] stringArray = new String [fKeyrefStackPos + INC_KEYREF_STACK_AMOUNT][];
System.arraycopy(fKeyrefNamespaceContext, 0, stringArray, 0, fKeyrefStackPos);
fKeyrefNamespaceContext = stringArray;
}
fKeyrefs[fKeyrefStackPos] = keyrefToStore;
fKeyrefElems[fKeyrefStackPos] = currElemDecl;
fKeyrefNamespaceContext[fKeyrefStackPos++] = schemaDoc.fNamespaceSupport.getEffectiveLocalContext();
} // storeKeyref (Element, XSDocumentInfo, XSElementDecl): void
private static final String[] DOC_ERROR_CODES = {
"src-include.0", "src-redefine.0", "src-import.0", "schema_reference.4",
"schema_reference.4", "schema_reference.4", "schema_reference.4", "schema_reference.4"
};
// This method is responsible for schema resolution. If it finds
// a schema document that the XMLEntityResolver resolves to with
// the given namespace and hint, it returns it. It returns true
// if this is the first time it's seen this document, false
// otherwise. schemaDoc is null if and only if no schema document
// was resolved to.
private Document getSchema(XSDDescription desc,
boolean mustResolve, Element referElement) {
XMLInputSource schemaSource=null;
try {
schemaSource = XMLSchemaLoader.resolveDocument(desc, fLocationPairs, fEntityResolver);
}
catch (IOException ex) {
if (mustResolve) {
reportSchemaError(DOC_ERROR_CODES[desc.getContextType()],
new Object[]{desc.getLocationHints()[0]},
referElement);
}
else {
reportSchemaWarning(DOC_ERROR_CODES[desc.getContextType()],
new Object[]{desc.getLocationHints()[0]},
referElement);
}
}
return getSchema(desc.getTargetNamespace(), schemaSource, mustResolve, desc.getContextType(), referElement);
} // getSchema(String, String, String, boolean, short): Document
private Document getSchema(String schemaNamespace, XMLInputSource schemaSource,
boolean mustResolve, short referType, Element referElement) {
boolean hasInput = true;
// contents of this method will depend on the system we adopt for entity resolution--i.e., XMLEntityHandler, EntityHandler, etc.
Document schemaDoc = null;
try {
// when the system id and byte stream and character stream
// of the input source are all null, it's
// impossible to find the schema document. so we skip in
// this case. otherwise we'll receive some NPE or
// file not found errors. but schemaHint=="" is perfectly
// legal for import.
if (schemaSource != null &&
(schemaSource.getSystemId() != null ||
schemaSource.getByteStream() != null ||
schemaSource.getCharacterStream() != null)) {
// When the system id of the input source is used, first try to
// expand it, and check whether the same document has been
// parsed before. If so, return the document corresponding to
// that system id.
String schemaId = XMLEntityManager.expandSystemId(schemaSource.getSystemId(), schemaSource.getBaseSystemId(), false);
XSDKey key = new XSDKey(schemaId, referType, schemaNamespace);
if ((schemaDoc = (Document)fTraversed.get(key)) != null) {
fLastSchemaWasDuplicate = true;
return schemaDoc;
}
// If this is the first schema this Handler has
// parsed, it has to construct a DOMParser
if (fSchemaParser == null) {
//fSchemaParser = new DOMParser();
fSchemaParser = new SchemaParsingConfig();
resetSchemaParserErrorHandler();
}
fSchemaParser.parse(schemaSource);
schemaDoc = fSchemaParser.getDocument();
// now we need to store the mapping information from system id
// to the document. also from the document to the system id.
fTraversed.put(key, schemaDoc );
if (schemaId != null)
fDoc2SystemId.put(schemaDoc, schemaId );
fLastSchemaWasDuplicate = false;
return schemaDoc;
}
else {
hasInput = false;
}
}
catch (IOException ex) {
}
// either an error occured (exception), or empty input source was
// returned, we need to report an error or a warning
if (mustResolve) {
reportSchemaError(DOC_ERROR_CODES[referType],
new Object[]{schemaSource.getSystemId()},
referElement);
}
else if (hasInput) {
reportSchemaWarning(DOC_ERROR_CODES[referType],
new Object[]{schemaSource.getSystemId()},
referElement);
}
fLastSchemaWasDuplicate = false;
return null;
} // getSchema(String, XMLInputSource, boolean, boolean): Document
// initialize all the traversers.
// this should only need to be called once during the construction
// of this object; it creates the traversers that will be used to
// construct schemaGrammars.
private void createTraversers() {
fAttributeChecker = new XSAttributeChecker(this);
fAttributeGroupTraverser = new XSDAttributeGroupTraverser(this, fAttributeChecker);
fAttributeTraverser = new XSDAttributeTraverser(this, fAttributeChecker);
fComplexTypeTraverser = new XSDComplexTypeTraverser(this, fAttributeChecker);
fElementTraverser = new XSDElementTraverser(this, fAttributeChecker);
fGroupTraverser = new XSDGroupTraverser(this, fAttributeChecker);
fKeyrefTraverser = new XSDKeyrefTraverser(this, fAttributeChecker);
fNotationTraverser = new XSDNotationTraverser(this, fAttributeChecker);
fSimpleTypeTraverser = new XSDSimpleTypeTraverser(this, fAttributeChecker);
fUniqueOrKeyTraverser = new XSDUniqueOrKeyTraverser(this, fAttributeChecker);
fWildCardTraverser = new XSDWildcardTraverser(this, fAttributeChecker);
} // createTraversers()
// before parsing a schema, need to clear registries associated with
// parsing schemas
void prepareForParse() {
fTraversed.clear();
fDoc2SystemId.clear();
fLastSchemaWasDuplicate = false;
}
// before traversing a schema's parse tree, need to reset all traversers and
// clear all registries
void prepareForTraverse() {
fUnparsedAttributeRegistry.clear();
fUnparsedAttributeGroupRegistry.clear();
fUnparsedElementRegistry.clear();
fUnparsedGroupRegistry.clear();
fUnparsedIdentityConstraintRegistry.clear();
fUnparsedNotationRegistry.clear();
fUnparsedTypeRegistry.clear();
fXSDocumentInfoRegistry.clear();
fDependencyMap.clear();
fDoc2XSDocumentMap.clear();
fRedefine2XSDMap.clear();
fRedefine2NSSupport.clear();
fAllTNSs.removeAllElements();
fImportMap.clear();
fRoot = null;
// clear local element stack
for (int i = 0; i < fLocalElemStackPos; i++) {
fParticle[i] = null;
fLocalElementDecl[i] = null;
fLocalElemNamespaceContext[i] = null;
}
fLocalElemStackPos = 0;
// and do same for keyrefs.
for (int i = 0; i < fKeyrefStackPos; i++) {
fKeyrefs[i] = null;
fKeyrefElems[i] = null;
fKeyrefNamespaceContext[i] = null;
}
fKeyrefStackPos = 0;
// create traversers if necessary
if (fAttributeChecker == null) {
createTraversers();
}
// reset traversers
fAttributeChecker.reset(fSymbolTable);
fAttributeGroupTraverser.reset(fSymbolTable);
fAttributeTraverser.reset(fSymbolTable);
fComplexTypeTraverser.reset(fSymbolTable);
fElementTraverser.reset(fSymbolTable);
fGroupTraverser.reset(fSymbolTable);
fKeyrefTraverser.reset(fSymbolTable);
fNotationTraverser.reset(fSymbolTable);
fSimpleTypeTraverser.reset(fSymbolTable);
fUniqueOrKeyTraverser.reset(fSymbolTable);
fWildCardTraverser.reset(fSymbolTable);
fRedefinedRestrictedAttributeGroupRegistry.clear();
fRedefinedRestrictedGroupRegistry.clear();
}
public void setDeclPool (XSDeclarationPool declPool){
fDeclPool = declPool;
}
// this method reset properties that might change between parses.
// and process the jaxp schemaSource property
public void reset(XMLErrorReporter errorReporter,
XMLEntityResolver entityResolver,
SymbolTable symbolTable,
XMLGrammarPool grammarPool,
boolean allowJavaEncodings,
boolean strictURI) {
fErrorReporter = errorReporter;
fEntityResolver = entityResolver;
fSymbolTable = symbolTable;
fGrammarPool = grammarPool;
fAllowJavaEncodings = allowJavaEncodings;
fStrictURI = strictURI;
resetSchemaParserErrorHandler();
} // reset(ErrorReporter, EntityResolver, SymbolTable, XMLGrammarPool)
void resetSchemaParserErrorHandler() {
if (fSchemaParser != null) {
try {
XMLErrorHandler currErrorHandler =
fErrorReporter.getErrorHandler();
// Setting a parser property can be much more expensive
// than checking its value. Don't set the ERROR_HANDLER
// property unless it's actually changed.
if (currErrorHandler
!= fSchemaParser.getProperty(ERROR_HANDLER)) {
fSchemaParser.setProperty(ERROR_HANDLER, currErrorHandler);
}
} catch (Exception e) {
}
// make sure the following are set correctly:
// continue-after-fatal-error
// allow-java-encodings
// standard-uri-conformant
try {
fSchemaParser.setFeature(CONTINUE_AFTER_FATAL_ERROR, fErrorReporter.getFeature(CONTINUE_AFTER_FATAL_ERROR));
} catch (Exception e) {
}
try {
fSchemaParser.setFeature(ALLOW_JAVA_ENCODINGS, fAllowJavaEncodings);
} catch (Exception e) {
}
try {
fSchemaParser.setFeature(STANDARD_URI_CONFORMANT_FEATURE, fStrictURI);
} catch (Exception e) {
}
try {
if (fEntityResolver != fSchemaParser.getProperty(ENTITY_RESOLVER)) {
fSchemaParser.setProperty(ENTITY_RESOLVER, fEntityResolver);
}
} catch (Exception e) {
}
}
} // resetSchemaParserErrorHandler()
/**
* Traverse all the deferred local elements. This method should be called
* by traverseSchemas after we've done with all the global declarations.
*/
void traverseLocalElements() {
fElementTraverser.fDeferTraversingLocalElements = false;
for (int i = 0; i < fLocalElemStackPos; i++) {
Element currElem = fLocalElementDecl[i];
XSDocumentInfo currSchema = (XSDocumentInfo)fDoc2XSDocumentMap.get(DOMUtil.getDocument(currElem));
SchemaGrammar currGrammar = fGrammarBucket.getGrammar(currSchema.fTargetNamespace);
fElementTraverser.traverseLocal (fParticle[i], currElem, currSchema, currGrammar, fAllContext[i], fEnclosingCT[i]);
}
}
// the purpose of this method is to keep up-to-date structures
// we'll need for the feferred traversal of local elements.
void fillInLocalElemInfo(Element elmDecl,
XSDocumentInfo schemaDoc,
int allContextFlags,
XSComplexTypeDecl enclosingCT,
XSParticleDecl particle) {
// if the stack is full, increase the size
if (fParticle.length == fLocalElemStackPos) {
// increase size
XSParticleDecl[] newStackP = new XSParticleDecl[fLocalElemStackPos+INC_STACK_SIZE];
System.arraycopy(fParticle, 0, newStackP, 0, fLocalElemStackPos);
fParticle = newStackP;
Element[] newStackE = new Element[fLocalElemStackPos+INC_STACK_SIZE];
System.arraycopy(fLocalElementDecl, 0, newStackE, 0, fLocalElemStackPos);
fLocalElementDecl = newStackE;
int[] newStackI = new int[fLocalElemStackPos+INC_STACK_SIZE];
System.arraycopy(fAllContext, 0, newStackI, 0, fLocalElemStackPos);
fAllContext = newStackI;
XSComplexTypeDecl[] newStackC = new XSComplexTypeDecl[fLocalElemStackPos+INC_STACK_SIZE];
System.arraycopy(fEnclosingCT, 0, newStackC, 0, fLocalElemStackPos);
fEnclosingCT = newStackC;
String [][] newStackN = new String [fLocalElemStackPos+INC_STACK_SIZE][];
System.arraycopy(fLocalElemNamespaceContext, 0, newStackN, 0, fLocalElemStackPos);
fLocalElemNamespaceContext = newStackN;
}
fParticle[fLocalElemStackPos] = particle;
fLocalElementDecl[fLocalElemStackPos] = elmDecl;
fAllContext[fLocalElemStackPos] = allContextFlags;
fEnclosingCT[fLocalElemStackPos] = enclosingCT;
fLocalElemNamespaceContext[fLocalElemStackPos++] = schemaDoc.fNamespaceSupport.getEffectiveLocalContext();
} // end fillInLocalElemInfo(...)
/** This method makes sure that
* if this component is being redefined that it lives in the
* right schema. It then renames the component correctly. If it
* detects a collision--a duplicate definition--then it complains.
* Note that redefines must be handled carefully: if there
* is a collision, it may be because we're redefining something we know about
* or because we've found the thing we're redefining.
*/
void checkForDuplicateNames(String qName,
Hashtable registry, Element currComp,
XSDocumentInfo currSchema) {
Object objElem = null;
// REVISIT: when we add derivation checking, we'll have to make
// sure that ID constraint collisions don't necessarily result in error messages.
if ((objElem = registry.get(qName)) == null) {
// just add it in!
registry.put(qName, currComp);
}
else {
Element collidingElem = (Element)objElem;
if (collidingElem == currComp) return;
Element elemParent = null;
XSDocumentInfo redefinedSchema = null;
// case where we've collided with a redefining element
// (the parent of the colliding element is a redefine)
boolean collidedWithRedefine = true;
if ((DOMUtil.getLocalName((elemParent = DOMUtil.getParent(collidingElem))).equals(SchemaSymbols.ELT_REDEFINE))) {
redefinedSchema = (XSDocumentInfo)(fRedefine2XSDMap.get(elemParent));
// case where we're a redefining element.
}
else if ((DOMUtil.getLocalName(DOMUtil.getParent(currComp)).equals(SchemaSymbols.ELT_REDEFINE))) {
redefinedSchema = (XSDocumentInfo)(fDoc2XSDocumentMap.get(DOMUtil.getDocument(collidingElem)));
collidedWithRedefine = false;
}
if (redefinedSchema != null) { //redefinition involved somehow
// If both components belong to the same document then
// report an error and return.
if (fDoc2XSDocumentMap.get(DOMUtil.getDocument(collidingElem)) == currSchema) {
reportSchemaError("sch-props-correct.2", new Object[]{qName}, currComp);
return;
}
String newName = qName.substring(qName.lastIndexOf(',')+1)+REDEF_IDENTIFIER;
if (redefinedSchema == currSchema) { // object comp. okay here
// now have to do some renaming...
currComp.setAttribute(SchemaSymbols.ATT_NAME, newName);
if (currSchema.fTargetNamespace == null)
registry.put(","+newName, currComp);
else
registry.put(currSchema.fTargetNamespace+","+newName, currComp);
// and take care of nested redefines by calling recursively:
if (currSchema.fTargetNamespace == null)
checkForDuplicateNames(","+newName, registry, currComp, currSchema);
else
checkForDuplicateNames(currSchema.fTargetNamespace+","+newName, registry, currComp, currSchema);
}
else { // we may be redefining the wrong schema
if (collidedWithRedefine) {
if (currSchema.fTargetNamespace == null)
checkForDuplicateNames(","+newName, registry, currComp, currSchema);
else
checkForDuplicateNames(currSchema.fTargetNamespace+","+newName, registry, currComp, currSchema);
}
else {
// error that redefined element in wrong schema
reportSchemaError("src-redefine.1", new Object [] {qName}, currComp);
}
}
}
else {
// we've just got a flat-out collision
reportSchemaError("sch-props-correct.2", new Object []{qName}, currComp);
}
}
} // checkForDuplicateNames(String, Hashtable, Element, XSDocumentInfo):void
// the purpose of this method is to take the component of the
// specified type and rename references to itself so that they
// refer to the object being redefined. It takes special care of
// <group>s and <attributeGroup>s to ensure that information
// relating to implicit restrictions is preserved for those
// traversers.
private void renameRedefiningComponents(XSDocumentInfo currSchema,
Element child, String componentType,
String oldName, String newName) {
if (componentType.equals(SchemaSymbols.ELT_SIMPLETYPE)) {
Element grandKid = DOMUtil.getFirstChildElement(child);
if (grandKid == null) {
reportSchemaError("src-redefine.5", null, child);
}
else {
String grandKidName = grandKid.getLocalName();
if (grandKidName.equals(SchemaSymbols.ELT_ANNOTATION)) {
grandKid = DOMUtil.getNextSiblingElement(grandKid);
grandKidName = grandKid.getLocalName();
}
if (grandKid == null) {
reportSchemaError("src-redefine.5", null, child);
}
else if (!grandKidName.equals(SchemaSymbols.ELT_RESTRICTION)) {
reportSchemaError("src-redefine.5", null, child);
}
else {
Object[] attrs = fAttributeChecker.checkAttributes(grandKid, false, currSchema);
QName derivedBase = (QName)attrs[XSAttributeChecker.ATTIDX_BASE];
if (derivedBase == null ||
derivedBase.uri != currSchema.fTargetNamespace ||
!derivedBase.localpart.equals(oldName)) {
reportSchemaError("src-redefine.5", null, child);
}
else {
// now we have to do the renaming...
if (derivedBase.prefix != null && derivedBase.prefix.length() > 0)
grandKid.setAttribute( SchemaSymbols.ATT_BASE,
derivedBase.prefix + ":" + newName );
else
grandKid.setAttribute( SchemaSymbols.ATT_BASE, newName );
// return true;
}
fAttributeChecker.returnAttrArray(attrs, currSchema);
}
}
}
else if (componentType.equals(SchemaSymbols.ELT_COMPLEXTYPE)) {
Element grandKid = DOMUtil.getFirstChildElement(child);
if (grandKid == null) {
reportSchemaError("src-redefine.5", null, child);
}
else {
if (grandKid.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION)) {
grandKid = DOMUtil.getNextSiblingElement(grandKid);
}
if (grandKid == null) {
reportSchemaError("src-redefine.5", null, child);
}
else {
// have to go one more level down; let another pass worry whether complexType is valid.
Element greatGrandKid = DOMUtil.getFirstChildElement(grandKid);
if (greatGrandKid == null) {
reportSchemaError("src-redefine.5", null, grandKid);
}
else {
String greatGrandKidName = greatGrandKid.getLocalName();
if (greatGrandKidName.equals(SchemaSymbols.ELT_ANNOTATION)) {
greatGrandKid = DOMUtil.getNextSiblingElement(greatGrandKid);
greatGrandKidName = greatGrandKid.getLocalName();
}
if (greatGrandKid == null) {
reportSchemaError("src-redefine.5", null, grandKid);
}
else if (!greatGrandKidName.equals(SchemaSymbols.ELT_RESTRICTION) &&
!greatGrandKidName.equals(SchemaSymbols.ELT_EXTENSION)) {
reportSchemaError("src-redefine.5", null, greatGrandKid);
}
else {
Object[] attrs = fAttributeChecker.checkAttributes(greatGrandKid, false, currSchema);
QName derivedBase = (QName)attrs[XSAttributeChecker.ATTIDX_BASE];
if (derivedBase == null ||
derivedBase.uri != currSchema.fTargetNamespace ||
!derivedBase.localpart.equals(oldName)) {
reportSchemaError("src-redefine.5", null, greatGrandKid);
}
else {
// now we have to do the renaming...
if (derivedBase.prefix != null && derivedBase.prefix.length() > 0)
greatGrandKid.setAttribute( SchemaSymbols.ATT_BASE,
derivedBase.prefix + ":" + newName );
else
greatGrandKid.setAttribute( SchemaSymbols.ATT_BASE,
newName );
// return true;
}
}
}
}
}
}
else if (componentType.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) {
String processedBaseName = (currSchema.fTargetNamespace == null)?
","+oldName:currSchema.fTargetNamespace+","+oldName;
int attGroupRefsCount = changeRedefineGroup(processedBaseName, componentType, newName, child, currSchema);
if (attGroupRefsCount > 1) {
reportSchemaError("src-redefine.7.1", new Object []{new Integer(attGroupRefsCount)}, child);
}
else if (attGroupRefsCount == 1) {
// return true;
}
else
if (currSchema.fTargetNamespace == null)
fRedefinedRestrictedAttributeGroupRegistry.put(processedBaseName, ","+newName);
else
fRedefinedRestrictedAttributeGroupRegistry.put(processedBaseName, currSchema.fTargetNamespace+","+newName);
}
else if (componentType.equals(SchemaSymbols.ELT_GROUP)) {
String processedBaseName = (currSchema.fTargetNamespace == null)?
","+oldName:currSchema.fTargetNamespace+","+oldName;
int groupRefsCount = changeRedefineGroup(processedBaseName, componentType, newName, child, currSchema);
if (groupRefsCount > 1) {
reportSchemaError("src-redefine.6.1.1", new Object []{new Integer(groupRefsCount)}, child);
}
else if (groupRefsCount == 1) {
// return true;
}
else {
if (currSchema.fTargetNamespace == null)
fRedefinedRestrictedGroupRegistry.put(processedBaseName, ","+newName);
else
fRedefinedRestrictedGroupRegistry.put(processedBaseName, currSchema.fTargetNamespace+","+newName);
}
}
else {
reportSchemaError("Internal-Error", new Object [] {"could not handle this particular <redefine>; please submit your schemas and instance document in a bug report!"}, child);
}
// if we get here then we must have reported an error and failed somewhere...
// return false;
} // renameRedefiningComponents(XSDocumentInfo, Element, String, String, String):void
// this method takes a name of the form a:b, determines the URI mapped
// to by a in the current SchemaNamespaceSupport object, and returns this
// information in the form (nsURI,b) suitable for lookups in the global
// decl Hashtables.
// REVISIT: should have it return QName, instead of String. this would
// save lots of string concatenation time. we can use
// QName#equals() to compare two QNames, and use QName directly
// as a key to the SymbolHash.
// And when the DV's are ready to return compiled values from
// validate() method, we should just call QNameDV.validate()
// in this method.
private String findQName(String name, XSDocumentInfo schemaDoc) {
SchemaNamespaceSupport currNSMap = schemaDoc.fNamespaceSupport;
int colonPtr = name.indexOf(':');
String prefix = XMLSymbols.EMPTY_STRING;
if (colonPtr > 0)
prefix = name.substring(0, colonPtr);
String uri = currNSMap.getURI(fSymbolTable.addSymbol(prefix));
String localpart = (colonPtr == 0)?name:name.substring(colonPtr+1);
if (prefix == XMLSymbols.EMPTY_STRING && uri == null && schemaDoc.fIsChameleonSchema)
uri = schemaDoc.fTargetNamespace;
if (uri == null)
return ","+localpart;
return uri+","+localpart;
} // findQName(String, XSDocumentInfo): String
// This function looks among the children of curr for an element of type elementSought.
// If it finds one, it evaluates whether its ref attribute contains a reference
// to originalQName. If it does, it returns 1 + the value returned by
// calls to itself on all other children. In all other cases it returns 0 plus
// the sum of the values returned by calls to itself on curr's children.
// It also resets the value of ref so that it will refer to the renamed type from the schema
// being redefined.
private int changeRedefineGroup(String originalQName, String elementSought,
String newName, Element curr, XSDocumentInfo schemaDoc) {
int result = 0;
for (Element child = DOMUtil.getFirstChildElement(curr);
child != null; child = DOMUtil.getNextSiblingElement(child)) {
String name = child.getLocalName();
if (!name.equals(elementSought))
result += changeRedefineGroup(originalQName, elementSought, newName, child, schemaDoc);
else {
String ref = child.getAttribute( SchemaSymbols.ATT_REF );
if (ref.length() != 0) {
String processedRef = findQName(ref, schemaDoc);
if (originalQName.equals(processedRef)) {
String prefix = XMLSymbols.EMPTY_STRING;
int colonptr = ref.indexOf(":");
if (colonptr > 0) {
prefix = ref.substring(0,colonptr);
child.setAttribute(SchemaSymbols.ATT_REF, prefix + ":" + newName);
}
else
child.setAttribute(SchemaSymbols.ATT_REF, newName);
result++;
if (elementSought.equals(SchemaSymbols.ELT_GROUP)) {
String minOccurs = child.getAttribute( SchemaSymbols.ATT_MINOCCURS );
String maxOccurs = child.getAttribute( SchemaSymbols.ATT_MAXOCCURS );
if (!((maxOccurs.length() == 0 || maxOccurs.equals("1"))
&& (minOccurs.length() == 0 || minOccurs.equals("1")))) {
reportSchemaError("src-redefine.6.1.2", new Object [] {ref}, child);
}
}
}
} // if ref was null some other stage of processing will flag the error
}
}
return result;
} // changeRedefineGroup
// this method returns the XSDocumentInfo object that contains the
// component corresponding to decl. If components from this
// document cannot be referred to from those of currSchema, this
// method returns null; it's up to the caller to throw an error.
// @param: currSchema: the XSDocumentInfo object containing the
// decl ref'ing us.
// @param: decl: the declaration being ref'd.
private XSDocumentInfo findXSDocumentForDecl(XSDocumentInfo currSchema,
Element decl) {
if (DEBUG_NODE_POOL) {
System.out.println("DOCUMENT NS:"+ currSchema.fTargetNamespace+" hashcode:"+ ((Object)currSchema.fSchemaDoc).hashCode());
}
Document declDoc = DOMUtil.getDocument(decl);
Object temp = fDoc2XSDocumentMap.get(declDoc);
if (temp == null) {
// something went badly wrong; we don't know this doc?
return null;
}
XSDocumentInfo declDocInfo = (XSDocumentInfo)temp;
return declDocInfo;
/*********
Logic here is unnecessary after schema WG's recent decision to allow
schema components from one document to refer to components of any other,
so long as there's some include/import/redefine path amongst them.
If they rver reverse this decision the code's right here though... - neilg
// now look in fDependencyMap to see if this is reachable
if(((Vector)fDependencyMap.get(currSchema)).contains(declDocInfo)) {
return declDocInfo;
}
// obviously the requesting doc didn't include, redefine or
// import the one containing decl...
return null;
**********/
} // findXSDocumentForDecl(XSDocumentInfo, Element): XSDocumentInfo
// returns whether more than <annotation>s occur in children of elem
private boolean nonAnnotationContent(Element elem) {
for(Element child = DOMUtil.getFirstChildElement(elem); child != null; child = DOMUtil.getNextSiblingElement(child)) {
if(!(DOMUtil.getLocalName(child).equals(SchemaSymbols.ELT_ANNOTATION))) return true;
}
return false;
} // nonAnnotationContent(Element): boolean
private void setSchemasVisible(XSDocumentInfo startSchema) {
if (DOMUtil.isHidden(startSchema.fSchemaDoc)) {
// make it visible
DOMUtil.setVisible(startSchema.fSchemaDoc);
Vector dependingSchemas = (Vector)fDependencyMap.get(startSchema);
for (int i = 0; i < dependingSchemas.size(); i++) {
setSchemasVisible((XSDocumentInfo)dependingSchemas.elementAt(i));
}
}
// if it's visible already than so must be its children
} // setSchemasVisible(XSDocumentInfo): void
private SimpleLocator xl = new SimpleLocator();
/**
* Extract location information from an Element node, and create a
* new SimpleLocator object from such information. Returning null means
* no information can be retrieved from the element.
*/
public SimpleLocator element2Locator(Element e) {
if (!(e instanceof ElementNSImpl || e instanceof ElementImpl))
return null;
SimpleLocator l = new SimpleLocator();
return element2Locator(e, l) ? l : null;
}
/**
* Extract location information from an Element node, store such
* information in the passed-in SimpleLocator object, then return
* true. Returning false means can't extract or store such information.
*/
public boolean element2Locator(Element e, SimpleLocator l) {
if (l == null)
return false;
if (e instanceof ElementImpl) {
ElementImpl ele = (ElementImpl)e;
// get system id from document object
Document doc = ele.getOwnerDocument();
String sid = (String)fDoc2SystemId.get(doc);
// line/column numbers are stored in the element node
int line = ele.getLineNumber();
int column = ele.getColumnNumber();
l.setValues(sid, sid, line, column);
return true;
}
if (e instanceof ElementNSImpl) {
ElementNSImpl ele = (ElementNSImpl)e;
// get system id from document object
Document doc = ele.getOwnerDocument();
String sid = (String)fDoc2SystemId.get(doc);
// line/column numbers are stored in the element node
int line = ele.getLineNumber();
int column = ele.getColumnNumber();
l.setValues(sid, sid, line, column);
return true;
}
return false;
}
void reportSchemaError(String key, Object[] args, Element ele) {
if (element2Locator(ele, xl)) {
fErrorReporter.reportError(xl, XSMessageFormatter.SCHEMA_DOMAIN,
key, args, XMLErrorReporter.SEVERITY_ERROR);
}
else {
fErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN,
key, args, XMLErrorReporter.SEVERITY_ERROR);
}
}
void reportSchemaWarning(String key, Object[] args, Element ele) {
if (element2Locator(ele, xl)) {
fErrorReporter.reportError(xl, XSMessageFormatter.SCHEMA_DOMAIN,
key, args, XMLErrorReporter.SEVERITY_WARNING);
}
else {
fErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN,
key, args, XMLErrorReporter.SEVERITY_WARNING);
}
}
/**
* used to identify a reference to a schema document
* if the same document is referenced twice with the same key, then
* we only need to parse it once.
*
* When 2 XSDKey's are compared, the following table can be used to
* determine whether they are equal:
* inc red imp pre ins
* inc N/L ? N/L N/L N/L
* red ? N/L ? ? ?
* imp N/L ? N/P N/P N/P
* pre N/L ? N/P N/P N/P
* ins N/L ? N/P N/P N/P
*
* Where: N/L: duplicate when they have the same namespace and location.
* ? : not clear from the spec.
* REVISIT: to simplify the process, also considering
* it's very rare, we treat them as not duplicate.
* N/P: not possible. imp/pre/ins are referenced by namespace.
* when the first time we encounter a schema document for a
* namespace, we create a grammar and store it in the grammar
* bucket. when we see another reference to the same namespace,
* we first check whether a grammar with the same namespace is
* already in the bucket, which is true in this case, so we
* won't create another XSDKey.
*
* Conclusion from the table: two XSDKey's are duplicate only when all of
* the following are true:
* 1. They are both "redefine", or neither is "redefine" (which implies
* that they are both "include");
* 2. They have the same namespace and location.
*/
private static class XSDKey {
String systemId;
short referType;
// for inclue/redefine, this is the enclosing namespace
// for import/preparse/instance, this is the target namespace
String referNS;
XSDKey(String systemId, short referType, String referNS) {
this.systemId = systemId;
this.referType = referType;
this.referNS = referNS;
}
public int hashCode() {
// according to the description at the beginning of this class,
// we use the hashcode of the namespace as the hashcoe of this key.
return referNS == null ? 0 : referNS.hashCode();
}
public boolean equals(Object obj) {
if (!(obj instanceof XSDKey)) {
return false;
}
XSDKey key = (XSDKey)obj;
// condition 1: both are redefine
if (referType == XSDDescription.CONTEXT_REDEFINE ||
key.referType == XSDDescription.CONTEXT_REDEFINE) {
if (referType != key.referType)
return false;
}
// condition 2: same namespace and same locatoin
if (referNS != key.referNS ||
(systemId == null && key.systemId != null) ||
systemId != null && !systemId.equals(key.systemId)) {
return false;
}
return true;
}
}
} // XSDHandler
| true | true | protected XSDocumentInfo constructTrees(Document schemaRoot, String locationHint, XSDDescription desc) {
if (schemaRoot == null) return null;
String callerTNS = desc.getTargetNamespace();
short referType = desc.getContextType();
XSDocumentInfo currSchemaInfo = null;
try {
currSchemaInfo = new XSDocumentInfo(schemaRoot, fAttributeChecker, fSymbolTable);
} catch (XMLSchemaException se) {
reportSchemaError(ELE_ERROR_CODES[referType],
new Object[]{locationHint},
DOMUtil.getRoot(schemaRoot));
return null;
}
// targetNamespace="" is not valid, issue a warning, and ignore it
if (currSchemaInfo.fTargetNamespace != null &&
currSchemaInfo.fTargetNamespace.length() == 0) {
reportSchemaWarning("EmptyTargetNamespace",
new Object[]{locationHint},
DOMUtil.getRoot(schemaRoot));
currSchemaInfo.fTargetNamespace = null;
}
if (callerTNS != null) {
// the second index to the NS_ERROR_CODES array
// if the caller/expected NS is not absent, we use the first column
int secondIdx = 0;
// for include and redefine
if (referType == XSDDescription.CONTEXT_INCLUDE ||
referType == XSDDescription.CONTEXT_REDEFINE) {
// if the referred document has no targetNamespace,
// it's a chameleon schema
if (currSchemaInfo.fTargetNamespace == null) {
currSchemaInfo.fTargetNamespace = callerTNS;
currSchemaInfo.fIsChameleonSchema = true;
}
// if the referred document has a target namespace differing
// from the caller, it's an error
else if (callerTNS != currSchemaInfo.fTargetNamespace) {
reportSchemaError(NS_ERROR_CODES[referType][secondIdx],
new Object [] {callerTNS, currSchemaInfo.fTargetNamespace},
DOMUtil.getRoot(schemaRoot));
return null;
}
}
// for instance and import, the two NS's must be the same
else if (referType != XSDDescription.CONTEXT_PREPARSE && callerTNS != currSchemaInfo.fTargetNamespace) {
reportSchemaError(NS_ERROR_CODES[referType][secondIdx],
new Object [] {callerTNS, currSchemaInfo.fTargetNamespace},
DOMUtil.getRoot(schemaRoot));
return null;
}
}
// now there is no caller/expected NS, it's an error for the referred
// document to have a target namespace, unless we are preparsing a schema
else if (currSchemaInfo.fTargetNamespace != null) {
// set the target namespace of the description
if (referType == XSDDescription.CONTEXT_PREPARSE) {
desc.setTargetNamespace(currSchemaInfo.fTargetNamespace);
callerTNS = currSchemaInfo.fTargetNamespace;
}
else {
// the second index to the NS_ERROR_CODES array
// if the caller/expected NS is absent, we use the second column
int secondIdx = 1;
reportSchemaError(NS_ERROR_CODES[referType][secondIdx],
new Object [] {callerTNS, currSchemaInfo.fTargetNamespace},
DOMUtil.getRoot(schemaRoot));
return null;
}
}
// the other cases (callerTNS == currSchemaInfo.fTargetNamespce == null)
// are valid
// a schema document can always access it's own target namespace
currSchemaInfo.addAllowedNS(currSchemaInfo.fTargetNamespace);
SchemaGrammar sg = null;
if (referType == XSDDescription.CONTEXT_INCLUDE ||
referType == XSDDescription.CONTEXT_REDEFINE) {
sg = fGrammarBucket.getGrammar(currSchemaInfo.fTargetNamespace);
}
else {
sg = new SchemaGrammar(currSchemaInfo.fTargetNamespace, desc.makeClone());
fGrammarBucket.putGrammar(sg);
}
// store the document and its location
// REVISIT: don't expose the DOM tree
//sg.addDocument(currSchemaInfo.fSchemaDoc, (String)fDoc2SystemId.get(currSchemaInfo));
sg.addDocument(null, (String)fDoc2SystemId.get(currSchemaInfo));
fDoc2XSDocumentMap.put(schemaRoot, currSchemaInfo);
Vector dependencies = new Vector();
Element rootNode = DOMUtil.getRoot(schemaRoot);
Document newSchemaRoot = null;
for (Element child = DOMUtil.getFirstChildElement(rootNode);
child != null;
child = DOMUtil.getNextSiblingElement(child)) {
String schemaNamespace=null;
String schemaHint=null;
String localName = DOMUtil.getLocalName(child);
short refType = -1;
if (localName.equals(SchemaSymbols.ELT_ANNOTATION))
continue;
else if (localName.equals(SchemaSymbols.ELT_IMPORT)) {
refType = XSDDescription.CONTEXT_IMPORT;
// have to handle some validation here too!
// call XSAttributeChecker to fill in attrs
Object[] includeAttrs = fAttributeChecker.checkAttributes(child, true, currSchemaInfo);
schemaHint = (String)includeAttrs[XSAttributeChecker.ATTIDX_SCHEMALOCATION];
schemaNamespace = (String)includeAttrs[XSAttributeChecker.ATTIDX_NAMESPACE];
if (schemaNamespace != null)
schemaNamespace = fSymbolTable.addSymbol(schemaNamespace);
// a document can't import another document with the same namespace
if (schemaNamespace == currSchemaInfo.fTargetNamespace) {
reportSchemaError("src-import.1.1", new Object [] {schemaNamespace}, child);
}
fAttributeChecker.returnAttrArray(includeAttrs, currSchemaInfo);
// if this namespace has been imported by this document,
// ignore the <import> statement
if (currSchemaInfo.isAllowedNS(schemaNamespace))
continue;
// a schema document can access it's imported namespaces
currSchemaInfo.addAllowedNS(schemaNamespace);
// also record the fact that one namespace imports another one
// convert null to ""
String tns = null2EmptyString(currSchemaInfo.fTargetNamespace);
// get all namespaces imported by this one
Vector ins = (Vector)fImportMap.get(tns);
// if no namespace was imported, create new Vector
if (ins == null) {
// record that this one imports other(s)
fAllTNSs.addElement(tns);
ins = new Vector();
fImportMap.put(tns, ins);
ins.addElement(schemaNamespace);
}
else if (!ins.contains(schemaNamespace)){
ins.addElement(schemaNamespace);
}
fSchemaGrammarDescription.reset();
fSchemaGrammarDescription.setContextType(XSDDescription.CONTEXT_IMPORT);
fSchemaGrammarDescription.setBaseSystemId((String)fDoc2SystemId.get(schemaRoot));
fSchemaGrammarDescription.setLocationHints(new String[]{schemaHint});
fSchemaGrammarDescription.setTargetNamespace(schemaNamespace);
// if a grammar with the same namespace exists (or being
// built), ignore this one (don't traverse it).
if (findGrammar(fSchemaGrammarDescription) != null)
continue;
newSchemaRoot = getSchema(fSchemaGrammarDescription, false, child);
}
else if ((localName.equals(SchemaSymbols.ELT_INCLUDE)) ||
(localName.equals(SchemaSymbols.ELT_REDEFINE))) {
// validation for redefine/include will be the same here; just
// make sure TNS is right (don't care about redef contents
// yet).
Object[] includeAttrs = fAttributeChecker.checkAttributes(child, true, currSchemaInfo);
schemaHint = (String)includeAttrs[XSAttributeChecker.ATTIDX_SCHEMALOCATION];
// store the namespace decls of the redefine element
if (localName.equals(SchemaSymbols.ELT_REDEFINE)) {
fRedefine2NSSupport.put(child, new SchemaNamespaceSupport(currSchemaInfo.fNamespaceSupport));
}
fAttributeChecker.returnAttrArray(includeAttrs, currSchemaInfo);
// schemaLocation is required on <include> and <redefine>
if (schemaHint == null) {
reportSchemaError("s4s-att-must-appear", new Object [] {
"<include> or <redefine>", "schemaLocation"},
child);
}
// pass the systemId of the current document as the base systemId
boolean mustResolve = false;
refType = XSDDescription.CONTEXT_INCLUDE;
if(localName.equals(SchemaSymbols.ELT_REDEFINE)) {
mustResolve = nonAnnotationContent(child);
refType = XSDDescription.CONTEXT_REDEFINE;
}
fSchemaGrammarDescription.reset();
fSchemaGrammarDescription.setContextType(refType);
fSchemaGrammarDescription.setBaseSystemId((String)fDoc2SystemId.get(schemaRoot));
fSchemaGrammarDescription.setLocationHints(new String[]{schemaHint});
fSchemaGrammarDescription.setTargetNamespace(callerTNS);
newSchemaRoot = getSchema(fSchemaGrammarDescription, mustResolve, child);
schemaNamespace = currSchemaInfo.fTargetNamespace;
}
else {
// no more possibility of schema references in well-formed
// schema...
break;
}
// If the schema is duplicate, we needn't call constructTrees() again.
// To handle mutual <include>s
XSDocumentInfo newSchemaInfo = null;
if (fLastSchemaWasDuplicate) {
newSchemaInfo = (XSDocumentInfo)fDoc2XSDocumentMap.get(newSchemaRoot);
}
else {
newSchemaInfo = constructTrees(newSchemaRoot, schemaHint, fSchemaGrammarDescription);
}
if (localName.equals(SchemaSymbols.ELT_REDEFINE) &&
newSchemaInfo != null) {
// must record which schema we're redefining so that we can
// rename the right things later!
fRedefine2XSDMap.put(child, newSchemaInfo);
}
if (newSchemaRoot != null) {
if (newSchemaInfo != null)
dependencies.addElement(newSchemaInfo);
newSchemaRoot = null;
}
}
fDependencyMap.put(currSchemaInfo, dependencies);
return currSchemaInfo;
} // end constructTrees
| protected XSDocumentInfo constructTrees(Document schemaRoot, String locationHint, XSDDescription desc) {
if (schemaRoot == null) return null;
String callerTNS = desc.getTargetNamespace();
short referType = desc.getContextType();
XSDocumentInfo currSchemaInfo = null;
try {
currSchemaInfo = new XSDocumentInfo(schemaRoot, fAttributeChecker, fSymbolTable);
} catch (XMLSchemaException se) {
reportSchemaError(ELE_ERROR_CODES[referType],
new Object[]{locationHint},
DOMUtil.getRoot(schemaRoot));
return null;
}
// targetNamespace="" is not valid, issue a warning, and ignore it
if (currSchemaInfo.fTargetNamespace != null &&
currSchemaInfo.fTargetNamespace.length() == 0) {
reportSchemaWarning("EmptyTargetNamespace",
new Object[]{locationHint},
DOMUtil.getRoot(schemaRoot));
currSchemaInfo.fTargetNamespace = null;
}
if (callerTNS != null) {
// the second index to the NS_ERROR_CODES array
// if the caller/expected NS is not absent, we use the first column
int secondIdx = 0;
// for include and redefine
if (referType == XSDDescription.CONTEXT_INCLUDE ||
referType == XSDDescription.CONTEXT_REDEFINE) {
// if the referred document has no targetNamespace,
// it's a chameleon schema
if (currSchemaInfo.fTargetNamespace == null) {
currSchemaInfo.fTargetNamespace = callerTNS;
currSchemaInfo.fIsChameleonSchema = true;
}
// if the referred document has a target namespace differing
// from the caller, it's an error
else if (callerTNS != currSchemaInfo.fTargetNamespace) {
reportSchemaError(NS_ERROR_CODES[referType][secondIdx],
new Object [] {callerTNS, currSchemaInfo.fTargetNamespace},
DOMUtil.getRoot(schemaRoot));
return null;
}
}
// for instance and import, the two NS's must be the same
else if (referType != XSDDescription.CONTEXT_PREPARSE && callerTNS != currSchemaInfo.fTargetNamespace) {
reportSchemaError(NS_ERROR_CODES[referType][secondIdx],
new Object [] {callerTNS, currSchemaInfo.fTargetNamespace},
DOMUtil.getRoot(schemaRoot));
return null;
}
}
// now there is no caller/expected NS, it's an error for the referred
// document to have a target namespace, unless we are preparsing a schema
else if (currSchemaInfo.fTargetNamespace != null) {
// set the target namespace of the description
if (referType == XSDDescription.CONTEXT_PREPARSE) {
desc.setTargetNamespace(currSchemaInfo.fTargetNamespace);
callerTNS = currSchemaInfo.fTargetNamespace;
}
else {
// the second index to the NS_ERROR_CODES array
// if the caller/expected NS is absent, we use the second column
int secondIdx = 1;
reportSchemaError(NS_ERROR_CODES[referType][secondIdx],
new Object [] {callerTNS, currSchemaInfo.fTargetNamespace},
DOMUtil.getRoot(schemaRoot));
return null;
}
}
// the other cases (callerTNS == currSchemaInfo.fTargetNamespce == null)
// are valid
// a schema document can always access it's own target namespace
currSchemaInfo.addAllowedNS(currSchemaInfo.fTargetNamespace);
SchemaGrammar sg = null;
if (referType == XSDDescription.CONTEXT_INCLUDE ||
referType == XSDDescription.CONTEXT_REDEFINE) {
sg = fGrammarBucket.getGrammar(currSchemaInfo.fTargetNamespace);
}
else {
sg = new SchemaGrammar(currSchemaInfo.fTargetNamespace, desc.makeClone());
fGrammarBucket.putGrammar(sg);
}
// store the document and its location
// REVISIT: don't expose the DOM tree
//sg.addDocument(currSchemaInfo.fSchemaDoc, (String)fDoc2SystemId.get(currSchemaInfo));
sg.addDocument(null, (String)fDoc2SystemId.get(currSchemaInfo.fSchemaDoc));
fDoc2XSDocumentMap.put(schemaRoot, currSchemaInfo);
Vector dependencies = new Vector();
Element rootNode = DOMUtil.getRoot(schemaRoot);
Document newSchemaRoot = null;
for (Element child = DOMUtil.getFirstChildElement(rootNode);
child != null;
child = DOMUtil.getNextSiblingElement(child)) {
String schemaNamespace=null;
String schemaHint=null;
String localName = DOMUtil.getLocalName(child);
short refType = -1;
if (localName.equals(SchemaSymbols.ELT_ANNOTATION))
continue;
else if (localName.equals(SchemaSymbols.ELT_IMPORT)) {
refType = XSDDescription.CONTEXT_IMPORT;
// have to handle some validation here too!
// call XSAttributeChecker to fill in attrs
Object[] includeAttrs = fAttributeChecker.checkAttributes(child, true, currSchemaInfo);
schemaHint = (String)includeAttrs[XSAttributeChecker.ATTIDX_SCHEMALOCATION];
schemaNamespace = (String)includeAttrs[XSAttributeChecker.ATTIDX_NAMESPACE];
if (schemaNamespace != null)
schemaNamespace = fSymbolTable.addSymbol(schemaNamespace);
// a document can't import another document with the same namespace
if (schemaNamespace == currSchemaInfo.fTargetNamespace) {
reportSchemaError("src-import.1.1", new Object [] {schemaNamespace}, child);
}
fAttributeChecker.returnAttrArray(includeAttrs, currSchemaInfo);
// if this namespace has been imported by this document,
// ignore the <import> statement
if (currSchemaInfo.isAllowedNS(schemaNamespace))
continue;
// a schema document can access it's imported namespaces
currSchemaInfo.addAllowedNS(schemaNamespace);
// also record the fact that one namespace imports another one
// convert null to ""
String tns = null2EmptyString(currSchemaInfo.fTargetNamespace);
// get all namespaces imported by this one
Vector ins = (Vector)fImportMap.get(tns);
// if no namespace was imported, create new Vector
if (ins == null) {
// record that this one imports other(s)
fAllTNSs.addElement(tns);
ins = new Vector();
fImportMap.put(tns, ins);
ins.addElement(schemaNamespace);
}
else if (!ins.contains(schemaNamespace)){
ins.addElement(schemaNamespace);
}
fSchemaGrammarDescription.reset();
fSchemaGrammarDescription.setContextType(XSDDescription.CONTEXT_IMPORT);
fSchemaGrammarDescription.setBaseSystemId((String)fDoc2SystemId.get(schemaRoot));
fSchemaGrammarDescription.setLocationHints(new String[]{schemaHint});
fSchemaGrammarDescription.setTargetNamespace(schemaNamespace);
// if a grammar with the same namespace exists (or being
// built), ignore this one (don't traverse it).
if (findGrammar(fSchemaGrammarDescription) != null)
continue;
newSchemaRoot = getSchema(fSchemaGrammarDescription, false, child);
}
else if ((localName.equals(SchemaSymbols.ELT_INCLUDE)) ||
(localName.equals(SchemaSymbols.ELT_REDEFINE))) {
// validation for redefine/include will be the same here; just
// make sure TNS is right (don't care about redef contents
// yet).
Object[] includeAttrs = fAttributeChecker.checkAttributes(child, true, currSchemaInfo);
schemaHint = (String)includeAttrs[XSAttributeChecker.ATTIDX_SCHEMALOCATION];
// store the namespace decls of the redefine element
if (localName.equals(SchemaSymbols.ELT_REDEFINE)) {
fRedefine2NSSupport.put(child, new SchemaNamespaceSupport(currSchemaInfo.fNamespaceSupport));
}
fAttributeChecker.returnAttrArray(includeAttrs, currSchemaInfo);
// schemaLocation is required on <include> and <redefine>
if (schemaHint == null) {
reportSchemaError("s4s-att-must-appear", new Object [] {
"<include> or <redefine>", "schemaLocation"},
child);
}
// pass the systemId of the current document as the base systemId
boolean mustResolve = false;
refType = XSDDescription.CONTEXT_INCLUDE;
if(localName.equals(SchemaSymbols.ELT_REDEFINE)) {
mustResolve = nonAnnotationContent(child);
refType = XSDDescription.CONTEXT_REDEFINE;
}
fSchemaGrammarDescription.reset();
fSchemaGrammarDescription.setContextType(refType);
fSchemaGrammarDescription.setBaseSystemId((String)fDoc2SystemId.get(schemaRoot));
fSchemaGrammarDescription.setLocationHints(new String[]{schemaHint});
fSchemaGrammarDescription.setTargetNamespace(callerTNS);
newSchemaRoot = getSchema(fSchemaGrammarDescription, mustResolve, child);
schemaNamespace = currSchemaInfo.fTargetNamespace;
}
else {
// no more possibility of schema references in well-formed
// schema...
break;
}
// If the schema is duplicate, we needn't call constructTrees() again.
// To handle mutual <include>s
XSDocumentInfo newSchemaInfo = null;
if (fLastSchemaWasDuplicate) {
newSchemaInfo = (XSDocumentInfo)fDoc2XSDocumentMap.get(newSchemaRoot);
}
else {
newSchemaInfo = constructTrees(newSchemaRoot, schemaHint, fSchemaGrammarDescription);
}
if (localName.equals(SchemaSymbols.ELT_REDEFINE) &&
newSchemaInfo != null) {
// must record which schema we're redefining so that we can
// rename the right things later!
fRedefine2XSDMap.put(child, newSchemaInfo);
}
if (newSchemaRoot != null) {
if (newSchemaInfo != null)
dependencies.addElement(newSchemaInfo);
newSchemaRoot = null;
}
}
fDependencyMap.put(currSchemaInfo, dependencies);
return currSchemaInfo;
} // end constructTrees
|
diff --git a/src/com/redhat/qe/xmlrpc/Session.java b/src/com/redhat/qe/xmlrpc/Session.java
index ffdc7fa..e405e50 100644
--- a/src/com/redhat/qe/xmlrpc/Session.java
+++ b/src/com/redhat/qe/xmlrpc/Session.java
@@ -1,101 +1,102 @@
package com.redhat.qe.xmlrpc;
import java.io.IOException;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthPolicy;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.contrib.auth.NegotiateScheme;
import org.apache.commons.httpclient.params.DefaultHttpParams;
import org.apache.commons.httpclient.params.HttpParams;
import org.apache.ws.commons.util.NamespaceContextImpl;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
import org.apache.xmlrpc.client.XmlRpcCommonsTransportFactory;
import org.apache.xmlrpc.common.TypeFactoryImpl;
import org.apache.xmlrpc.common.XmlRpcController;
import org.apache.xmlrpc.common.XmlRpcStreamConfig;
import org.apache.xmlrpc.parser.NullParser;
import org.apache.xmlrpc.parser.TypeParser;
import org.apache.xmlrpc.serializer.NullSerializer;
import com.redhat.qe.tools.SSLCertificateTruster;
public class Session {
protected String userName;
protected String password;
protected URL url;
protected XmlRpcClient client;
public Session(String userName, String password, URL url) {
this.userName = userName;
this.password = password;
this.url = url;
}
public void init() throws XmlRpcException, GeneralSecurityException,
IOException {
SSLCertificateTruster.trustAllCertsForApacheXMLRPC();
// setup client
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setServerURL(url);
client = new XmlRpcClient();
client.setConfig(config);
XmlRpcCommonsTransportFactory factory = new XmlRpcCommonsTransportFactory(client);
client.setTransportFactory(factory);
factory.setHttpClient(new HttpClient());
client.setTypeFactory(new MyTypeFactory(client));
factory.getHttpClient().getState().setCredentials(
new AuthScope(url.getHost(), 443, null), new UsernamePasswordCredentials(userName, password));
// register the auth scheme
AuthPolicy.registerAuthScheme("Negotiate", NegotiateScheme.class);
// include the scheme in the AuthPolicy.AUTH_SCHEME_PRIORITY preference
List<String> schemes = new ArrayList<String>();
+ schemes.add(AuthPolicy.BASIC);
schemes.add("Negotiate");
HttpParams params = DefaultHttpParams.getDefaultParams();
params.setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, schemes);
- Credentials use_jaas_creds = new Credentials() {};
+ Credentials use_jaas_creds = new UsernamePasswordCredentials(userName, password);
factory.getHttpClient().getState().setCredentials(
new AuthScope(null, -1, null),
use_jaas_creds);
}
public XmlRpcClient getClient() {
return client;
}
public class MyTypeFactory extends TypeFactoryImpl {
public MyTypeFactory(XmlRpcController pController) {
super(pController);
}
@Override
public TypeParser getParser(XmlRpcStreamConfig pConfig,
NamespaceContextImpl pContext, String pURI, String pLocalName) {
if ("".equals(pURI) && NullSerializer.NIL_TAG.equals(pLocalName)) {
return new NullParser();
} else {
return super.getParser(pConfig, pContext, pURI, pLocalName);
}
}
}
}
| false | true | public void init() throws XmlRpcException, GeneralSecurityException,
IOException {
SSLCertificateTruster.trustAllCertsForApacheXMLRPC();
// setup client
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setServerURL(url);
client = new XmlRpcClient();
client.setConfig(config);
XmlRpcCommonsTransportFactory factory = new XmlRpcCommonsTransportFactory(client);
client.setTransportFactory(factory);
factory.setHttpClient(new HttpClient());
client.setTypeFactory(new MyTypeFactory(client));
factory.getHttpClient().getState().setCredentials(
new AuthScope(url.getHost(), 443, null), new UsernamePasswordCredentials(userName, password));
// register the auth scheme
AuthPolicy.registerAuthScheme("Negotiate", NegotiateScheme.class);
// include the scheme in the AuthPolicy.AUTH_SCHEME_PRIORITY preference
List<String> schemes = new ArrayList<String>();
schemes.add("Negotiate");
HttpParams params = DefaultHttpParams.getDefaultParams();
params.setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, schemes);
Credentials use_jaas_creds = new Credentials() {};
factory.getHttpClient().getState().setCredentials(
new AuthScope(null, -1, null),
use_jaas_creds);
}
| public void init() throws XmlRpcException, GeneralSecurityException,
IOException {
SSLCertificateTruster.trustAllCertsForApacheXMLRPC();
// setup client
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setServerURL(url);
client = new XmlRpcClient();
client.setConfig(config);
XmlRpcCommonsTransportFactory factory = new XmlRpcCommonsTransportFactory(client);
client.setTransportFactory(factory);
factory.setHttpClient(new HttpClient());
client.setTypeFactory(new MyTypeFactory(client));
factory.getHttpClient().getState().setCredentials(
new AuthScope(url.getHost(), 443, null), new UsernamePasswordCredentials(userName, password));
// register the auth scheme
AuthPolicy.registerAuthScheme("Negotiate", NegotiateScheme.class);
// include the scheme in the AuthPolicy.AUTH_SCHEME_PRIORITY preference
List<String> schemes = new ArrayList<String>();
schemes.add(AuthPolicy.BASIC);
schemes.add("Negotiate");
HttpParams params = DefaultHttpParams.getDefaultParams();
params.setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, schemes);
Credentials use_jaas_creds = new UsernamePasswordCredentials(userName, password);
factory.getHttpClient().getState().setCredentials(
new AuthScope(null, -1, null),
use_jaas_creds);
}
|
diff --git a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.persistence/src/org/wso2/developerstudio/eclipse/gmf/esb/internal/persistence/AddressEndPointTransformer.java b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.persistence/src/org/wso2/developerstudio/eclipse/gmf/esb/internal/persistence/AddressEndPointTransformer.java
index 80aa49f85..2fc646c79 100755
--- a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.persistence/src/org/wso2/developerstudio/eclipse/gmf/esb/internal/persistence/AddressEndPointTransformer.java
+++ b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.persistence/src/org/wso2/developerstudio/eclipse/gmf/esb/internal/persistence/AddressEndPointTransformer.java
@@ -1,263 +1,265 @@
/*
* Copyright 2009-2010 WSO2, Inc. (http://wso2.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.developerstudio.eclipse.gmf.esb.internal.persistence;
import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;
import org.apache.synapse.Mediator;
import org.apache.synapse.SynapseArtifact;
import org.apache.synapse.config.xml.AnonymousListMediator;
import org.apache.synapse.config.xml.SwitchCase;
import org.apache.synapse.endpoints.AddressEndpoint;
import org.apache.synapse.endpoints.Endpoint;
import org.apache.synapse.endpoints.EndpointDefinition;
import org.apache.synapse.mediators.base.SequenceMediator;
import org.apache.synapse.mediators.builtin.PropertyMediator;
import org.apache.synapse.mediators.builtin.SendMediator;
import org.apache.synapse.mediators.filters.SwitchMediator;
import org.apache.synapse.util.xpath.SynapseXPath;
import org.eclipse.core.runtime.Assert;
import org.eclipse.emf.ecore.EObject;
import org.wso2.developerstudio.eclipse.gmf.esb.AddressEndPoint;
import org.wso2.developerstudio.eclipse.gmf.esb.EndPointAddressingVersion;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbNode;
import org.wso2.developerstudio.eclipse.gmf.esb.FailoverEndPoint;
import org.wso2.developerstudio.eclipse.gmf.esb.LoadBalanceEndPoint;
import org.wso2.developerstudio.eclipse.gmf.esb.Sequence;
import org.wso2.developerstudio.eclipse.gmf.esb.SequenceInputConnector;
import org.wso2.developerstudio.eclipse.gmf.esb.persistence.EsbNodeTransformer;
import org.wso2.developerstudio.eclipse.gmf.esb.persistence.TransformationInfo;
/**
* {@link EsbNodeTransformer} responsible for transforming
* {@link org.wso2.developerstudio.eclipse.gmf.esb.EndPoint} model objects into
* corresponding synapse artifact(s).
*/
public class AddressEndPointTransformer extends AbstractEsbNodeTransformer {
/**
* {@inheritDoc}
*/
public void transform(TransformationInfo info, EsbNode subject)
throws Exception {
// Check subject.
Assert.isTrue(subject instanceof AddressEndPoint, "Invalid subject");
AddressEndPoint visualEndPoint = (AddressEndPoint) subject;
// Tag the outbound message.
// String pathId = UUID.randomUUID().toString();
// PropertyMediator tagMediator = new PropertyMediator();
// tagMediator.setAction(PropertyMediator.ACTION_SET);
// tagMediator.setName("outPathId");
// tagMediator.setValue(pathId);
// info.getParentSequence().addChild(tagMediator);
// Send the message.
// TODO: We're using a default endpoint here, need to handle other cases
// on the real implementation.
SendMediator sendMediator = null;
if (info.getPreviouNode() instanceof org.wso2.developerstudio.eclipse.gmf.esb.SendMediator) {
if(visualEndPoint.getInputConnector().getIncomingLinks().get(0).getSource().eContainer() instanceof org.wso2.developerstudio.eclipse.gmf.esb.Sequence){
sendMediator=(SendMediator)info.getCurrentReferredSequence().getList().get(info.getCurrentReferredSequence().getList().size()-1);
}else{
sendMediator = (SendMediator) info.getParentSequence().getList()
.get(info.getParentSequence().getList().size() - 1);
}
}
else {
sendMediator = new SendMediator();
info.getParentSequence().addChild(sendMediator);
}
AddressEndpoint synapseAddEP = new AddressEndpoint();
EndpointDefinition synapseEPDef = new EndpointDefinition();
synapseEPDef.setAddress(visualEndPoint.getURI());
// TODO: Configure endpoint with values extracted from the visual model.
// synapseEPDef.setCharSetEncoding(charSetEncoding);
if (visualEndPoint.isAddressingEnabled()) {
synapseEPDef.setAddressingOn(true);
synapseEPDef.setUseSeparateListener(visualEndPoint
.isAddressingSeparateListener());
synapseEPDef
.setAddressingVersion((visualEndPoint
.getAddressingVersion() == EndPointAddressingVersion.FINAL) ? "final"
: "submission");
}
if (visualEndPoint.isReliableMessagingEnabled()) {
synapseEPDef.setReliableMessagingOn(visualEndPoint
.isReliableMessagingEnabled());
// synapseEPDef.setWsRMPolicyKey(visualEndPoint.getReliableMessagingPolicy().getKeyValue());
}
if (visualEndPoint.isSecurityEnabled()) {
synapseEPDef.setSecurityOn(true);
// synapseEPDef.setWsSecPolicyKey(visualEndPoint.getSecurityPolicy().getKeyValue());
}
synapseEPDef.setRetryDurationOnTimeout((int) (visualEndPoint
.getRetryDelay()));
if (ValidationUtil.isInt(visualEndPoint.getRetryErrorCodes()))
synapseEPDef.addRetryDisabledErrorCode(ValidationUtil
.getInt(visualEndPoint.getRetryErrorCodes()));
if (ValidationUtil.isInt(visualEndPoint.getSuspendErrorCodes()))
synapseEPDef.addSuspendErrorCode(ValidationUtil
.getInt(visualEndPoint.getSuspendErrorCodes()));
synapseAddEP.setDefinition(synapseEPDef);
sendMediator.setEndpoint(synapseAddEP);
// Process endpoint output.
// SwitchMediator outSwitch = null;
// // List<Mediator> outSequenceMediators = rootService
// // .getTargetInLineOutSequence().getList();
// List<Mediator> outSequenceMediators = info.getOriginOutSequence()
// .getList();
//
// if (!outSequenceMediators.isEmpty()) {
// Mediator firstMediator = outSequenceMediators.get(0);
// if (firstMediator instanceof SwitchMediator) {
// outSwitch = (SwitchMediator) firstMediator;
// }
// }
//
// // Introduce output switch if necessary.
// if (null == outSwitch) {
// outSwitch = new SwitchMediator();
// outSwitch.setSource(new SynapseXPath("$ctx.outPathId"));
// outSequenceMediators.add(0, outSwitch);
// }
//
// // Add path case.
// SwitchCase pathCase = new SwitchCase();
// pathCase.setRegex(Pattern.compile(pathId));
// AnonymousListMediator pathCaseMediator = new AnonymousListMediator();
// pathCase.setCaseMediator(pathCaseMediator);
// // Remove the path tag introduced earlier.
// PropertyMediator tagRemoveMediator = new PropertyMediator();
// tagRemoveMediator.setAction(PropertyMediator.ACTION_REMOVE);
// tagRemoveMediator.setName("outPathId");
// pathCaseMediator.addChild(tagRemoveMediator);
// outSwitch.addCase(pathCase);
if (!info.isEndPointFound) {
info.isEndPointFound = true;
info.firstEndPoint = visualEndPoint;
}
+ if(visualEndPoint.getOutputConnector().getOutgoingLink() !=null){
if(!(visualEndPoint.getOutputConnector().getOutgoingLink().getTarget() instanceof SequenceInputConnector)){
info.setParentSequence(info.getOriginOutSequence());
info.setTraversalDirection(TransformationInfo.TRAVERSAL_DIRECTION_OUT);
}else if(visualEndPoint.getInputConnector().getIncomingLinks().get(0).getSource().eContainer() instanceof Sequence){
info.setParentSequence(info.getCurrentReferredSequence());
}
+ }
// Transform endpoint output data flow.
doTransform(info, visualEndPoint.getOutputConnector());
}
public void createSynapseObject(TransformationInfo info, EObject subject,
List<Endpoint> endPoints) {
Assert.isTrue(subject instanceof AddressEndPoint, "Invalid subject");
AddressEndPoint addressEndPoint = (AddressEndPoint) subject;
AddressEndpoint synapseAddEP = new AddressEndpoint();
EndpointDefinition synapseEPDef = new EndpointDefinition();
synapseEPDef.setAddress(addressEndPoint.getURI());
// TODO: Configure endpoint with values extracted from the visual model.
// synapseEPDef.setCharSetEncoding(charSetEncoding);
if (addressEndPoint.isAddressingEnabled()) {
synapseEPDef.setAddressingOn(true);
synapseEPDef.setUseSeparateListener(addressEndPoint
.isAddressingSeparateListener());
synapseEPDef
.setAddressingVersion((addressEndPoint
.getAddressingVersion() == EndPointAddressingVersion.FINAL) ? "final"
: "submission");
}
if (addressEndPoint.isReliableMessagingEnabled()) {
synapseEPDef.setReliableMessagingOn(addressEndPoint
.isReliableMessagingEnabled());
// synapseEPDef.setWsRMPolicyKey(visualEndPoint.getReliableMessagingPolicy().getKeyValue());
}
if (addressEndPoint.isSecurityEnabled()) {
synapseEPDef.setSecurityOn(true);
// synapseEPDef.setWsSecPolicyKey(visualEndPoint.getSecurityPolicy().getKeyValue());
}
synapseEPDef.setRetryDurationOnTimeout((int) (addressEndPoint
.getRetryDelay()));
if (ValidationUtil.isInt(addressEndPoint.getRetryErrorCodes()))
synapseEPDef.addRetryDisabledErrorCode(ValidationUtil
.getInt(addressEndPoint.getRetryErrorCodes()));
if (ValidationUtil.isInt(addressEndPoint.getSuspendErrorCodes()))
synapseEPDef.addSuspendErrorCode(ValidationUtil
.getInt(addressEndPoint.getSuspendErrorCodes()));
synapseAddEP.setDefinition(synapseEPDef);
// sendMediator.setEndpoint(synapseAddEP);
Endpoint endPoint = (Endpoint) synapseAddEP;
endPoints.add(endPoint);
// Next node may be a Failover endPoint. So that this should be edited
// to be compatible with that also.
info.setParentSequence(info.getOriginOutSequence());
info.setTraversalDirection(TransformationInfo.TRAVERSAL_DIRECTION_OUT);
// Transform endpoint output data flow.
if (!info.isOutputPathSet) {
if (info.firstEndPoint instanceof FailoverEndPoint) {
try {
doTransform(info,
((FailoverEndPoint) info.firstEndPoint)
.getWestOutputConnector());
} catch (Exception e) {
// TODO Auto-generated catch block
System.out
.println("Error addressEndpointTransformer class.");
e.printStackTrace();
}
}
if (info.firstEndPoint instanceof LoadBalanceEndPoint) {
try {
doTransform(info,
((LoadBalanceEndPoint) info.firstEndPoint)
.getWestOutputConnector());
} catch (Exception e) {
// TODO Auto-generated catch block
System.out
.println("Error addressEndpointTransformer class.");
e.printStackTrace();
}
}
info.isOutputPathSet = true;
}
// return synapseAddEP;
}
public void transformWithinSequence(TransformationInfo information,
EsbNode subject, SequenceMediator sequence) throws Exception {
// TODO Auto-generated method stub
}
}
| false | true | public void transform(TransformationInfo info, EsbNode subject)
throws Exception {
// Check subject.
Assert.isTrue(subject instanceof AddressEndPoint, "Invalid subject");
AddressEndPoint visualEndPoint = (AddressEndPoint) subject;
// Tag the outbound message.
// String pathId = UUID.randomUUID().toString();
// PropertyMediator tagMediator = new PropertyMediator();
// tagMediator.setAction(PropertyMediator.ACTION_SET);
// tagMediator.setName("outPathId");
// tagMediator.setValue(pathId);
// info.getParentSequence().addChild(tagMediator);
// Send the message.
// TODO: We're using a default endpoint here, need to handle other cases
// on the real implementation.
SendMediator sendMediator = null;
if (info.getPreviouNode() instanceof org.wso2.developerstudio.eclipse.gmf.esb.SendMediator) {
if(visualEndPoint.getInputConnector().getIncomingLinks().get(0).getSource().eContainer() instanceof org.wso2.developerstudio.eclipse.gmf.esb.Sequence){
sendMediator=(SendMediator)info.getCurrentReferredSequence().getList().get(info.getCurrentReferredSequence().getList().size()-1);
}else{
sendMediator = (SendMediator) info.getParentSequence().getList()
.get(info.getParentSequence().getList().size() - 1);
}
}
else {
sendMediator = new SendMediator();
info.getParentSequence().addChild(sendMediator);
}
AddressEndpoint synapseAddEP = new AddressEndpoint();
EndpointDefinition synapseEPDef = new EndpointDefinition();
synapseEPDef.setAddress(visualEndPoint.getURI());
// TODO: Configure endpoint with values extracted from the visual model.
// synapseEPDef.setCharSetEncoding(charSetEncoding);
if (visualEndPoint.isAddressingEnabled()) {
synapseEPDef.setAddressingOn(true);
synapseEPDef.setUseSeparateListener(visualEndPoint
.isAddressingSeparateListener());
synapseEPDef
.setAddressingVersion((visualEndPoint
.getAddressingVersion() == EndPointAddressingVersion.FINAL) ? "final"
: "submission");
}
if (visualEndPoint.isReliableMessagingEnabled()) {
synapseEPDef.setReliableMessagingOn(visualEndPoint
.isReliableMessagingEnabled());
// synapseEPDef.setWsRMPolicyKey(visualEndPoint.getReliableMessagingPolicy().getKeyValue());
}
if (visualEndPoint.isSecurityEnabled()) {
synapseEPDef.setSecurityOn(true);
// synapseEPDef.setWsSecPolicyKey(visualEndPoint.getSecurityPolicy().getKeyValue());
}
synapseEPDef.setRetryDurationOnTimeout((int) (visualEndPoint
.getRetryDelay()));
if (ValidationUtil.isInt(visualEndPoint.getRetryErrorCodes()))
synapseEPDef.addRetryDisabledErrorCode(ValidationUtil
.getInt(visualEndPoint.getRetryErrorCodes()));
if (ValidationUtil.isInt(visualEndPoint.getSuspendErrorCodes()))
synapseEPDef.addSuspendErrorCode(ValidationUtil
.getInt(visualEndPoint.getSuspendErrorCodes()));
synapseAddEP.setDefinition(synapseEPDef);
sendMediator.setEndpoint(synapseAddEP);
// Process endpoint output.
// SwitchMediator outSwitch = null;
// // List<Mediator> outSequenceMediators = rootService
// // .getTargetInLineOutSequence().getList();
// List<Mediator> outSequenceMediators = info.getOriginOutSequence()
// .getList();
//
// if (!outSequenceMediators.isEmpty()) {
// Mediator firstMediator = outSequenceMediators.get(0);
// if (firstMediator instanceof SwitchMediator) {
// outSwitch = (SwitchMediator) firstMediator;
// }
// }
//
// // Introduce output switch if necessary.
// if (null == outSwitch) {
// outSwitch = new SwitchMediator();
// outSwitch.setSource(new SynapseXPath("$ctx.outPathId"));
// outSequenceMediators.add(0, outSwitch);
// }
//
// // Add path case.
// SwitchCase pathCase = new SwitchCase();
// pathCase.setRegex(Pattern.compile(pathId));
// AnonymousListMediator pathCaseMediator = new AnonymousListMediator();
// pathCase.setCaseMediator(pathCaseMediator);
// // Remove the path tag introduced earlier.
// PropertyMediator tagRemoveMediator = new PropertyMediator();
// tagRemoveMediator.setAction(PropertyMediator.ACTION_REMOVE);
// tagRemoveMediator.setName("outPathId");
// pathCaseMediator.addChild(tagRemoveMediator);
// outSwitch.addCase(pathCase);
if (!info.isEndPointFound) {
info.isEndPointFound = true;
info.firstEndPoint = visualEndPoint;
}
if(!(visualEndPoint.getOutputConnector().getOutgoingLink().getTarget() instanceof SequenceInputConnector)){
info.setParentSequence(info.getOriginOutSequence());
info.setTraversalDirection(TransformationInfo.TRAVERSAL_DIRECTION_OUT);
}else if(visualEndPoint.getInputConnector().getIncomingLinks().get(0).getSource().eContainer() instanceof Sequence){
info.setParentSequence(info.getCurrentReferredSequence());
}
// Transform endpoint output data flow.
doTransform(info, visualEndPoint.getOutputConnector());
}
| public void transform(TransformationInfo info, EsbNode subject)
throws Exception {
// Check subject.
Assert.isTrue(subject instanceof AddressEndPoint, "Invalid subject");
AddressEndPoint visualEndPoint = (AddressEndPoint) subject;
// Tag the outbound message.
// String pathId = UUID.randomUUID().toString();
// PropertyMediator tagMediator = new PropertyMediator();
// tagMediator.setAction(PropertyMediator.ACTION_SET);
// tagMediator.setName("outPathId");
// tagMediator.setValue(pathId);
// info.getParentSequence().addChild(tagMediator);
// Send the message.
// TODO: We're using a default endpoint here, need to handle other cases
// on the real implementation.
SendMediator sendMediator = null;
if (info.getPreviouNode() instanceof org.wso2.developerstudio.eclipse.gmf.esb.SendMediator) {
if(visualEndPoint.getInputConnector().getIncomingLinks().get(0).getSource().eContainer() instanceof org.wso2.developerstudio.eclipse.gmf.esb.Sequence){
sendMediator=(SendMediator)info.getCurrentReferredSequence().getList().get(info.getCurrentReferredSequence().getList().size()-1);
}else{
sendMediator = (SendMediator) info.getParentSequence().getList()
.get(info.getParentSequence().getList().size() - 1);
}
}
else {
sendMediator = new SendMediator();
info.getParentSequence().addChild(sendMediator);
}
AddressEndpoint synapseAddEP = new AddressEndpoint();
EndpointDefinition synapseEPDef = new EndpointDefinition();
synapseEPDef.setAddress(visualEndPoint.getURI());
// TODO: Configure endpoint with values extracted from the visual model.
// synapseEPDef.setCharSetEncoding(charSetEncoding);
if (visualEndPoint.isAddressingEnabled()) {
synapseEPDef.setAddressingOn(true);
synapseEPDef.setUseSeparateListener(visualEndPoint
.isAddressingSeparateListener());
synapseEPDef
.setAddressingVersion((visualEndPoint
.getAddressingVersion() == EndPointAddressingVersion.FINAL) ? "final"
: "submission");
}
if (visualEndPoint.isReliableMessagingEnabled()) {
synapseEPDef.setReliableMessagingOn(visualEndPoint
.isReliableMessagingEnabled());
// synapseEPDef.setWsRMPolicyKey(visualEndPoint.getReliableMessagingPolicy().getKeyValue());
}
if (visualEndPoint.isSecurityEnabled()) {
synapseEPDef.setSecurityOn(true);
// synapseEPDef.setWsSecPolicyKey(visualEndPoint.getSecurityPolicy().getKeyValue());
}
synapseEPDef.setRetryDurationOnTimeout((int) (visualEndPoint
.getRetryDelay()));
if (ValidationUtil.isInt(visualEndPoint.getRetryErrorCodes()))
synapseEPDef.addRetryDisabledErrorCode(ValidationUtil
.getInt(visualEndPoint.getRetryErrorCodes()));
if (ValidationUtil.isInt(visualEndPoint.getSuspendErrorCodes()))
synapseEPDef.addSuspendErrorCode(ValidationUtil
.getInt(visualEndPoint.getSuspendErrorCodes()));
synapseAddEP.setDefinition(synapseEPDef);
sendMediator.setEndpoint(synapseAddEP);
// Process endpoint output.
// SwitchMediator outSwitch = null;
// // List<Mediator> outSequenceMediators = rootService
// // .getTargetInLineOutSequence().getList();
// List<Mediator> outSequenceMediators = info.getOriginOutSequence()
// .getList();
//
// if (!outSequenceMediators.isEmpty()) {
// Mediator firstMediator = outSequenceMediators.get(0);
// if (firstMediator instanceof SwitchMediator) {
// outSwitch = (SwitchMediator) firstMediator;
// }
// }
//
// // Introduce output switch if necessary.
// if (null == outSwitch) {
// outSwitch = new SwitchMediator();
// outSwitch.setSource(new SynapseXPath("$ctx.outPathId"));
// outSequenceMediators.add(0, outSwitch);
// }
//
// // Add path case.
// SwitchCase pathCase = new SwitchCase();
// pathCase.setRegex(Pattern.compile(pathId));
// AnonymousListMediator pathCaseMediator = new AnonymousListMediator();
// pathCase.setCaseMediator(pathCaseMediator);
// // Remove the path tag introduced earlier.
// PropertyMediator tagRemoveMediator = new PropertyMediator();
// tagRemoveMediator.setAction(PropertyMediator.ACTION_REMOVE);
// tagRemoveMediator.setName("outPathId");
// pathCaseMediator.addChild(tagRemoveMediator);
// outSwitch.addCase(pathCase);
if (!info.isEndPointFound) {
info.isEndPointFound = true;
info.firstEndPoint = visualEndPoint;
}
if(visualEndPoint.getOutputConnector().getOutgoingLink() !=null){
if(!(visualEndPoint.getOutputConnector().getOutgoingLink().getTarget() instanceof SequenceInputConnector)){
info.setParentSequence(info.getOriginOutSequence());
info.setTraversalDirection(TransformationInfo.TRAVERSAL_DIRECTION_OUT);
}else if(visualEndPoint.getInputConnector().getIncomingLinks().get(0).getSource().eContainer() instanceof Sequence){
info.setParentSequence(info.getCurrentReferredSequence());
}
}
// Transform endpoint output data flow.
doTransform(info, visualEndPoint.getOutputConnector());
}
|
diff --git a/src/drbd/utilities/RoboTest.java b/src/drbd/utilities/RoboTest.java
index ff186e01..7ca78a51 100644
--- a/src/drbd/utilities/RoboTest.java
+++ b/src/drbd/utilities/RoboTest.java
@@ -1,2773 +1,2773 @@
/*
* This file is part of DRBD Management Console by LINBIT HA-Solutions GmbH
* written by Rasto Levrinc.
*
* Copyright (C) 2009, LINBIT HA-Solutions GmbH.
*
* DRBD Management Console 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, or (at your option)
* any later version.
*
* DRBD Management Console 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 drbd; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package drbd.utilities;
import drbd.data.Host;
import java.awt.Robot;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.MouseInfo;
import java.awt.geom.Point2D;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
/**
* This class is used to test the GUI.
*
* @author Rasto Levrinc
* @version $Id$
*
*/
public final class RoboTest {
/** Screen device. */
private static final GraphicsDevice SCREEN_DEVICE =
GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
/** Don't move the mosue pointer smothly. */
private static final boolean MOVE_MOUSE_FAST = false;
/** Previous position of the mouse. */
private static Point2D prevP = null;
/** Whether the test was aborted. */
private static volatile boolean aborted = false;
/** Slow down the animation. */
private static float slowFactor = 1f;
/** Private constructor, cannot be instantiated. */
private RoboTest() {
/* Cannot be instantiated. */
}
/** Abort if mouse moved. */
private static boolean abortWithMouseMovement() {
if (MouseInfo.getPointerInfo() == null) {
return false;
}
final Point2D loc =
Tools.getGUIData().getMainFrame().getLocationOnScreen();
Point2D p = MouseInfo.getPointerInfo().getLocation();
double x = p.getX() - loc.getX();
if (x > 1536 || x < -100) {
int i = 0;
while (x > 1536 || x < -100) {
if (i % 5 == 0) {
Tools.info("sleep: " + x);
}
Tools.sleep(1000);
if (MouseInfo.getPointerInfo() != null) {
p = MouseInfo.getPointerInfo().getLocation();
x = p.getX() - loc.getX();
}
i++;
}
prevP = p;
return false;
}
if (prevP != null
&& (Math.abs(p.getX() - prevP.getX()) > 200
|| Math.abs(p.getY() - prevP.getY()) > 200)) {
prevP = null;
Tools.info("test aborted");
aborted = true;
return true;
}
prevP = p;
return false;
}
/**
* Restore mouse when the program was interrupted, while a mouse button
* was pressed.
*/
public static void restoreMouse() {
Robot robot = null;
try {
robot = new Robot(SCREEN_DEVICE);
} catch (final java.awt.AWTException e) {
Tools.appWarning("Robot error");
}
if (robot == null) {
return;
}
leftClick(robot);
rightClick(robot);
}
/** Starts automatic left clicker in 10 seconds. */
public static void startClicker(final int duration,
final boolean lazy) {
startClicker0(duration, lazy, InputEvent.BUTTON1_MASK,
10, /* after click */
10, /* after release */
500, /* lazy after click */
100); /* lazy after release */
}
/** Starts automatic right clicker in 10 seconds. */
public static void startRightClicker(final int duration,
final boolean lazy) {
startClicker0(duration, lazy, InputEvent.BUTTON3_MASK,
10, /* after click */
500, /* after release */
500, /* lazy after click */
5000); /* lazy after release */
}
/** Starts automatic clicker in 10 seconds. */
private static void startClicker0(final int duration,
final boolean lazy,
final int buttonMask,
final int timeAfterClick,
final int timeAfterRelase,
final int timeAfterClickLazy,
final int timeAfterRelaseLazy) {
Tools.info("start click test in 10 seconds");
prevP = null;
final Thread thread = new Thread(new Runnable() {
public void run() {
Tools.sleep(10000);
Robot rbt = null;
try {
rbt = new Robot(SCREEN_DEVICE);
} catch (final java.awt.AWTException e) {
Tools.appWarning("Robot error");
}
if (rbt == null) {
return;
}
final Robot robot = rbt;
final long startTime = System.currentTimeMillis();
while (true) {
robot.mousePress(buttonMask);
if (lazy) {
Tools.sleep(timeAfterClickLazy);
} else {
Tools.sleep(timeAfterClick);
}
robot.mouseRelease(buttonMask);
if (lazy) {
Tools.sleep(timeAfterRelaseLazy);
} else {
Tools.sleep(timeAfterRelase);
}
robot.keyPress(KeyEvent.VK_ESCAPE);
Tools.sleep(100);
robot.keyRelease(KeyEvent.VK_ESCAPE);
if (abortWithMouseMovement()) {
break;
}
final long current = System.currentTimeMillis();
if ((current - startTime) > duration * 60 * 1000) {
break;
}
Tools.sleep(500);
}
Tools.info("click test done");
}
});
thread.start();
}
/** Starts automatic mouse mover in 10 seconds. */
public static void startMover(final int duration,
final boolean lazy) {
Tools.info("start mouse move test in 10 seconds");
prevP = null;
final Thread thread = new Thread(new Runnable() {
public void run() {
Tools.sleep(10000);
Robot rbt = null;
try {
rbt = new Robot(SCREEN_DEVICE);
} catch (final java.awt.AWTException e) {
Tools.appWarning("Robot error");
}
if (rbt == null) {
return;
}
final Robot robot = rbt;
final int xOffset = getOffset();
final Point2D origP = MouseInfo.getPointerInfo().getLocation();
final int origX = (int) origP.getX();
final int origY = (int) origP.getY();
Tools.info("move mouse to the end position");
Tools.sleep(5000);
final Point2D endP = MouseInfo.getPointerInfo().getLocation();
final int endX = (int) endP.getX();
final int endY = (int) endP.getY();
int destX = origX;
int destY = origY;
Tools.info("test started");
final long startTime = System.currentTimeMillis();
while (true) {
final Point2D p =
MouseInfo.getPointerInfo().getLocation();
final int x = (int) p.getX();
final int y = (int) p.getY();
int directionX;
int directionY;
if (x < destX) {
directionX = 1;
} else if (x > destX) {
directionX = -1;
} else {
if (destX == endX) {
destX = origX;
directionX = -1;
} else {
destX = endX;
directionX = 1;
}
}
if (y < destY) {
directionY = 1;
} else if (y > destY) {
directionY = -1;
} else {
if (destY == endY) {
destY = origY;
directionY = -1;
} else {
destY = endY;
directionY = 1;
}
}
final int directionX0 = directionX;
final int directionY0 = directionY;
robot.mouseMove(
(int) p.getX() + xOffset + directionX0,
(int) p.getY() + directionY0);
if (lazy) {
Tools.sleep(40);
} else {
Tools.sleep(5);
}
if (abortWithMouseMovement()) {
break;
}
final long current = System.currentTimeMillis();
if ((current - startTime) > duration * 60 * 1000) {
break;
}
}
Tools.info("mouse move test done");
}
});
thread.start();
}
/** workaround for dual monitors that are flipped. */
private static int getOffset() {
final Point2D p = MouseInfo.getPointerInfo().getLocation();
final GraphicsDevice[] devices =
GraphicsEnvironment.getLocalGraphicsEnvironment()
.getScreenDevices();
int xOffset = 0;
if (devices.length >= 2) {
final int x1 =
devices[0].getDefaultConfiguration().getBounds().x;
final int x2 =
devices[1].getDefaultConfiguration().getBounds().x;
if (x1 > x2) {
xOffset = -x1;
}
}
return xOffset;
}
/** Automatic tests. */
public static void startTest(final String index, final Host host) {
aborted = false;
Tools.info("start test " + index + " in 3 seconds");
final Thread thread = new Thread(new Runnable() {
public void run() {
Tools.sleep(3000);
Robot robot = null;
try {
robot = new Robot(SCREEN_DEVICE);
} catch (final java.awt.AWTException e) {
Tools.appWarning("Robot error");
}
if (robot == null) {
return;
}
final String selected =
host.getCluster().getBrowser().getTree()
.getLastSelectedPathComponent().toString();
if ("Services".equals(selected)
|| Tools.getString("ClusterBrowser.ClusterManager").equals(
selected)) {
if ("1".equals(index)) {
/* pacemaker */
int i = 1;
while (!aborted) {
final long startTime = System.currentTimeMillis();
Tools.info("test" + index + " no " + i);
startTest1(robot, host);
final int secs = (int) (System.currentTimeMillis()
- startTime) / 1000;
Tools.info("test" + index + " no " + i + ", secs: "
+ secs);
i++;
}
} else if ("2".equals(index)) {
/* resource sets */
int i = 1;
while (!aborted) {
final long startTime = System.currentTimeMillis();
Tools.info("test" + index + " no " + i);
startTest2(robot, host);
final int secs = (int) (System.currentTimeMillis()
- startTime) / 1000;
Tools.info("test" + index + " no " + i + ", secs: "
+ secs);
i++;
}
} else if ("3".equals(index)) {
/* pacemaker drbd */
final int i = 1;
final long startTime = System.currentTimeMillis();
Tools.info("test" + index + " no " + i);
startTest3(robot);
final int secs = (int) (System.currentTimeMillis()
- startTime) / 1000;
Tools.info("test" + index + " no " + i + ", secs: "
+ secs);
} else if ("4".equals(index)) {
/* placeholders 6 dummies */
final int i = 1;
final long startTime = System.currentTimeMillis();
Tools.info("test" + index + " no " + i);
startTest4(robot, host);
final int secs = (int) (System.currentTimeMillis()
- startTime) / 1000;
Tools.info("test" + index + " no " + i + ", secs: "
+ secs);
} else if ("5".equals(index)) {
int i = 1;
while (true) {
/* pacemaker */
final long startTime = System.currentTimeMillis();
Tools.info("test" + index + " no " + i);
startTest5(robot, host);
final int secs = (int) (System.currentTimeMillis()
- startTime) / 1000;
Tools.info("test" + index + " no " + i + ", secs: "
+ secs);
i++;
}
} else if ("6".equals(index)) {
int i = 1;
while (true) {
/* pacemaker */
final long startTime = System.currentTimeMillis();
Tools.info("test" + index + " no " + i);
startTest6(robot, host);
final int secs = (int) (System.currentTimeMillis()
- startTime) / 1000;
Tools.info("test" + index + " no " + i + ", secs: "
+ secs);
i++;
}
} else if ("7".equals(index)) {
/* pacemaker leak test */
final long startTime = System.currentTimeMillis();
Tools.info("test" + index);
startTest7(robot, host);
final int secs = (int) (System.currentTimeMillis()
- startTime) / 1000;
Tools.info("test" + index + ", secs: "
+ secs);
} else if ("8".equals(index)) {
/* pacemaker leak test */
final long startTime = System.currentTimeMillis();
Tools.info("test" + index);
startTest8(robot, host);
final int secs = (int) (System.currentTimeMillis()
- startTime) / 1000;
Tools.info("test" + index + ", secs: "
+ secs);
} else if ("A".equals(index)) {
/* pacemaker leak test group */
final long startTime = System.currentTimeMillis();
Tools.info("test" + index);
startTestA(robot, host);
final int secs = (int) (System.currentTimeMillis()
- startTime) / 1000;
Tools.info("test" + index + ", secs: "
+ secs);
} else if ("B".equals(index)) {
/* pacemaker leak test clone */
final long startTime = System.currentTimeMillis();
Tools.info("test" + index);
startTestB(robot, host);
final int secs = (int) (System.currentTimeMillis()
- startTime) / 1000;
Tools.info("test" + index + ", secs: "
+ secs);
} else if ("C".equals(index)) {
/* pacemaker master/slave test */
final long startTime = System.currentTimeMillis();
Tools.info("test" + index);
startTestC(robot, host);
final int secs = (int) (System.currentTimeMillis()
- startTime) / 1000;
Tools.info("test" + index + ", secs: "
+ secs);
} else if ("9".equals(index)) {
/* all pacemaker tests */
int i = 1;
while (true) {
final long startTime = System.currentTimeMillis();
Tools.info("test" + index + " no " + i);
startTest1(robot, host);
startTest2(robot, host);
final int secs = (int) (System.currentTimeMillis()
- startTime) / 1000;
Tools.info("test" + index + " no " + i + ", secs: "
+ secs);
i++;
}
}
} else if ("Storage (DRBD)".equals(selected)) {
if ("1".equals(index)) {
/* DRBD new style config */
int i = 1;
while (!aborted) {
final long startTime = System.currentTimeMillis();
Tools.info("test" + index + " no " + i);
startDRBDTest1(robot, host);
final int secs = (int) (System.currentTimeMillis()
- startTime) / 1000;
Tools.info("test" + index + " no " + i + ", secs: "
+ secs);
i++;
}
} else if ("2".equals(index)) {
/* DRBD */
int i = 1;
while (!aborted) {
final long startTime = System.currentTimeMillis();
Tools.info("test" + index + " no " + i);
startDRBDTest2(robot, host);
final int secs = (int) (System.currentTimeMillis()
- startTime) / 1000;
Tools.info("test" + index + " no " + i + ", secs: "
+ secs);
i++;
}
} else if ("3".equals(index)) {
/* DRBD old style config */
int i = 1;
while (!aborted) {
final long startTime = System.currentTimeMillis();
Tools.info("test" + index + " no " + i);
startDRBDTest3(robot, host);
final int secs = (int) (System.currentTimeMillis()
- startTime) / 1000;
Tools.info("test" + index + " no " + i + ", secs: "
+ secs);
i++;
}
} else if ("4".equals(index)) {
/* DRBD old style config */
int i = 1;
while (!aborted) {
final long startTime = System.currentTimeMillis();
Tools.info("test" + index + " no " + i);
startDRBDTest4(robot, host);
final int secs = (int) (System.currentTimeMillis()
- startTime) / 1000;
Tools.info("test" + index + " no " + i + ", secs: "
+ secs);
i++;
}
}
} else if ("VMs".equals(selected)) {
if ("1".equals(index) || "2".equals(index)) {
/* VMs */
int i = 1;
while (!aborted) {
final long startTime = System.currentTimeMillis();
Tools.info("test" + index + " no " + i);
startVMTest1and2("vm-test" + index, robot, host);
final int secs = (int) (System.currentTimeMillis()
- startTime) / 1000;
Tools.info("test" + index + " no " + i + ", secs: "
+ secs);
i++;
}
}
}
Tools.info(selected + " test " + index + " done");
}
});
thread.start();
}
/** Check test. */
private static void checkTest(final Host host,
final String test,
final double no) {
if (!aborted) {
host.checkPCMKTest(test, no);
}
}
/** Check DRBD test. */
private static void checkDRBDTest(final Host host,
final String test,
final double no) {
if (!aborted) {
host.checkDRBDTest(test, no);
}
}
/** Check VM test. */
private static void checkVMTest(final Host host,
final String test,
final double no) {
if (!aborted) {
host.checkVMTest(test, no);
}
}
/** TEST 1. */
private static void startTest1(final Robot robot, final Host host) {
slowFactor = 0.2f;
host.getSSH().installTestFiles();
aborted = false;
/* create IPaddr2 with 192.168.100.100 ip */
final int ipX = 235;
final int ipY = 255;
final int gx = 230;
final int gy = 374;
final int popX = 343;
final int popY = 300;
final int statefulX = 500;
final int statefulY = 255;
disableStonith(robot, host);
checkTest(host, "test1", 1);
moveTo(robot, ipX, ipY);
rightClick(robot); /* popup */
moveTo(robot, ipX + 57, ipY + 28);
moveTo(robot, ipX + 270, ipY + 28);
moveTo(robot, ipX + 267, ipY + 52);
leftClick(robot); /* choose ipaddr */
removeResource(robot, ipX, ipY, -15);
/* again */
moveTo(robot, ipX, ipY);
rightClick(robot); /* popup */
moveTo(robot, ipX + 57, ipY + 28);
moveTo(robot, ipX + 270, ipY + 28);
moveTo(robot, ipX + 267, ipY + 52);
leftClick(robot); /* choose ipaddr */
moveTo(robot, 1072, 405);
leftClick(robot); /* pull down */
moveTo(robot, 1044, 450);
leftClick(robot); /* choose */
sleep(1000);
press(robot, KeyEvent.VK_1);
press(robot, KeyEvent.VK_0);
press(robot, KeyEvent.VK_0);
sleep(1000);
setTimeouts(robot);
moveTo(robot, 814, 189);
sleep(6000); /* ptest */
leftClick(robot); /* apply */
checkTest(host, "test1", 2); /* 2 */
/* pingd */
moveTo(robot, 1105, 298);
leftPress(robot); /* scroll bar */
moveTo(robot, 1105, 510);
leftRelease(robot);
moveTo(robot, 1076, 420);
leftClick(robot);
moveTo(robot, 1037, 487);
leftClick(robot); /* no ping */
moveTo(robot, 809, 192); /* ptest */
sleep(2000);
leftClick(robot); /* apply */
sleep(2000);
checkTest(host, "test1", 2.1); /* 2.1 */
moveTo(robot, 1076, 420);
leftClick(robot);
moveTo(robot, 1067, 445);
leftClick(robot); /* default */
moveTo(robot, 809, 192); /* ptest */
sleep(2000);
leftClick(robot); /* apply */
moveTo(robot, 1105, 298);
leftPress(robot); /* scroll bar */
moveTo(robot, 1105, 550);
leftRelease(robot);
/* group with dummy resources */
moveTo(robot, gx, gy);
sleep(1000);
rightClick(robot); /* popup */
moveTo(robot, gx + 46, gy + 11);
sleep(1000);
leftClick(robot); /* choose group */
sleep(3000);
/* remove it */
removeResource(robot, gx, gy, 0);
moveTo(robot, gx, gy);
sleep(1000);
rightClick(robot); /* popup */
moveTo(robot, gx + 46, gy + 11);
sleep(1000);
leftClick(robot); /* choose group */
sleep(3000);
rightClick(robot); /* group popup */
moveTo(robot, gx + 80, gy + 20);
moveTo(robot, gx + 84, gy + 22);
moveTo(robot, gx + 580, gy + 22);
sleep(1000);
typeDummy(robot);
sleep(1000);
/* remove it */
removeResource(robot, gx, gy, 0);
/* group with dummy resources, once again */
moveTo(robot, gx, gy);
sleep(1000);
rightClick(robot); /* popup */
moveTo(robot, gx + 46, gy + 11);
sleep(1000);
leftClick(robot); /* choose group */
sleep(3000);
rightClick(robot); /* group popup */
moveTo(robot, gx + 80, gy + 20);
moveTo(robot, gx + 84, gy + 22);
moveTo(robot, gx + 580, gy + 22);
sleep(1000);
typeDummy(robot);
sleep(1000);
moveTo(robot, 125, 320);
sleep(1000);
rightClick(robot);
sleep(1000);
moveTo(robot, 150, 611);
leftClick(robot); /* remove service */
removeResource(robot, gx, gy, 0);
/* group with dummy resources, once again */
moveTo(robot, gx, gy);
sleep(1000);
rightClick(robot); /* popup */
moveTo(robot, gx + 46, gy + 11);
sleep(1000);
leftClick(robot); /* choose group */
sleep(3000);
rightClick(robot); /* group popup */
moveTo(robot, gx + 80, gy + 20);
moveTo(robot, gx + 84, gy + 22);
moveTo(robot, gx + 580, gy + 22);
sleep(1000);
typeDummy(robot);
sleep(1000);
removeResource(robot, gx, gy, 0);
/* once again */
moveTo(robot, gx, gy);
sleep(1000);
rightClick(robot); /* popup */
moveTo(robot, gx + 46, gy + 11);
sleep(1000);
leftClick(robot); /* choose group */
sleep(3000);
checkTest(host, "test1", 2); /* 2 */
rightClick(robot); /* group popup */
moveTo(robot, gx + 80, gy + 20);
moveTo(robot, gx + 84, gy + 22);
moveTo(robot, gx + 580, gy + 22);
sleep(1000);
typeDummy(robot);
sleep(1000);
setTimeouts(robot);
moveTo(robot, 809, 192); /* ptest */
sleep(2000);
leftClick(robot); /* apply */
for (int i = 0; i < 2; i++) {
/* another group resource */
sleep(20000);
moveTo(robot, gx + 46, gy + 11);
rightClick(robot); /* group popup */
sleep(2000 + i * 500);
moveTo(robot, gx + 80, gy + 20);
moveTo(robot, gx + 84, gy + 22);
moveTo(robot, gx + 580, gy + 22);
sleep(1000);
typeDummy(robot);
sleep(i * 300);
setTimeouts(robot);
moveTo(robot, 809, 192); /* ptest */
sleep(6000);
leftClick(robot); /* apply */
sleep(1000);
}
sleep(4000);
checkTest(host, "test1", 3); /* 3 */
/* constraints */
addConstraint(robot, gx, gy, 0, true, -1);
checkTest(host, "test1", 3.1); /* 3.1 */
/* move up, move down */
moveTo(robot, 137, 344);
rightClick(robot);
sleep(1000);
moveTo(robot, 221, 493);
leftClick(robot); /* move res 3 up */
Tools.sleep(10000);
checkTest(host, "test1", 3.11); /* 3.11 */
moveTo(robot, 137, 328);
rightClick(robot);
moveTo(robot, 236, 515);
leftClick(robot); /* move res 3 down */
Tools.sleep(10000);
checkTest(host, "test1", 3.12); /* 3.12 */
/* same as */
moveTo(robot, 125, 345);
sleep(1000);
leftClick(robot);
moveTo(robot, 1105, 298);
leftPress(robot); /* scroll bar */
moveTo(robot, 1105, 510);
leftRelease(robot);
sleep(1000);
moveTo(robot, 1078, 484);
leftClick(robot);
sleep(1000);
moveTo(robot, 1078, 535);
sleep(1000);
leftClick(robot); /* choose another dummy */
sleep(1000);
moveTo(robot, 809, 192); /* ptest */
sleep(4000);
leftClick(robot); /* apply */
sleep(4000);
checkTest(host, "test1", 3.2); /* 3.2 */
moveTo(robot, 1078 , 477);
leftClick(robot);
sleep(1000);
moveTo(robot, 1078 , 507);
leftClick(robot); /* choose "nothing selected */
sleep(1000);
moveTo(robot, 809, 192); /* ptest */
sleep(4000);
leftClick(robot); /* apply */
sleep(9000);
moveTo(robot, 1105, 298);
leftPress(robot); /* scroll bar back */
moveTo(robot, 1105, 150);
leftRelease(robot);
checkTest(host, "test1", 4); /* 4 */
/* locations */
moveTo(robot, ipX + 20, ipY);
leftClick(robot); /* choose ip */
setLocation(robot, new Integer[]{KeyEvent.VK_I});
sleep(3000);
checkTest(host, "test1", 4.1); /* 4.1 */
setLocation(robot, new Integer[]{KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_MINUS,
KeyEvent.VK_I});
sleep(3000);
checkTest(host, "test1", 4.2); /* 4.2 */
setLocation(robot, new Integer[]{KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_PLUS});
sleep(3000);
checkTest(host, "test1", 4.3); /* 4.3 */
setLocation(robot, new Integer[]{KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE});
sleep(3000);
checkTest(host, "test1", 4.4); /* 4.4 */
removeConstraint(robot, popX, popY);
sleep(3000);
checkTest(host, "test1", 5); /* 5 */
sleep(1000);
addConstraint(robot, gx, gy, 9, true, -1);
sleep(5000);
checkTest(host, "test1", 6); /* 6 */
removeOrder(robot, popX, popY);
sleep(4000);
checkTest(host, "test1", 7);
addOrder(robot, popX, popY);
sleep(4000);
checkTest(host, "test1", 8);
removeColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 9);
addColocation(robot, popX, popY);
sleep(4000);
checkTest(host, "test1", 10);
removeColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.1);
removeOrder(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.2);
addConstraintOrderOnly(robot, gx, gy, 0, 25, 0, true, -1);
sleep(4000);
checkTest(host, "test1", 10.3);
addColocation(robot, popX, popY);
sleep(4000);
checkTest(host, "test1", 10.4);
removeOrder(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.5);
removeColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.6);
addConstraintColocationOnly(robot, gx, gy, 0, 25, 0, true, -1);
sleep(4000);
checkTest(host, "test1", 10.7);
addOrder(robot, popX, popY);
sleep(4000);
checkTest(host, "test1", 10.8);
removeConstraint(robot, popX, popY);
sleep(4000);
checkTest(host, "test1", 10.9);
addConstraint(robot, ipX, ipY, 0, false, -1);
sleep(5000);
checkTest(host, "test1", 10.91);
removeOrder(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.92);
addOrder(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.93);
removeColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.94);
addColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.95);
removeColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.96);
removeOrder(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.97);
- addConstraintColocationOnly(robot, ipX, ipY, 0, 100, 0, false, -1);
+ addConstraintColocationOnly(robot, ipX, ipY, -20, 100, 0, false, -1);
sleep(5000);
checkTest(host, "test1", 10.98);
removeColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.99);
- addConstraintOrderOnly(robot, ipX, ipY, 0, 100, 0, false, -1);
+ addConstraintOrderOnly(robot, ipX, ipY, -20, 100, 0, false, -1);
sleep(5000);
checkTest(host, "test1", 11);
addColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.1);
removeConstraint(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.2);
addConstraint(robot, ipX, ipY, 60, false, -1);
sleep(5000);
checkTest(host, "test1", 11.3);
stopResource(robot, ipX, ipY, 0);
sleep(5000);
checkTest(host, "test1", 11.4);
resetStartStopResource(robot, ipX, ipY);
sleep(5000);
checkTest(host, "test1", 11.5);
moveTo(robot, ipX + 20, ipY + 10);
leftClick(robot); /* choose ip */
stopResource(robot, 1020, 180, 10); /* actions menu stop */
sleep(5000);
checkTest(host, "test1", 11.501);
moveTo(robot, ipX + 20, ipY + 10);
leftClick(robot); /* choose ip */
startResource(robot, 1020, 180, 20); /* actions menu start */
sleep(5000);
checkTest(host, "test1", 11.502);
resetStartStopResource(robot, ipX, ipY);
sleep(5000);
checkTest(host, "test1", 11.5);
removeColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.51);
addColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.52);
removeOrder(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.53);
addOrder(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.54);
removeColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.55);
removeOrder(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.56);
- addConstraintOrderOnly(robot, ipX, ipY, 0, 100, 55, false, -1);
+ addConstraintOrderOnly(robot, ipX, ipY, -20, 100, 55, false, -1);
sleep(5000);
checkTest(host, "test1", 11.57);
removeOrder(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.58);
- addConstraintColocationOnly(robot, ipX, ipY, 0, 100, 55, false, -1);
+ addConstraintColocationOnly(robot, ipX, ipY, -20, 100, 55, false, -1);
sleep(5000);
checkTest(host, "test1", 11.59);
addOrder(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.6);
removeConstraint(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.7);
addConstraint(robot, gx, gy, 9, true, -1);
sleep(5000);
checkTest(host, "test1", 11.8);
/** Add m/s Stateful resource */
moveTo(robot, statefulX, statefulY);
rightClick(robot); /* popup */
moveTo(robot, statefulX + 137, statefulY + 8);
moveTo(robot, statefulX + 137, statefulY + 28);
moveTo(robot, statefulX + 412, statefulY + 27);
moveTo(robot, statefulX + 432, statefulY + 70);
moveTo(robot, statefulX + 665, statefulY + 70);
sleep(1000);
press(robot, KeyEvent.VK_S);
sleep(200);
press(robot, KeyEvent.VK_T);
sleep(200);
press(robot, KeyEvent.VK_A);
sleep(200);
press(robot, KeyEvent.VK_T);
sleep(200);
press(robot, KeyEvent.VK_E);
sleep(200);
press(robot, KeyEvent.VK_F);
sleep(200);
press(robot, KeyEvent.VK_ENTER); /* choose Stateful */
sleep(1000);
moveTo(robot, 812, 179);
sleep(1000);
leftClick(robot); /* apply */
sleep(4000);
/* set clone max to 1 */
moveTo(robot, 978, 381);
sleep(3000);
leftClick(robot); /* Clone Max */
sleep(3000);
press(robot, KeyEvent.VK_BACK_SPACE);
sleep(3000);
press(robot, KeyEvent.VK_1);
setTimeouts(robot);
moveTo(robot, 812, 179);
sleep(3000);
leftClick(robot); /* apply */
sleep(3000);
checkTest(host, "test1", 12);
stopResource(robot, statefulX, statefulY, 0);
sleep(3000);
checkTest(host, "test1", 13);
startResource(robot, statefulX, statefulY, 0);
sleep(10000);
checkTest(host, "test1", 14);
unmanageResource(robot, statefulX, statefulY, 0);
sleep(3000);
checkTest(host, "test1", 15);
manageResource(robot, statefulX, statefulY, 0);
sleep(3000);
checkTest(host, "test1", 16);
/* IP addr cont. */
stopResource(robot, ipX, ipY, 0);
sleep(3000);
checkTest(host, "test1", 17);
startResource(robot, ipX, ipY, 0);
sleep(3000);
checkTest(host, "test1", 18);
unmanageResource(robot, ipX, ipY, 0);
sleep(3000);
checkTest(host, "test1", 19);
manageResource(robot, ipX, ipY, 0);
sleep(3000);
checkTest(host, "test1", 20);
migrateResource(robot, ipX, ipY, 0);
sleep(3000);
checkTest(host, "test1", 21);
unmigrateResource(robot, ipX, ipY, 0);
sleep(3000);
checkTest(host, "test1", 22);
/* Group cont. */
stopResource(robot, gx, gy, 15);
sleep(10000);
checkTest(host, "test1", 23);
startResource(robot, gx, gy, 15);
sleep(8000);
checkTest(host, "test1", 24);
unmanageResource(robot, gx, gy, 15);
sleep(5000);
checkTest(host, "test1", 25);
manageResource(robot, gx, gy, 15);
sleep(5000);
checkTest(host, "test1", 26);
migrateResource(robot, gx, gy, 25);
sleep(5000);
checkTest(host, "test1", 27);
unmigrateResource(robot, gx, gy, 25);
sleep(5000);
checkTest(host, "test1", 28);
stopResource(robot, ipX, ipY, 0);
sleep(5000);
stopGroup(robot, gx, gy, 15);
sleep(5000);
stopGroup(robot, statefulX, statefulY, 0);
stopEverything(robot); /* to be sure */
sleep(5000);
checkTest(host, "test1", 29);
if (true) {
removeResource(robot, ipX, ipY, -15);
sleep(5000);
removeGroup(robot, gx, gy, 0);
sleep(5000);
removeGroup(robot, statefulX, statefulY, -15);
} else {
removeEverything(robot);
}
if (!aborted) {
Tools.sleep(240000);
}
checkTest(host, "test1", 1);
}
/** Stop everything. */
private static void stopEverything(final Robot robot) {
sleep(10000);
moveTo(robot, 335, 129); /* advanced */
sleep(2000);
leftClick(robot);
sleep(2000);
moveTo(robot, 671, 568);
rightClick(robot); /* popup */
sleep(3000);
moveTo(robot, 732, 644);
sleep(3000);
leftClick(robot);
moveTo(robot, 335, 129); /* not advanced */
sleep(2000);
leftClick(robot);
sleep(2000);
}
/** Remove everything. */
private static void removeEverything(final Robot robot) {
sleep(10000);
moveTo(robot, 335, 129); /* advanced */
sleep(2000);
leftClick(robot);
sleep(2000);
moveTo(robot, 671, 568);
rightClick(robot); /* popup */
sleep(3000);
moveTo(robot, 732, 674);
sleep(3000);
leftClick(robot);
confirmRemove(robot);
sleep(3000);
leftClick(robot);
moveTo(robot, 335, 129); /* not advanced */
sleep(2000);
leftClick(robot);
sleep(2000);
}
/** Disable stonith if it is enabled. */
private static void disableStonith(final Robot robot, final Host host) {
moveTo(robot, 271, 250);
leftClick(robot); /* global options */
final String stonith = host.getCluster().getBrowser()
.getClusterStatus().getGlobalParam("stonith-enabled");
if (stonith == null || "true".equals(stonith)) {
moveTo(robot, 944, 298);
leftClick(robot); /* disable stonith */
}
moveTo(robot, 1073, 337);
leftClick(robot); /* no quorum policy */
moveTo(robot, 1058, 350);
leftClick(robot); /* ignore */
moveTo(robot, 828, 183);
sleep(2000);
leftClick(robot); /* apply */
}
/** TEST 2. */
private static void startTest2(final Robot robot, final Host host) {
slowFactor = 0.3f;
host.getSSH().installTestFiles();
aborted = false;
final int dummy1X = 235;
final int dummy1Y = 255;
final int dummy2X = 545;
final int dummy2Y = 255;
final int dummy3X = 235;
final int dummy3Y = 500;
final int dummy4X = 545;
final int dummy4Y = 390;
final int phX = 445;
final int phY = 390;
disableStonith(robot, host);
checkTest(host, "test2", 1);
/* create 4 dummies */
chooseDummy(robot, dummy1X, dummy1Y, false);
chooseDummy(robot, dummy2X, dummy2Y, false);
chooseDummy(robot, dummy3X, dummy3Y, false);
chooseDummy(robot, dummy4X, dummy4Y, false);
checkTest(host, "test2", 2);
/* placeholder */
moveTo(robot, phX, phY);
rightClick(robot);
sleep(2000);
moveTo(robot, phX + 30 , phY + 45);
sleep(2000);
leftClick(robot);
checkTest(host, "test2", 3);
/* constraints */
addConstraint(robot, phX, phY, 0, false, -1); /* with dummy 1 */
sleep(2000);
moveTo(robot, 809, 192); /* ptest */
sleep(2000);
leftClick(robot); /* apply */
sleep(5000);
checkTest(host, "test2", 4);
final int dum1PopX = dummy1X + 130;
final int dum1PopY = dummy1Y + 50;
for (int i = 0; i < 1; i++) {
removeOrder(robot, dum1PopX, dum1PopY);
sleep(4000);
checkTest(host, "test2", 5);
addOrder(robot, dum1PopX, dum1PopY);
sleep(4000);
checkTest(host, "test2", 6);
removeColocation(robot, dum1PopX, dum1PopY);
sleep(5000);
checkTest(host, "test2", 7);
addColocation(robot, dum1PopX, dum1PopY);
sleep(4000);
checkTest(host, "test2", 8);
}
addConstraint(robot, dummy3X, dummy3Y, 80, false, -1); /* with ph */
sleep(5000);
checkTest(host, "test2", 9);
final int dum3PopX = dummy3X + 130;
final int dum3PopY = dummy3Y - 50;
for (int i = 0; i < 2; i++) {
removeColocation(robot, dum3PopX, dum3PopY);
sleep(4000);
checkTest(host, "test2", 9.1);
addColocation(robot, dum3PopX, dum3PopY);
sleep(4000);
checkTest(host, "test2", 9.2);
removeOrder(robot, dum3PopX, dum3PopY);
sleep(5000);
checkTest(host, "test2", 9.3);
addOrder(robot, dum3PopX, dum3PopY);
sleep(4000);
checkTest(host, "test2", 9.4);
}
addConstraint(robot, phX, phY, 0, false, -1); /* with dummy 2 */
sleep(5000);
checkTest(host, "test2", 10);
addConstraint(robot, dummy4X, dummy4Y, 80, false, -1); /* with ph */
sleep(5000);
checkTest(host, "test2", 11);
/* ph -> dummy2 */
final int dum2PopX = dummy2X - 10;
final int dum2PopY = dummy2Y + 70;
removeConstraint(robot, dum2PopX, dum2PopY);
sleep(4000);
checkTest(host, "test2", 11.1);
addConstraintOrderOnly(robot,
phX,
phY,
-50,
20,
0,
false,
-1); /* with dummy 2 */
sleep(4000);
checkTest(host, "test2", 11.2);
removeOrder(robot, dum2PopX, dum2PopY);
sleep(4000);
checkTest(host, "test2", 11.3);
addConstraintColocationOnly(robot,
phX,
phY,
-50,
23,
0,
false,
-1); /* with dummy 2 */
sleep(4000);
checkTest(host, "test2", 11.4);
addOrder(robot, dum2PopX, dum2PopY);
sleep(4000);
checkTest(host, "test2", 11.5);
/* dummy4 -> ph */
final int dum4PopX = dummy4X - 40;
final int dum4PopY = dummy4Y - 10;
removeConstraint(robot, dum4PopX, dum4PopY);
sleep(4000);
checkTest(host, "test2", 11.6);
moveTo(robot, dummy4X + 20, dummy4Y + 5);
sleep(1000);
rightClick(robot); /* workaround for the next popup not working. */
sleep(1000);
rightClick(robot); /* workaround for the next popup not working. */
sleep(1000);
addConstraintColocationOnly(robot,
dummy4X,
dummy4Y,
-50,
93,
80,
false,
-1); /* with ph */
sleep(4000);
checkTest(host, "test2", 11.7);
removeColocation(robot, dum4PopX, dum4PopY);
sleep(4000);
checkTest(host, "test2", 11.8);
moveTo(robot, dummy4X + 20, dummy4Y + 5);
sleep(1000);
rightClick(robot); /* workaround for the next popup not working. */
sleep(1000);
addConstraintOrderOnly(robot,
dummy4X,
dummy4Y,
-50,
90,
80,
false,
-1); /* ph 2 */
sleep(4000);
checkTest(host, "test2", 11.9);
addColocation(robot, dum4PopX, dum4PopY);
sleep(4000);
checkTest(host, "test2", 11.91);
/* remove one dummy */
stopResource(robot, dummy1X, dummy1Y, 0);
sleep(5000);
checkTest(host, "test2", 11.92);
removeResource(robot, dummy1X, dummy1Y, -15);
sleep(5000);
checkTest(host, "test2", 12);
stopResource(robot, dummy2X, dummy2Y, 0);
sleep(10000);
stopResource(robot, dummy3X, dummy3Y, 0);
sleep(10000);
stopResource(robot, dummy3X, dummy3Y, 0);
sleep(10000);
stopResource(robot, dummy4X, dummy4Y, 0);
stopEverything(robot);
sleep(10000);
checkTest(host, "test2", 12.5);
if (true) {
/* remove placeholder */
moveTo(robot, phX , phY);
rightClick(robot);
sleep(1000);
moveTo(robot, phX + 40 , phY + 80);
leftClick(robot);
confirmRemove(robot);
sleep(5000);
/* remove rest of the dummies */
removeResource(robot, dummy2X, dummy2Y, -15);
sleep(5000);
checkTest(host, "test2", 14);
removeResource(robot, dummy3X, dummy3Y, -15);
sleep(5000);
checkTest(host, "test2", 15);
removeResource(robot, dummy4X, dummy4Y, -15);
sleep(5000);
} else {
removeEverything(robot);
}
if (!aborted) {
Tools.sleep(240000);
}
checkTest(host, "test2", 16);
}
/** TEST 4. */
private static void startTest4(final Robot robot, final Host host) {
slowFactor = 0.5f;
host.getSSH().installTestFiles();
aborted = false;
final int dummy1X = 235;
final int dummy1Y = 255;
final int dummy2X = 545;
final int dummy2Y = 255;
final int dummy3X = 235;
final int dummy3Y = 394;
final int dummy4X = 545;
final int dummy4Y = 394;
final int dummy5X = 235;
final int dummy5Y = 553;
final int dummy6X = 545;
final int dummy6Y = 553;
final int ph1X = 445;
final int ph1Y = 314;
final int ph2X = 445;
final int ph2Y = 473;
disableStonith(robot, host);
checkTest(host, "test4", 1);
/* create 6 dummies */
chooseDummy(robot, dummy1X, dummy1Y, false);
chooseDummy(robot, dummy2X, dummy2Y, false);
chooseDummy(robot, dummy3X, dummy3Y, false);
chooseDummy(robot, dummy4X, dummy4Y, false);
chooseDummy(robot, dummy5X, dummy5Y, false);
chooseDummy(robot, dummy6X, dummy6Y, false);
/* 2 placeholders */
while (true) {
moveTo(robot, ph1X, ph1Y);
rightClick(robot);
sleep(2000);
moveTo(robot, ph1X + 30 , ph1Y + 45);
sleep(2000);
leftClick(robot);
moveTo(robot, ph2X, ph2Y);
rightClick(robot);
sleep(2000);
moveTo(robot, ph2X + 30 , ph2Y + 45);
sleep(2000);
leftClick(robot);
checkTest(host, "test4", 2);
/* constraints */
addConstraint(robot, dummy5X, dummy5Y, 160, false, -1); /* with ph2 */
addConstraint(robot, dummy6X, dummy6Y, 160, false, -1); /* with ph2 */
addConstraint(robot, ph2X, ph2Y, 60, false, -1); /* with dummy 3 */
addConstraint(robot, ph2X, ph2Y, 60, false, -1); /* with dummy 4 */
addConstraint(robot, dummy3X, dummy3Y, 80, false, -1); /* with ph1 */
addConstraint(robot, dummy4X, dummy4Y, 80, false, -1); /* with ph1 */
addConstraint(robot, ph1X, ph1Y, 5, false, -1); /* with dummy 1 */
addConstraint(robot, ph1X, ph1Y, 5, false, -1); /* with dummy 2 */
checkTest(host, "test4", 3);
/* TEST test */
removePlaceHolder(robot, ph1X, ph1Y);
removePlaceHolder(robot, ph2X, ph2Y);
}
}
/** TEST 5. */
private static void startTest5(final Robot robot, final Host host) {
slowFactor = 0.2f;
host.getSSH().installTestFiles();
aborted = false;
final int dummy1X = 235;
final int dummy1Y = 255;
final int dummy2X = 235;
final int dummy2Y = 500;
final int ph1X = 315;
final int ph1Y = 394;
//disableStonith(robot, host);
/* create 2 dummies */
checkTest(host, "test5", 1);
/* placeholders */
moveTo(robot, ph1X, ph1Y);
rightClick(robot);
sleep(2000);
moveTo(robot, ph1X + 30 , ph1Y + 45);
sleep(2000);
leftClick(robot);
chooseDummy(robot, dummy1X, dummy1Y, false);
chooseDummy(robot, dummy2X, dummy2Y, false);
//checkTest(host, "test5", 2);
addConstraint(robot, dummy2X, dummy2Y, 35, false, -1);
addConstraint(robot, ph1X, ph1Y, 5, false, -1);
moveTo(robot, ph1X, ph1Y);
sleep(2000);
leftClick(robot);
sleep(2000);
moveTo(robot, 809, 192); /* ptest */
sleep(2000);
leftClick(robot); /* apply */
checkTest(host, "test5", 3);
leftClick(robot); /* apply */
removeEverything(robot);
sleep(5000);
checkTest(host, "test5", 4);
//int dum1PopX = dummy1X + 70;
//int dum1PopY = dummy1Y + 60;
///* constraints */
//for (int i = 1; i <=10; i++) {
// addConstraint(robot, dummy1X, dummy1Y, 5, false, -1);
// moveTo(robot, ph1X , ph1Y);
// sleep(2000);
// leftClick(robot);
// sleep(2000);
// moveTo(robot, 809, 192); /* ptest */
// sleep(2000);
// leftClick(robot); /* apply */
// checkTest(host, "test5", 2);
// removeConstraint(robot, dum1PopX, dum1PopY);
// checkTest(host, "test5", 3);
// addConstraint(robot, ph1X, ph1Y, 5, false, -1);
// moveTo(robot, ph1X, ph1Y);
// sleep(2000);
// leftClick(robot);
// sleep(2000);
// moveTo(robot, 809, 192); /* ptest */
// sleep(2000);
// leftClick(robot); /* apply */
// checkTest(host, "test5", 4);
// removeConstraint(robot, dum1PopX, dum1PopY);
// checkTest(host, "test5", 3);
// Tools.info("i: " + i);
//}
}
/** TEST 6. */
private static void startTest6(final Robot robot, final Host host) {
slowFactor = 0.2f;
host.getSSH().installTestFiles();
aborted = false;
final int dummy1X = 235;
final int dummy1Y = 255;
final int ph1X = 315;
final int ph1Y = 394;
//disableStonith(robot, host);
/* create 2 dummies */
//checkTest(host, "test5", 1);
/* placeholders */
moveTo(robot, ph1X, ph1Y);
rightClick(robot);
sleep(2000);
moveTo(robot, ph1X + 30 , ph1Y + 45);
sleep(2000);
leftClick(robot);
chooseDummy(robot, dummy1X, dummy1Y, false);
//checkTest(host, "test5", 2);
final int dum1PopX = dummy1X + 70;
final int dum1PopY = dummy1Y + 60;
while (true) {
addConstraint(robot, ph1X, ph1Y, 5, false, -1);
if (!aborted) {
Tools.sleep(2000);
}
removeConstraint(robot, dum1PopX, dum1PopY);
}
}
private static void startTest7(final Robot robot, final Host host) {
slowFactor = 0.5f;
host.getSSH().installTestFiles();
aborted = false;
final int dummy1X = 235;
final int dummy1Y = 255;
disableStonith(robot, host);
for (int i = 30; i > 0; i--) {
Tools.info("I: " + i);
checkTest(host, "test7", 1);
/* create dummy */
sleep(5000);
chooseDummy(robot, dummy1X, dummy1Y, false);
checkTest(host, "test7", 2);
sleep(5000);
stopResource(robot, dummy1X, dummy1Y, 0);
checkTest(host, "test7", 3);
sleep(5000);
removeResource(robot, dummy1X, dummy1Y, -15);
}
System.gc();
}
private static void startTestA(final Robot robot, final Host host) {
slowFactor = 0.5f;
host.getSSH().installTestFiles();
aborted = false;
final int gx = 235;
final int gy = 255;
disableStonith(robot, host);
for (int i = 20; i > 0; i--) {
Tools.info("I: " + i);
checkTest(host, "testA", 1);
/* group with dummy resources */
moveTo(robot, gx, gy);
sleep(1000);
rightClick(robot); /* popup */
moveTo(robot, gx + 46, gy + 11);
sleep(1000);
leftClick(robot); /* choose group */
sleep(3000);
/* create dummy */
moveTo(robot, gx + 46, gy + 11);
rightClick(robot); /* group popup */
sleep(2000 + i * 500);
moveTo(robot, gx + 80, gy + 20);
moveTo(robot, gx + 84, gy + 22);
moveTo(robot, gx + 580, gy + 22);
sleep(1000);
typeDummy(robot);
sleep(i * 300);
setTimeouts(robot);
moveTo(robot, 809, 192); /* ptest */
sleep(6000);
leftClick(robot); /* apply */
sleep(6000);
checkTest(host, "testA", 2);
stopResource(robot, gx, gy, 0);
sleep(6000);
checkTest(host, "testA", 3);
removeResource(robot, gx, gy, 0);
}
System.gc();
}
private static void startTestB(final Robot robot, final Host host) {
slowFactor = 0.5f;
host.getSSH().installTestFiles();
aborted = false;
final int dummy1X = 235;
final int dummy1Y = 255;
disableStonith(robot, host);
for (int i = 20; i > 0; i--) {
Tools.info("I: " + i);
checkTest(host, "testB", 1);
/* create dummy */
sleep(5000);
chooseDummy(robot, dummy1X, dummy1Y, true);
checkTest(host, "testB", 2);
sleep(5000);
stopResource(robot, dummy1X, dummy1Y, 0);
checkTest(host, "testB", 3);
sleep(5000);
removeResource(robot, dummy1X, dummy1Y, -15);
}
System.gc();
}
private static void startTestC(final Robot robot, final Host host) {
slowFactor = 0.5f;
host.getSSH().installTestFiles();
final int statefulX = 500;
final int statefulY = 255;
disableStonith(robot, host);
for (int i = 20; i > 0; i--) {
Tools.info("I: " + i);
checkTest(host, "testC", 1);
/** Add m/s Stateful resource */
moveTo(robot, statefulX, statefulY);
rightClick(robot); /* popup */
moveTo(robot, statefulX + 137, statefulY + 8);
moveTo(robot, statefulX + 137, statefulY + 28);
moveTo(robot, statefulX + 412, statefulY + 27);
moveTo(robot, statefulX + 432, statefulY + 70);
moveTo(robot, statefulX + 665, statefulY + 70);
sleep(1000);
press(robot, KeyEvent.VK_S);
sleep(200);
press(robot, KeyEvent.VK_T);
sleep(200);
press(robot, KeyEvent.VK_A);
sleep(200);
press(robot, KeyEvent.VK_T);
sleep(200);
press(robot, KeyEvent.VK_E);
sleep(200);
press(robot, KeyEvent.VK_F);
sleep(200);
press(robot, KeyEvent.VK_ENTER); /* choose Stateful */
sleep(1000);
moveTo(robot, 812, 179);
sleep(1000);
leftClick(robot); /* apply */
sleep(4000);
stopResource(robot, statefulX, statefulY, -20);
checkTest(host, "testC", 2);
sleep(5000);
removeResource(robot, statefulX, statefulY, -20);
}
}
private static void startTest8(final Robot robot, final Host host) {
slowFactor = 0.5f;
host.getSSH().installTestFiles();
aborted = false;
final int dummy1X = 540;
final int dummy1Y = 250;
disableStonith(robot, host);
for (int i = 5; i > 0; i--) {
Tools.info("I: " + i);
//checkTest(host, "test7", 1);
sleep(5000);
chooseDummy(robot, dummy1X, dummy1Y, false);
sleep(5000);
moveTo(robot, 550, 250);
leftPress(robot); /* move the reosurce */
moveTo(robot, 300, 250);
leftRelease(robot);
}
//checkTest(host, "test7", 2);
}
/** Sets location. */
private static void setLocation(final Robot robot, final Integer[] events) {
moveTo(robot, 1041 , 615);
leftClick(robot);
sleep(2000);
for (final int ev : events) {
if (ev == KeyEvent.VK_PLUS) {
robot.keyPress(KeyEvent.VK_SHIFT);
sleep(400);
}
press(robot, ev);
sleep(400);
if (ev == KeyEvent.VK_PLUS) {
robot.keyRelease(KeyEvent.VK_SHIFT);
sleep(400);
}
}
moveTo(robot, 809, 192); /* ptest */
sleep(4000);
leftClick(robot); /* apply */
sleep(2000);
}
/** Choose dummy resource. */
private static void typeDummy(final Robot robot) {
press(robot, KeyEvent.VK_D);
sleep(200);
press(robot, KeyEvent.VK_U);
sleep(200);
press(robot, KeyEvent.VK_M);
sleep(200);
press(robot, KeyEvent.VK_M);
sleep(200);
press(robot, KeyEvent.VK_Y);
sleep(200);
press(robot, KeyEvent.VK_ENTER); /* choose dummy */
}
/** Sets start timeout. */
private static void setTimeouts(final Robot robot) {
sleep(3000);
moveTo(robot, 1105, 298);
leftPress(robot); /* scroll bar */
moveTo(robot, 1105, 550);
leftRelease(robot);
moveTo(robot, 956, 520);
leftClick(robot); /* start timeout */
press(robot, KeyEvent.VK_2);
sleep(200);
press(robot, KeyEvent.VK_0);
sleep(200);
press(robot, KeyEvent.VK_0);
sleep(200);
moveTo(robot, 956, 550);
leftClick(robot); /* stop timeout */
press(robot, KeyEvent.VK_1);
sleep(200);
press(robot, KeyEvent.VK_9);
sleep(200);
press(robot, KeyEvent.VK_2);
sleep(200);
moveTo(robot, 956, 580);
leftClick(robot); /* monitor timeout */
press(robot, KeyEvent.VK_1);
sleep(200);
press(robot, KeyEvent.VK_5);
sleep(200);
press(robot, KeyEvent.VK_4);
sleep(200);
moveTo(robot, 956, 610);
leftClick(robot); /* monitor interval */
press(robot, KeyEvent.VK_1);
sleep(200);
press(robot, KeyEvent.VK_2);
sleep(200);
press(robot, KeyEvent.VK_1);
sleep(200);
moveTo(robot, 1105, 350);
leftPress(robot); /* scroll bar back */
moveTo(robot, 1105, 150);
leftRelease(robot);
}
/** Sleep for x milliseconds * slowFactor + some random time. */
private static void sleep(final int x) {
if (abortWithMouseMovement()) {
return;
}
if (!aborted) {
Tools.sleep((int) (x * slowFactor));
Tools.sleep((int) (x * slowFactor * Math.random()));
}
}
/** Returns maybe true. */
private static boolean maybe() {
if (Math.random() < 0.5) {
return true;
}
return false;
}
/** Create dummy resource. */
private static void chooseDummy(final Robot robot,
final int x,
final int y,
boolean clone) {
moveTo(robot, x, y);
sleep(1000);
rightClick(robot); /* popup */
sleep(1000);
moveTo(robot, x + 57, y + 28);
moveTo(robot, x + 290, y + 28);
moveTo(robot, x + 290, y + 72);
moveTo(robot, x + 580, y + 72);
sleep(2000);
typeDummy(robot);
sleep(2000);
setTimeouts(robot);
if (clone) {
moveTo(robot, 893, 250);
leftClick(robot); /* clone */
}
moveTo(robot, 809, 192); /* ptest */
sleep(4000);
leftClick(robot); /* apply */
sleep(2000);
}
/** Removes service. */
private static void removeResource(final Robot robot,
final int x,
final int y,
final int corr) {
moveTo(robot, x + 20, y);
rightClick(robot);
sleep(1000);
moveTo(robot, x + 40 , y + 250 + corr);
leftClick(robot);
confirmRemove(robot);
}
/** Removes group. */
private static void removeGroup(final Robot robot,
final int x,
final int y,
final int corr) {
moveTo(robot, x + 20, y);
rightClick(robot);
sleep(120000);
moveTo(robot, x + 40 , y + 250 + corr);
leftClick(robot);
confirmRemove(robot);
}
/** Removes placeholder. */
private static void removePlaceHolder(final Robot robot,
final int x,
final int y) {
moveTo(robot, x + 20, y);
rightClick(robot);
sleep(1000);
moveTo(robot, x + 40 , y + 60);
leftClick(robot);
confirmRemove(robot);
}
/** Confirms remove dialog. */
private static void confirmRemove(final Robot robot) {
sleep(1000);
moveTo(robot, 512 , 480);
leftClick(robot);
}
/** Stops resource. */
private static void stopResource(final Robot robot,
final int x,
final int y,
final int yFactor) {
moveTo(robot, x + 50, y + 5);
sleep(2000);
rightClick(robot); /* popup */
moveTo(robot, x + 140, y + 130 + yFactor);
sleep(6000); /* ptest */
leftClick(robot); /* stop */
}
/** Stops group. */
private static void stopGroup(final Robot robot,
final int x,
final int y,
final int yFactor) {
moveTo(robot, x + 50, y + 5);
sleep(1000);
rightClick(robot); /* popup */
moveTo(robot, x + 140, y + 130 + yFactor);
sleep(120000); /* ptest */
leftClick(robot); /* stop */
}
/** Removes target role. */
private static void resetStartStopResource(final Robot robot,
final int x,
final int y) {
moveTo(robot, x + 50, y + 5);
sleep(1000);
leftClick(robot); /* select */
moveTo(robot, 1072, 496);
leftClick(robot); /* pull down */
moveTo(robot, 1044, 520);
leftClick(robot); /* choose */
moveTo(robot, 814, 189);
sleep(6000); /* ptest */
leftClick(robot); /* apply */
}
/** Starts resource. */
private static void startResource(final Robot robot,
final int x,
final int y,
final int yFactor) {
moveTo(robot, x + 50, y + 5);
sleep(1000);
rightClick(robot); /* popup */
moveTo(robot, x + 140, y + 80 + yFactor);
sleep(6000); /* ptest */
leftClick(robot); /* stop */
}
/** Migrate resource. */
private static void migrateResource(final Robot robot,
final int x,
final int y,
final int yFactor) {
moveTo(robot, x + 50, y + 5);
sleep(1000);
rightClick(robot); /* popup */
moveTo(robot, x + 140, y + 220 + yFactor);
sleep(6000); /* ptest */
leftClick(robot); /* stop */
}
/** Unmigrate resource. */
private static void unmigrateResource(final Robot robot,
final int x,
final int y,
final int yFactor) {
moveTo(robot, x + 50, y + 5);
sleep(12000);
rightClick(robot); /* popup */
sleep(6000);
rightClick(robot); /* popup */
moveTo(robot, x + 140, y + 260 + yFactor);
sleep(12000); /* ptest */
leftClick(robot); /* stop */
}
/** Unmanage resource. */
private static void unmanageResource(final Robot robot,
final int x,
final int y,
final int yFactor) {
moveTo(robot, x + 50, y + 5);
sleep(1000);
rightClick(robot); /* popup */
moveTo(robot, x + 140, y + 200 + yFactor);
sleep(6000); /* ptest */
leftClick(robot); /* stop */
}
/** Manage resource. */
private static void manageResource(final Robot robot,
final int x,
final int y,
final int yFactor) {
moveTo(robot, x + 50, y + 5);
sleep(1000);
rightClick(robot); /* popup */
moveTo(robot, x + 140, y + 200 + yFactor);
sleep(6000); /* ptest */
leftClick(robot); /* stop */
}
/** Go to the group service menu. */
private static void groupServiceMenu(final Robot robot,
final int x,
final int y,
final int groupService) {
final int groupServicePos = 365 + groupService;
final int startBefore = 100 + groupService;
moveTo(robot, x + 82, y + groupServicePos);
moveTo(robot, x + 382, y + groupServicePos);
}
/** Adds constraint from vertex. */
private static void addConstraint(final Robot robot,
final int x,
final int y,
final int with,
final boolean group,
final int groupService) {
int groupcor = 0;
if (group) {
groupcor = 24;
}
moveTo(robot, x + 20, y + 5);
sleep(1000);
if (group) {
rightClickGroup(robot); /* popup */
} else {
rightClick(robot); /* popup */
}
if (groupService >= 0) {
groupServiceMenu(robot, x, y, groupService);
final int startBefore = 100 + groupService;
moveTo(robot, x + 382, y + startBefore);
moveTo(robot, x + 632, y + startBefore);
moveTo(robot, x + 632, y + startBefore + with);
} else {
moveTo(robot, x + 82, y + 50 + groupcor);
moveTo(robot, x + 335, y + 50 + groupcor);
moveTo(robot, x + 335, y + 50 + groupcor + with);
}
sleep(6000); /* ptest */
leftClick(robot); /* start before */
}
/** Adds constraint (order only) from vertex. */
private static void addConstraintOrderOnly(final Robot robot,
final int x,
final int y,
final int xCorrection,
final int skipY,
final int with,
final boolean group,
final int groupService) {
int groupcor = 0;
if (group) {
groupcor = 24;
}
moveTo(robot, x + 20, y + 5);
sleep(1000);
if (group) {
rightClickGroup(robot); /* popup */
} else {
rightClick(robot); /* popup */
}
moveTo(robot, x + 82, y + 50 + groupcor);
moveTo(robot, x + 335, y + 50 + groupcor);
moveTo(robot, x + 335, y + 50 + groupcor + skipY + 34);
moveTo(robot, x + 500 + xCorrection, y + 50 + groupcor + skipY + 34);
moveTo(robot,
x + 520 + xCorrection,
y + 50 + groupcor + skipY + 34 + with);
sleep(6000); /* ptest */
leftClick(robot); /* start before */
}
/** Adds constraint (colocation only) from vertex. */
private static void addConstraintColocationOnly(final Robot robot,
final int x,
final int y,
final int xCorrection,
final int skipY,
final int with,
final boolean group,
final int groupService) {
int groupcor = 0;
if (group) {
groupcor = 24;
}
moveTo(robot, x + 20, y + 5);
sleep(1000);
if (group) {
rightClickGroup(robot); /* popup */
} else {
rightClick(robot); /* popup */
}
moveTo(robot, x + 82, y + 50 + groupcor);
moveTo(robot, x + 335, y + 50 + groupcor);
moveTo(robot, x + 335, y + 50 + groupcor + skipY + 9);
moveTo(robot, x + 500 + xCorrection, y + 50 + groupcor + skipY + 9);
moveTo(robot,
x + 520 + xCorrection,
y + 50 + groupcor + skipY + 9 + with);
sleep(6000); /* ptest */
leftClick(robot); /* start before */
}
/** Removes constraint. */
private static void removeConstraint(final Robot robot,
final int popX,
final int popY) {
moveTo(robot, popX, popY);
sleep(1000);
rightClick(robot); /* constraint popup */
moveTo(robot, popX + 70, popY + 20);
sleep(6000); /* ptest */
leftClick(robot); /* remove ord */
}
/** Removes order. */
private static void removeOrder(final Robot robot,
final int popX,
final int popY) {
moveTo(robot, popX, popY);
sleep(1000);
rightClick(robot); /* constraint popup */
moveTo(robot, popX + 70, popY + 50);
sleep(6000); /* ptest */
leftClick(robot); /* remove ord */
}
/** Adds order. */
private static void addOrder(final Robot robot,
final int popX,
final int popY) {
moveTo(robot, popX, popY);
sleep(1000);
rightClick(robot); /* constraint popup */
moveTo(robot, popX + 70, popY + 50);
sleep(6000); /* ptest */
leftClick(robot); /* add ord */
}
/** Removes colocation. */
private static void removeColocation(final Robot robot,
final int popX,
final int popY) {
moveTo(robot, popX, popY);
sleep(1000);
rightClick(robot); /* constraint popup */
moveTo(robot, popX + 70, popY + 93);
sleep(6000); /* ptest */
leftClick(robot); /* remove col */
}
/** Adds colocation. */
private static void addColocation(final Robot robot,
final int popX,
final int popY) {
moveTo(robot, popX, popY);
sleep(1000);
rightClick(robot); /* constraint popup */
moveTo(robot, popX + 70, popY + 90);
sleep(6000); /* ptest */
leftClick(robot); /* add col */
}
/** TEST 3. */
private static void startTest3(final Robot robot) {
aborted = false;
/* filesystem/drbd */
moveTo(robot, 577, 253);
rightClick(robot); /* popup */
moveTo(robot, 609, 278);
moveTo(robot, 794, 283);
leftClick(robot); /* choose fs */
moveTo(robot, 1075, 406);
leftClick(robot); /* choose drbd */
moveTo(robot, 1043, 444);
leftClick(robot); /* choose drbd */
moveTo(robot, 1068, 439);
leftClick(robot); /* mount point */
moveTo(robot, 1039, 475);
leftClick(robot); /* mount point */
moveTo(robot, 815, 186);
leftClick(robot); /* apply */
sleep(2000);
aborted = false;
}
/** Press button. */
private static void press(final Robot robot, final int ke) {
if (aborted) {
return;
}
robot.keyPress(ke);
robot.keyRelease(ke);
Tools.sleep(200);
}
/** Left click. */
private static void leftClick(final Robot robot) {
if (aborted) {
return;
}
robot.mousePress(InputEvent.BUTTON1_MASK);
Tools.sleep(300);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
Tools.sleep(300);
}
/** Left press. */
private static void leftPress(final Robot robot) {
if (aborted) {
return;
}
robot.mousePress(InputEvent.BUTTON1_MASK);
Tools.sleep(300);
}
/** Left release. */
private static void leftRelease(final Robot robot) {
if (aborted) {
return;
}
robot.mouseRelease(InputEvent.BUTTON1_MASK);
Tools.sleep(300);
}
/** Right click. */
private static void rightClick(final Robot robot) {
if (aborted) {
return;
}
Tools.sleep(1000);
robot.mousePress(InputEvent.BUTTON3_MASK);
Tools.sleep(500);
robot.mouseRelease(InputEvent.BUTTON3_MASK);
sleep(6000);
}
/** Right click. */
private static void rightClickGroup(final Robot robot) {
if (aborted) {
return;
}
rightClick(robot);
Tools.sleep(10000);
}
/** Move to position. */
private static void moveTo(final Robot robot,
final int toX,
final int toY) {
if (aborted) {
return;
}
prevP = null;
final int xOffset = getOffset();
final Point2D origP = MouseInfo.getPointerInfo().getLocation();
final int origX = (int) origP.getX();
final int origY = (int) origP.getY();
final Point2D endP =
Tools.getGUIData().getMainFrame().getLocationOnScreen();
final int endX = (int) endP.getX() + toX;
final int endY = (int) endP.getY() + toY;
if (MOVE_MOUSE_FAST) {
robot.mouseMove(endX, endY);
return;
}
final int destX = endX;
final int destY = endY;
while (true) {
if (MouseInfo.getPointerInfo() == null) {
return;
}
final Point2D p = MouseInfo.getPointerInfo().getLocation();
final int x = (int) p.getX();
final int y = (int) p.getY();
int directionX = 0;
int directionY = 0;
if (x < destX) {
directionX = 1;
} else if (x > destX) {
directionX = -1;
}
if (y < destY) {
directionY = 1;
} else if (y > destY) {
directionY = -1;
}
if (directionY == 0 && directionX == 0) {
break;
}
final int directionX0 = directionX;
final int directionY0 = directionY;
robot.mouseMove((int) p.getX() + xOffset + directionX0,
(int) p.getY() + directionY0);
sleep(5);
if (abortWithMouseMovement()) {
break;
}
}
}
/** Register movement. */
public static void registerMovement() {
Tools.info("start register movement in 3 seconds");
Tools.sleep(3000);
final Thread thread = new Thread(new Runnable() {
public void run() {
Point2D prevP = new Point2D.Double(0, 0);
Point2D prevPrevP = new Point2D.Double(0, 0);
while (true) {
final Point2D loc =
Tools.getGUIData().getMainFrame().getLocationOnScreen();
final Point2D pos =
MouseInfo.getPointerInfo().getLocation();
final Point2D newPos = new Point2D.Double(
pos.getX() - loc.getX(),
pos.getY() - loc.getY());
Tools.sleep(2000);
if (newPos.equals(prevP) && !prevPrevP.equals(prevP)) {
Tools.info("moveTo(robot, "
+ (int) newPos.getX()
+ ", "
+ (int) newPos.getY() + ");");
}
prevPrevP = prevP;
prevP = newPos;
if (abortWithMouseMovement()) {
break;
}
}
Tools.info("stopped movement registering");
}
});
thread.start();
}
/** DRBD Test 1. */
private static void startDRBDTest1(final Robot robot, final Host host) {
slowFactor = 0.2f;
host.getSSH().installTestFiles();
aborted = false;
moveTo(robot, 334, 315); /* add drbd resource */
rightClick(robot);
moveTo(robot, 342, 321);
moveTo(robot, 667, 322);
leftClick(robot);
sleep(20000);
moveTo(robot, 720, 580);
leftClick(robot); /* next */
sleep(20000);
moveTo(robot, 751, 412); /* interface */
leftClick(robot);
moveTo(robot, 716, 451);
leftClick(robot);
sleep(1000);
moveTo(robot, 720, 580);
leftClick(robot); /* next */
sleep(20000);
moveTo(robot, 751, 412); /* interface again */
leftClick(robot);
moveTo(robot, 716, 451);
leftClick(robot);
sleep(1000);
moveTo(robot, 720, 580);
leftClick(robot); /* next */
sleep(20000);
moveTo(robot, 720, 580); /* meta-data */
leftClick(robot); /* next */
sleep(20000);
moveTo(robot, 820, 580); /* fs */
leftClick(robot); /* finish */
sleep(10000);
checkDRBDTest(host, "drbd-test1", 1);
moveTo(robot, 480, 250); /* rsc popup */
rightClick(robot); /* finish */
moveTo(robot, 555, 340); /* remove */
leftClick(robot);
confirmRemove(robot);
checkDRBDTest(host, "drbd-test1", 2);
}
/** DRBD Test 1. */
private static void startDRBDTest2(final Robot robot, final Host host) {
slowFactor = 0.2f;
host.getSSH().installTestFiles();
aborted = false;
moveTo(robot, 334, 315); /* add drbd resource */
rightClick(robot);
moveTo(robot, 342, 321);
moveTo(robot, 667, 322);
leftClick(robot);
sleep(20000);
moveTo(robot, 960, 580);
leftClick(robot); /* cancel */
sleep(20000);
}
/** DRBD Test 3. */
private static void startDRBDTest3(final Robot robot, final Host host) {
/* works only with --big-drbd-conf option */
slowFactor = 0.2f;
host.getSSH().installTestFiles();
aborted = false;
moveTo(robot, 334, 315); /* add drbd resource */
rightClick(robot);
moveTo(robot, 342, 321);
moveTo(robot, 667, 322);
leftClick(robot);
sleep(20000);
moveTo(robot, 720, 580);
leftClick(robot); /* next */
sleep(20000);
moveTo(robot, 751, 412); /* interface */
leftClick(robot);
moveTo(robot, 716, 451);
leftClick(robot);
sleep(1000);
moveTo(robot, 720, 580);
leftClick(robot); /* next */
sleep(20000);
moveTo(robot, 751, 412); /* interface again */
leftClick(robot);
moveTo(robot, 716, 451);
leftClick(robot);
sleep(1000);
moveTo(robot, 720, 580);
leftClick(robot); /* next */
sleep(20000);
moveTo(robot, 720, 580); /* meta-data */
leftClick(robot); /* next */
sleep(20000);
moveTo(robot, 820, 580); /* fs */
leftClick(robot); /* finish */
sleep(10000);
checkDRBDTest(host, "drbd-test3", 1);
moveTo(robot, 480, 250); /* rsc popup */
rightClick(robot); /* finish */
moveTo(robot, 555, 340); /* remove */
leftClick(robot);
confirmRemove(robot);
checkDRBDTest(host, "drbd-test3", 2);
}
/** DRBD Test 4. */
private static void startDRBDTest4(final Robot robot, final Host host) {
/* Two drbds. */
slowFactor = 0.2f;
host.getSSH().installTestFiles();
aborted = false;
int offset = 0;
for (int i = 0; i < 2; i++) {
moveTo(robot, 334, 315 + offset); /* add drbd resource */
rightClick(robot);
moveTo(robot, 342, 321 + offset);
moveTo(robot, 667, 322 + offset);
leftClick(robot);
sleep(20000);
moveTo(robot, 720, 580);
leftClick(robot); /* next */
sleep(20000);
moveTo(robot, 751, 412); /* interface */
leftClick(robot);
moveTo(robot, 716, 451);
leftClick(robot);
sleep(1000);
moveTo(robot, 720, 580);
leftClick(robot); /* next */
sleep(20000);
moveTo(robot, 751, 412); /* interface again */
leftClick(robot);
moveTo(robot, 716, 451);
leftClick(robot);
sleep(1000);
moveTo(robot, 720, 580);
leftClick(robot); /* next */
sleep(20000);
moveTo(robot, 720, 580); /* meta-data */
leftClick(robot); /* next */
sleep(20000);
moveTo(robot, 820, 580); /* fs */
leftClick(robot); /* finish */
sleep(10000);
if (offset == 0) {
checkDRBDTest(host, "drbd-test4", 1);
}
offset += 40;
}
checkDRBDTest(host, "drbd-test4", 2);
moveTo(robot, 480, 250); /* select r0 */
leftClick(robot);
sleep(2000);
leftClick(robot);
moveTo(robot, 1073, 317); /* select protocol */
leftClick(robot);
sleep(2000);
moveTo(robot, 1070, 350); /* protocol b */
sleep(2000);
leftClick(robot);
sleep(2000);
moveTo(robot, 1075, 372); /* select fence peer */
leftClick(robot);
sleep(2000);
moveTo(robot, 1075, 410); /* select dopd */
sleep(2000);
leftClick(robot);
sleep(2000);
moveTo(robot, 970, 420); /* wfc timeout */
leftClick(robot);
press(robot, KeyEvent.VK_BACK_SPACE);
sleep(1000);
press(robot, KeyEvent.VK_9);
sleep(2000);
moveTo(robot, 814, 189);
sleep(6000); /* test */
leftClick(robot); /* apply */
checkDRBDTest(host, "drbd-test4", 2.1); /* 2.1 */
/* common */
moveTo(robot, 500, 390); /* select background */
leftClick(robot);
sleep(2000);
leftClick(robot);
moveTo(robot, 970, 380); /* wfc timeout */
leftClick(robot);
press(robot, KeyEvent.VK_BACK_SPACE);
sleep(1000);
press(robot, KeyEvent.VK_3);
sleep(2000);
moveTo(robot, 814, 189);
sleep(6000); /* test */
leftClick(robot); /* apply */
checkDRBDTest(host, "drbd-test4", 2.11); /* 2.11 */
moveTo(robot, 970, 380); /* wfc timeout */
sleep(6000);
leftClick(robot);
press(robot, KeyEvent.VK_BACK_SPACE);
sleep(1000);
press(robot, KeyEvent.VK_0);
sleep(2000);
moveTo(robot, 814, 189);
sleep(6000); /* test */
leftClick(robot); /* apply */
/* resource */
moveTo(robot, 480, 250); /* select r0 */
leftClick(robot);
sleep(2000);
leftClick(robot);
moveTo(robot, 1073, 317); /* select protocol */
leftClick(robot);
sleep(2000);
moveTo(robot, 1070, 372); /* protocol c */
sleep(2000);
leftClick(robot);
sleep(2000);
moveTo(robot, 1075, 372); /* select fence peer */
leftClick(robot);
sleep(2000);
moveTo(robot, 1075, 390); /* deselect dopd */
sleep(2000);
leftClick(robot);
sleep(2000);
moveTo(robot, 970, 420); /* wfc timeout */
leftClick(robot);
press(robot, KeyEvent.VK_BACK_SPACE);
sleep(1000);
press(robot, KeyEvent.VK_5);
sleep(2000);
moveTo(robot, 814, 189);
sleep(6000); /* test */
leftClick(robot); /* apply */
checkDRBDTest(host, "drbd-test4", 2.2); /* 2.2 */
moveTo(robot, 970, 420); /* wfc timeout */
leftClick(robot);
press(robot, KeyEvent.VK_BACK_SPACE);
sleep(1000);
press(robot, KeyEvent.VK_0);
sleep(2000);
moveTo(robot, 814, 189);
sleep(6000); /* test */
leftClick(robot); /* apply */
checkDRBDTest(host, "drbd-test4", 2.3); /* 2.3 */
moveTo(robot, 480, 250); /* rsc popup */
rightClick(robot);
moveTo(robot, 555, 340); /* remove */
leftClick(robot);
confirmRemove(robot);
checkDRBDTest(host, "drbd-test4", 3);
moveTo(robot, 480, 250); /* rsc popup */
rightClick(robot);
moveTo(robot, 555, 340); /* remove */
leftClick(robot);
confirmRemove(robot);
checkDRBDTest(host, "drbd-test4", 4);
}
/** VM Test 1. */
private static void startVMTest1and2(final String vmTest,
final Robot robot,
final Host host) {
slowFactor = 0.2f;
host.getSSH().installTestFiles();
aborted = false;
checkVMTest(host, vmTest, 1);
moveTo(robot, 56, 252); /* popup */
rightClick(robot);
moveTo(robot, 159, 273); /* new domain */
leftClick(robot);
moveTo(robot, 450, 395); /* domain name */
leftClick(robot);
press(robot, KeyEvent.VK_D);
sleep(200);
press(robot, KeyEvent.VK_M);
sleep(200);
press(robot, KeyEvent.VK_C);
sleep(200);
moveTo(robot, 730, 580);
leftClick(robot);
//press(robot, KeyEvent.VK_ENTER);
moveTo(robot, 593, 456); /* source file */
sleep(2000);
leftClick(robot);
sleep(2000);
press(robot, KeyEvent.VK_T);
sleep(200);
press(robot, KeyEvent.VK_E);
sleep(200);
press(robot, KeyEvent.VK_S);
sleep(200);
press(robot, KeyEvent.VK_T);
sleep(5000);
moveTo(robot, 730, 580);
leftClick(robot);
//press(robot, KeyEvent.VK_ENTER);
sleep(9000);
moveTo(robot, 730, 580);
leftClick(robot);
//press(robot, KeyEvent.VK_ENTER); /* storage */
sleep(9000);
moveTo(robot, 730, 580);
leftClick(robot);
//press(robot, KeyEvent.VK_ENTER); /* network */
sleep(9000);
moveTo(robot, 730, 580);
leftClick(robot);
//press(robot, KeyEvent.VK_ENTER); /* display */
sleep(9000);
moveTo(robot, 560, 423); /* create config */
leftClick(robot);
checkVMTest(host, vmTest, 2);
moveTo(robot, 814, 581); /* finish */
leftClick(robot);
Tools.sleep(5000);
moveTo(robot, 1066, 284); /* remove */
leftClick(robot);
Tools.sleep(5000);
moveTo(robot, 516, 485); /* confirm */
leftClick(robot);
Tools.sleep(5000);
}
}
| false | true | private static void startTest1(final Robot robot, final Host host) {
slowFactor = 0.2f;
host.getSSH().installTestFiles();
aborted = false;
/* create IPaddr2 with 192.168.100.100 ip */
final int ipX = 235;
final int ipY = 255;
final int gx = 230;
final int gy = 374;
final int popX = 343;
final int popY = 300;
final int statefulX = 500;
final int statefulY = 255;
disableStonith(robot, host);
checkTest(host, "test1", 1);
moveTo(robot, ipX, ipY);
rightClick(robot); /* popup */
moveTo(robot, ipX + 57, ipY + 28);
moveTo(robot, ipX + 270, ipY + 28);
moveTo(robot, ipX + 267, ipY + 52);
leftClick(robot); /* choose ipaddr */
removeResource(robot, ipX, ipY, -15);
/* again */
moveTo(robot, ipX, ipY);
rightClick(robot); /* popup */
moveTo(robot, ipX + 57, ipY + 28);
moveTo(robot, ipX + 270, ipY + 28);
moveTo(robot, ipX + 267, ipY + 52);
leftClick(robot); /* choose ipaddr */
moveTo(robot, 1072, 405);
leftClick(robot); /* pull down */
moveTo(robot, 1044, 450);
leftClick(robot); /* choose */
sleep(1000);
press(robot, KeyEvent.VK_1);
press(robot, KeyEvent.VK_0);
press(robot, KeyEvent.VK_0);
sleep(1000);
setTimeouts(robot);
moveTo(robot, 814, 189);
sleep(6000); /* ptest */
leftClick(robot); /* apply */
checkTest(host, "test1", 2); /* 2 */
/* pingd */
moveTo(robot, 1105, 298);
leftPress(robot); /* scroll bar */
moveTo(robot, 1105, 510);
leftRelease(robot);
moveTo(robot, 1076, 420);
leftClick(robot);
moveTo(robot, 1037, 487);
leftClick(robot); /* no ping */
moveTo(robot, 809, 192); /* ptest */
sleep(2000);
leftClick(robot); /* apply */
sleep(2000);
checkTest(host, "test1", 2.1); /* 2.1 */
moveTo(robot, 1076, 420);
leftClick(robot);
moveTo(robot, 1067, 445);
leftClick(robot); /* default */
moveTo(robot, 809, 192); /* ptest */
sleep(2000);
leftClick(robot); /* apply */
moveTo(robot, 1105, 298);
leftPress(robot); /* scroll bar */
moveTo(robot, 1105, 550);
leftRelease(robot);
/* group with dummy resources */
moveTo(robot, gx, gy);
sleep(1000);
rightClick(robot); /* popup */
moveTo(robot, gx + 46, gy + 11);
sleep(1000);
leftClick(robot); /* choose group */
sleep(3000);
/* remove it */
removeResource(robot, gx, gy, 0);
moveTo(robot, gx, gy);
sleep(1000);
rightClick(robot); /* popup */
moveTo(robot, gx + 46, gy + 11);
sleep(1000);
leftClick(robot); /* choose group */
sleep(3000);
rightClick(robot); /* group popup */
moveTo(robot, gx + 80, gy + 20);
moveTo(robot, gx + 84, gy + 22);
moveTo(robot, gx + 580, gy + 22);
sleep(1000);
typeDummy(robot);
sleep(1000);
/* remove it */
removeResource(robot, gx, gy, 0);
/* group with dummy resources, once again */
moveTo(robot, gx, gy);
sleep(1000);
rightClick(robot); /* popup */
moveTo(robot, gx + 46, gy + 11);
sleep(1000);
leftClick(robot); /* choose group */
sleep(3000);
rightClick(robot); /* group popup */
moveTo(robot, gx + 80, gy + 20);
moveTo(robot, gx + 84, gy + 22);
moveTo(robot, gx + 580, gy + 22);
sleep(1000);
typeDummy(robot);
sleep(1000);
moveTo(robot, 125, 320);
sleep(1000);
rightClick(robot);
sleep(1000);
moveTo(robot, 150, 611);
leftClick(robot); /* remove service */
removeResource(robot, gx, gy, 0);
/* group with dummy resources, once again */
moveTo(robot, gx, gy);
sleep(1000);
rightClick(robot); /* popup */
moveTo(robot, gx + 46, gy + 11);
sleep(1000);
leftClick(robot); /* choose group */
sleep(3000);
rightClick(robot); /* group popup */
moveTo(robot, gx + 80, gy + 20);
moveTo(robot, gx + 84, gy + 22);
moveTo(robot, gx + 580, gy + 22);
sleep(1000);
typeDummy(robot);
sleep(1000);
removeResource(robot, gx, gy, 0);
/* once again */
moveTo(robot, gx, gy);
sleep(1000);
rightClick(robot); /* popup */
moveTo(robot, gx + 46, gy + 11);
sleep(1000);
leftClick(robot); /* choose group */
sleep(3000);
checkTest(host, "test1", 2); /* 2 */
rightClick(robot); /* group popup */
moveTo(robot, gx + 80, gy + 20);
moveTo(robot, gx + 84, gy + 22);
moveTo(robot, gx + 580, gy + 22);
sleep(1000);
typeDummy(robot);
sleep(1000);
setTimeouts(robot);
moveTo(robot, 809, 192); /* ptest */
sleep(2000);
leftClick(robot); /* apply */
for (int i = 0; i < 2; i++) {
/* another group resource */
sleep(20000);
moveTo(robot, gx + 46, gy + 11);
rightClick(robot); /* group popup */
sleep(2000 + i * 500);
moveTo(robot, gx + 80, gy + 20);
moveTo(robot, gx + 84, gy + 22);
moveTo(robot, gx + 580, gy + 22);
sleep(1000);
typeDummy(robot);
sleep(i * 300);
setTimeouts(robot);
moveTo(robot, 809, 192); /* ptest */
sleep(6000);
leftClick(robot); /* apply */
sleep(1000);
}
sleep(4000);
checkTest(host, "test1", 3); /* 3 */
/* constraints */
addConstraint(robot, gx, gy, 0, true, -1);
checkTest(host, "test1", 3.1); /* 3.1 */
/* move up, move down */
moveTo(robot, 137, 344);
rightClick(robot);
sleep(1000);
moveTo(robot, 221, 493);
leftClick(robot); /* move res 3 up */
Tools.sleep(10000);
checkTest(host, "test1", 3.11); /* 3.11 */
moveTo(robot, 137, 328);
rightClick(robot);
moveTo(robot, 236, 515);
leftClick(robot); /* move res 3 down */
Tools.sleep(10000);
checkTest(host, "test1", 3.12); /* 3.12 */
/* same as */
moveTo(robot, 125, 345);
sleep(1000);
leftClick(robot);
moveTo(robot, 1105, 298);
leftPress(robot); /* scroll bar */
moveTo(robot, 1105, 510);
leftRelease(robot);
sleep(1000);
moveTo(robot, 1078, 484);
leftClick(robot);
sleep(1000);
moveTo(robot, 1078, 535);
sleep(1000);
leftClick(robot); /* choose another dummy */
sleep(1000);
moveTo(robot, 809, 192); /* ptest */
sleep(4000);
leftClick(robot); /* apply */
sleep(4000);
checkTest(host, "test1", 3.2); /* 3.2 */
moveTo(robot, 1078 , 477);
leftClick(robot);
sleep(1000);
moveTo(robot, 1078 , 507);
leftClick(robot); /* choose "nothing selected */
sleep(1000);
moveTo(robot, 809, 192); /* ptest */
sleep(4000);
leftClick(robot); /* apply */
sleep(9000);
moveTo(robot, 1105, 298);
leftPress(robot); /* scroll bar back */
moveTo(robot, 1105, 150);
leftRelease(robot);
checkTest(host, "test1", 4); /* 4 */
/* locations */
moveTo(robot, ipX + 20, ipY);
leftClick(robot); /* choose ip */
setLocation(robot, new Integer[]{KeyEvent.VK_I});
sleep(3000);
checkTest(host, "test1", 4.1); /* 4.1 */
setLocation(robot, new Integer[]{KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_MINUS,
KeyEvent.VK_I});
sleep(3000);
checkTest(host, "test1", 4.2); /* 4.2 */
setLocation(robot, new Integer[]{KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_PLUS});
sleep(3000);
checkTest(host, "test1", 4.3); /* 4.3 */
setLocation(robot, new Integer[]{KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE});
sleep(3000);
checkTest(host, "test1", 4.4); /* 4.4 */
removeConstraint(robot, popX, popY);
sleep(3000);
checkTest(host, "test1", 5); /* 5 */
sleep(1000);
addConstraint(robot, gx, gy, 9, true, -1);
sleep(5000);
checkTest(host, "test1", 6); /* 6 */
removeOrder(robot, popX, popY);
sleep(4000);
checkTest(host, "test1", 7);
addOrder(robot, popX, popY);
sleep(4000);
checkTest(host, "test1", 8);
removeColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 9);
addColocation(robot, popX, popY);
sleep(4000);
checkTest(host, "test1", 10);
removeColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.1);
removeOrder(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.2);
addConstraintOrderOnly(robot, gx, gy, 0, 25, 0, true, -1);
sleep(4000);
checkTest(host, "test1", 10.3);
addColocation(robot, popX, popY);
sleep(4000);
checkTest(host, "test1", 10.4);
removeOrder(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.5);
removeColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.6);
addConstraintColocationOnly(robot, gx, gy, 0, 25, 0, true, -1);
sleep(4000);
checkTest(host, "test1", 10.7);
addOrder(robot, popX, popY);
sleep(4000);
checkTest(host, "test1", 10.8);
removeConstraint(robot, popX, popY);
sleep(4000);
checkTest(host, "test1", 10.9);
addConstraint(robot, ipX, ipY, 0, false, -1);
sleep(5000);
checkTest(host, "test1", 10.91);
removeOrder(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.92);
addOrder(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.93);
removeColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.94);
addColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.95);
removeColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.96);
removeOrder(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.97);
addConstraintColocationOnly(robot, ipX, ipY, 0, 100, 0, false, -1);
sleep(5000);
checkTest(host, "test1", 10.98);
removeColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.99);
addConstraintOrderOnly(robot, ipX, ipY, 0, 100, 0, false, -1);
sleep(5000);
checkTest(host, "test1", 11);
addColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.1);
removeConstraint(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.2);
addConstraint(robot, ipX, ipY, 60, false, -1);
sleep(5000);
checkTest(host, "test1", 11.3);
stopResource(robot, ipX, ipY, 0);
sleep(5000);
checkTest(host, "test1", 11.4);
resetStartStopResource(robot, ipX, ipY);
sleep(5000);
checkTest(host, "test1", 11.5);
moveTo(robot, ipX + 20, ipY + 10);
leftClick(robot); /* choose ip */
stopResource(robot, 1020, 180, 10); /* actions menu stop */
sleep(5000);
checkTest(host, "test1", 11.501);
moveTo(robot, ipX + 20, ipY + 10);
leftClick(robot); /* choose ip */
startResource(robot, 1020, 180, 20); /* actions menu start */
sleep(5000);
checkTest(host, "test1", 11.502);
resetStartStopResource(robot, ipX, ipY);
sleep(5000);
checkTest(host, "test1", 11.5);
removeColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.51);
addColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.52);
removeOrder(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.53);
addOrder(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.54);
removeColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.55);
removeOrder(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.56);
addConstraintOrderOnly(robot, ipX, ipY, 0, 100, 55, false, -1);
sleep(5000);
checkTest(host, "test1", 11.57);
removeOrder(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.58);
addConstraintColocationOnly(robot, ipX, ipY, 0, 100, 55, false, -1);
sleep(5000);
checkTest(host, "test1", 11.59);
addOrder(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.6);
removeConstraint(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.7);
addConstraint(robot, gx, gy, 9, true, -1);
sleep(5000);
checkTest(host, "test1", 11.8);
/** Add m/s Stateful resource */
moveTo(robot, statefulX, statefulY);
rightClick(robot); /* popup */
moveTo(robot, statefulX + 137, statefulY + 8);
moveTo(robot, statefulX + 137, statefulY + 28);
moveTo(robot, statefulX + 412, statefulY + 27);
moveTo(robot, statefulX + 432, statefulY + 70);
moveTo(robot, statefulX + 665, statefulY + 70);
sleep(1000);
press(robot, KeyEvent.VK_S);
sleep(200);
press(robot, KeyEvent.VK_T);
sleep(200);
press(robot, KeyEvent.VK_A);
sleep(200);
press(robot, KeyEvent.VK_T);
sleep(200);
press(robot, KeyEvent.VK_E);
sleep(200);
press(robot, KeyEvent.VK_F);
sleep(200);
press(robot, KeyEvent.VK_ENTER); /* choose Stateful */
sleep(1000);
moveTo(robot, 812, 179);
sleep(1000);
leftClick(robot); /* apply */
sleep(4000);
/* set clone max to 1 */
moveTo(robot, 978, 381);
sleep(3000);
leftClick(robot); /* Clone Max */
sleep(3000);
press(robot, KeyEvent.VK_BACK_SPACE);
sleep(3000);
press(robot, KeyEvent.VK_1);
setTimeouts(robot);
moveTo(robot, 812, 179);
sleep(3000);
leftClick(robot); /* apply */
sleep(3000);
checkTest(host, "test1", 12);
stopResource(robot, statefulX, statefulY, 0);
sleep(3000);
checkTest(host, "test1", 13);
startResource(robot, statefulX, statefulY, 0);
sleep(10000);
checkTest(host, "test1", 14);
unmanageResource(robot, statefulX, statefulY, 0);
sleep(3000);
checkTest(host, "test1", 15);
manageResource(robot, statefulX, statefulY, 0);
sleep(3000);
checkTest(host, "test1", 16);
/* IP addr cont. */
stopResource(robot, ipX, ipY, 0);
sleep(3000);
checkTest(host, "test1", 17);
startResource(robot, ipX, ipY, 0);
sleep(3000);
checkTest(host, "test1", 18);
unmanageResource(robot, ipX, ipY, 0);
sleep(3000);
checkTest(host, "test1", 19);
manageResource(robot, ipX, ipY, 0);
sleep(3000);
checkTest(host, "test1", 20);
migrateResource(robot, ipX, ipY, 0);
sleep(3000);
checkTest(host, "test1", 21);
unmigrateResource(robot, ipX, ipY, 0);
sleep(3000);
checkTest(host, "test1", 22);
/* Group cont. */
stopResource(robot, gx, gy, 15);
sleep(10000);
checkTest(host, "test1", 23);
startResource(robot, gx, gy, 15);
sleep(8000);
checkTest(host, "test1", 24);
unmanageResource(robot, gx, gy, 15);
sleep(5000);
checkTest(host, "test1", 25);
manageResource(robot, gx, gy, 15);
sleep(5000);
checkTest(host, "test1", 26);
migrateResource(robot, gx, gy, 25);
sleep(5000);
checkTest(host, "test1", 27);
unmigrateResource(robot, gx, gy, 25);
sleep(5000);
checkTest(host, "test1", 28);
stopResource(robot, ipX, ipY, 0);
sleep(5000);
stopGroup(robot, gx, gy, 15);
sleep(5000);
stopGroup(robot, statefulX, statefulY, 0);
stopEverything(robot); /* to be sure */
sleep(5000);
checkTest(host, "test1", 29);
if (true) {
removeResource(robot, ipX, ipY, -15);
sleep(5000);
removeGroup(robot, gx, gy, 0);
sleep(5000);
removeGroup(robot, statefulX, statefulY, -15);
} else {
removeEverything(robot);
}
if (!aborted) {
Tools.sleep(240000);
}
checkTest(host, "test1", 1);
}
| private static void startTest1(final Robot robot, final Host host) {
slowFactor = 0.2f;
host.getSSH().installTestFiles();
aborted = false;
/* create IPaddr2 with 192.168.100.100 ip */
final int ipX = 235;
final int ipY = 255;
final int gx = 230;
final int gy = 374;
final int popX = 343;
final int popY = 300;
final int statefulX = 500;
final int statefulY = 255;
disableStonith(robot, host);
checkTest(host, "test1", 1);
moveTo(robot, ipX, ipY);
rightClick(robot); /* popup */
moveTo(robot, ipX + 57, ipY + 28);
moveTo(robot, ipX + 270, ipY + 28);
moveTo(robot, ipX + 267, ipY + 52);
leftClick(robot); /* choose ipaddr */
removeResource(robot, ipX, ipY, -15);
/* again */
moveTo(robot, ipX, ipY);
rightClick(robot); /* popup */
moveTo(robot, ipX + 57, ipY + 28);
moveTo(robot, ipX + 270, ipY + 28);
moveTo(robot, ipX + 267, ipY + 52);
leftClick(robot); /* choose ipaddr */
moveTo(robot, 1072, 405);
leftClick(robot); /* pull down */
moveTo(robot, 1044, 450);
leftClick(robot); /* choose */
sleep(1000);
press(robot, KeyEvent.VK_1);
press(robot, KeyEvent.VK_0);
press(robot, KeyEvent.VK_0);
sleep(1000);
setTimeouts(robot);
moveTo(robot, 814, 189);
sleep(6000); /* ptest */
leftClick(robot); /* apply */
checkTest(host, "test1", 2); /* 2 */
/* pingd */
moveTo(robot, 1105, 298);
leftPress(robot); /* scroll bar */
moveTo(robot, 1105, 510);
leftRelease(robot);
moveTo(robot, 1076, 420);
leftClick(robot);
moveTo(robot, 1037, 487);
leftClick(robot); /* no ping */
moveTo(robot, 809, 192); /* ptest */
sleep(2000);
leftClick(robot); /* apply */
sleep(2000);
checkTest(host, "test1", 2.1); /* 2.1 */
moveTo(robot, 1076, 420);
leftClick(robot);
moveTo(robot, 1067, 445);
leftClick(robot); /* default */
moveTo(robot, 809, 192); /* ptest */
sleep(2000);
leftClick(robot); /* apply */
moveTo(robot, 1105, 298);
leftPress(robot); /* scroll bar */
moveTo(robot, 1105, 550);
leftRelease(robot);
/* group with dummy resources */
moveTo(robot, gx, gy);
sleep(1000);
rightClick(robot); /* popup */
moveTo(robot, gx + 46, gy + 11);
sleep(1000);
leftClick(robot); /* choose group */
sleep(3000);
/* remove it */
removeResource(robot, gx, gy, 0);
moveTo(robot, gx, gy);
sleep(1000);
rightClick(robot); /* popup */
moveTo(robot, gx + 46, gy + 11);
sleep(1000);
leftClick(robot); /* choose group */
sleep(3000);
rightClick(robot); /* group popup */
moveTo(robot, gx + 80, gy + 20);
moveTo(robot, gx + 84, gy + 22);
moveTo(robot, gx + 580, gy + 22);
sleep(1000);
typeDummy(robot);
sleep(1000);
/* remove it */
removeResource(robot, gx, gy, 0);
/* group with dummy resources, once again */
moveTo(robot, gx, gy);
sleep(1000);
rightClick(robot); /* popup */
moveTo(robot, gx + 46, gy + 11);
sleep(1000);
leftClick(robot); /* choose group */
sleep(3000);
rightClick(robot); /* group popup */
moveTo(robot, gx + 80, gy + 20);
moveTo(robot, gx + 84, gy + 22);
moveTo(robot, gx + 580, gy + 22);
sleep(1000);
typeDummy(robot);
sleep(1000);
moveTo(robot, 125, 320);
sleep(1000);
rightClick(robot);
sleep(1000);
moveTo(robot, 150, 611);
leftClick(robot); /* remove service */
removeResource(robot, gx, gy, 0);
/* group with dummy resources, once again */
moveTo(robot, gx, gy);
sleep(1000);
rightClick(robot); /* popup */
moveTo(robot, gx + 46, gy + 11);
sleep(1000);
leftClick(robot); /* choose group */
sleep(3000);
rightClick(robot); /* group popup */
moveTo(robot, gx + 80, gy + 20);
moveTo(robot, gx + 84, gy + 22);
moveTo(robot, gx + 580, gy + 22);
sleep(1000);
typeDummy(robot);
sleep(1000);
removeResource(robot, gx, gy, 0);
/* once again */
moveTo(robot, gx, gy);
sleep(1000);
rightClick(robot); /* popup */
moveTo(robot, gx + 46, gy + 11);
sleep(1000);
leftClick(robot); /* choose group */
sleep(3000);
checkTest(host, "test1", 2); /* 2 */
rightClick(robot); /* group popup */
moveTo(robot, gx + 80, gy + 20);
moveTo(robot, gx + 84, gy + 22);
moveTo(robot, gx + 580, gy + 22);
sleep(1000);
typeDummy(robot);
sleep(1000);
setTimeouts(robot);
moveTo(robot, 809, 192); /* ptest */
sleep(2000);
leftClick(robot); /* apply */
for (int i = 0; i < 2; i++) {
/* another group resource */
sleep(20000);
moveTo(robot, gx + 46, gy + 11);
rightClick(robot); /* group popup */
sleep(2000 + i * 500);
moveTo(robot, gx + 80, gy + 20);
moveTo(robot, gx + 84, gy + 22);
moveTo(robot, gx + 580, gy + 22);
sleep(1000);
typeDummy(robot);
sleep(i * 300);
setTimeouts(robot);
moveTo(robot, 809, 192); /* ptest */
sleep(6000);
leftClick(robot); /* apply */
sleep(1000);
}
sleep(4000);
checkTest(host, "test1", 3); /* 3 */
/* constraints */
addConstraint(robot, gx, gy, 0, true, -1);
checkTest(host, "test1", 3.1); /* 3.1 */
/* move up, move down */
moveTo(robot, 137, 344);
rightClick(robot);
sleep(1000);
moveTo(robot, 221, 493);
leftClick(robot); /* move res 3 up */
Tools.sleep(10000);
checkTest(host, "test1", 3.11); /* 3.11 */
moveTo(robot, 137, 328);
rightClick(robot);
moveTo(robot, 236, 515);
leftClick(robot); /* move res 3 down */
Tools.sleep(10000);
checkTest(host, "test1", 3.12); /* 3.12 */
/* same as */
moveTo(robot, 125, 345);
sleep(1000);
leftClick(robot);
moveTo(robot, 1105, 298);
leftPress(robot); /* scroll bar */
moveTo(robot, 1105, 510);
leftRelease(robot);
sleep(1000);
moveTo(robot, 1078, 484);
leftClick(robot);
sleep(1000);
moveTo(robot, 1078, 535);
sleep(1000);
leftClick(robot); /* choose another dummy */
sleep(1000);
moveTo(robot, 809, 192); /* ptest */
sleep(4000);
leftClick(robot); /* apply */
sleep(4000);
checkTest(host, "test1", 3.2); /* 3.2 */
moveTo(robot, 1078 , 477);
leftClick(robot);
sleep(1000);
moveTo(robot, 1078 , 507);
leftClick(robot); /* choose "nothing selected */
sleep(1000);
moveTo(robot, 809, 192); /* ptest */
sleep(4000);
leftClick(robot); /* apply */
sleep(9000);
moveTo(robot, 1105, 298);
leftPress(robot); /* scroll bar back */
moveTo(robot, 1105, 150);
leftRelease(robot);
checkTest(host, "test1", 4); /* 4 */
/* locations */
moveTo(robot, ipX + 20, ipY);
leftClick(robot); /* choose ip */
setLocation(robot, new Integer[]{KeyEvent.VK_I});
sleep(3000);
checkTest(host, "test1", 4.1); /* 4.1 */
setLocation(robot, new Integer[]{KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_MINUS,
KeyEvent.VK_I});
sleep(3000);
checkTest(host, "test1", 4.2); /* 4.2 */
setLocation(robot, new Integer[]{KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_PLUS});
sleep(3000);
checkTest(host, "test1", 4.3); /* 4.3 */
setLocation(robot, new Integer[]{KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_BACK_SPACE});
sleep(3000);
checkTest(host, "test1", 4.4); /* 4.4 */
removeConstraint(robot, popX, popY);
sleep(3000);
checkTest(host, "test1", 5); /* 5 */
sleep(1000);
addConstraint(robot, gx, gy, 9, true, -1);
sleep(5000);
checkTest(host, "test1", 6); /* 6 */
removeOrder(robot, popX, popY);
sleep(4000);
checkTest(host, "test1", 7);
addOrder(robot, popX, popY);
sleep(4000);
checkTest(host, "test1", 8);
removeColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 9);
addColocation(robot, popX, popY);
sleep(4000);
checkTest(host, "test1", 10);
removeColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.1);
removeOrder(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.2);
addConstraintOrderOnly(robot, gx, gy, 0, 25, 0, true, -1);
sleep(4000);
checkTest(host, "test1", 10.3);
addColocation(robot, popX, popY);
sleep(4000);
checkTest(host, "test1", 10.4);
removeOrder(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.5);
removeColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.6);
addConstraintColocationOnly(robot, gx, gy, 0, 25, 0, true, -1);
sleep(4000);
checkTest(host, "test1", 10.7);
addOrder(robot, popX, popY);
sleep(4000);
checkTest(host, "test1", 10.8);
removeConstraint(robot, popX, popY);
sleep(4000);
checkTest(host, "test1", 10.9);
addConstraint(robot, ipX, ipY, 0, false, -1);
sleep(5000);
checkTest(host, "test1", 10.91);
removeOrder(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.92);
addOrder(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.93);
removeColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.94);
addColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.95);
removeColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.96);
removeOrder(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.97);
addConstraintColocationOnly(robot, ipX, ipY, -20, 100, 0, false, -1);
sleep(5000);
checkTest(host, "test1", 10.98);
removeColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 10.99);
addConstraintOrderOnly(robot, ipX, ipY, -20, 100, 0, false, -1);
sleep(5000);
checkTest(host, "test1", 11);
addColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.1);
removeConstraint(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.2);
addConstraint(robot, ipX, ipY, 60, false, -1);
sleep(5000);
checkTest(host, "test1", 11.3);
stopResource(robot, ipX, ipY, 0);
sleep(5000);
checkTest(host, "test1", 11.4);
resetStartStopResource(robot, ipX, ipY);
sleep(5000);
checkTest(host, "test1", 11.5);
moveTo(robot, ipX + 20, ipY + 10);
leftClick(robot); /* choose ip */
stopResource(robot, 1020, 180, 10); /* actions menu stop */
sleep(5000);
checkTest(host, "test1", 11.501);
moveTo(robot, ipX + 20, ipY + 10);
leftClick(robot); /* choose ip */
startResource(robot, 1020, 180, 20); /* actions menu start */
sleep(5000);
checkTest(host, "test1", 11.502);
resetStartStopResource(robot, ipX, ipY);
sleep(5000);
checkTest(host, "test1", 11.5);
removeColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.51);
addColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.52);
removeOrder(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.53);
addOrder(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.54);
removeColocation(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.55);
removeOrder(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.56);
addConstraintOrderOnly(robot, ipX, ipY, -20, 100, 55, false, -1);
sleep(5000);
checkTest(host, "test1", 11.57);
removeOrder(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.58);
addConstraintColocationOnly(robot, ipX, ipY, -20, 100, 55, false, -1);
sleep(5000);
checkTest(host, "test1", 11.59);
addOrder(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.6);
removeConstraint(robot, popX, popY);
sleep(5000);
checkTest(host, "test1", 11.7);
addConstraint(robot, gx, gy, 9, true, -1);
sleep(5000);
checkTest(host, "test1", 11.8);
/** Add m/s Stateful resource */
moveTo(robot, statefulX, statefulY);
rightClick(robot); /* popup */
moveTo(robot, statefulX + 137, statefulY + 8);
moveTo(robot, statefulX + 137, statefulY + 28);
moveTo(robot, statefulX + 412, statefulY + 27);
moveTo(robot, statefulX + 432, statefulY + 70);
moveTo(robot, statefulX + 665, statefulY + 70);
sleep(1000);
press(robot, KeyEvent.VK_S);
sleep(200);
press(robot, KeyEvent.VK_T);
sleep(200);
press(robot, KeyEvent.VK_A);
sleep(200);
press(robot, KeyEvent.VK_T);
sleep(200);
press(robot, KeyEvent.VK_E);
sleep(200);
press(robot, KeyEvent.VK_F);
sleep(200);
press(robot, KeyEvent.VK_ENTER); /* choose Stateful */
sleep(1000);
moveTo(robot, 812, 179);
sleep(1000);
leftClick(robot); /* apply */
sleep(4000);
/* set clone max to 1 */
moveTo(robot, 978, 381);
sleep(3000);
leftClick(robot); /* Clone Max */
sleep(3000);
press(robot, KeyEvent.VK_BACK_SPACE);
sleep(3000);
press(robot, KeyEvent.VK_1);
setTimeouts(robot);
moveTo(robot, 812, 179);
sleep(3000);
leftClick(robot); /* apply */
sleep(3000);
checkTest(host, "test1", 12);
stopResource(robot, statefulX, statefulY, 0);
sleep(3000);
checkTest(host, "test1", 13);
startResource(robot, statefulX, statefulY, 0);
sleep(10000);
checkTest(host, "test1", 14);
unmanageResource(robot, statefulX, statefulY, 0);
sleep(3000);
checkTest(host, "test1", 15);
manageResource(robot, statefulX, statefulY, 0);
sleep(3000);
checkTest(host, "test1", 16);
/* IP addr cont. */
stopResource(robot, ipX, ipY, 0);
sleep(3000);
checkTest(host, "test1", 17);
startResource(robot, ipX, ipY, 0);
sleep(3000);
checkTest(host, "test1", 18);
unmanageResource(robot, ipX, ipY, 0);
sleep(3000);
checkTest(host, "test1", 19);
manageResource(robot, ipX, ipY, 0);
sleep(3000);
checkTest(host, "test1", 20);
migrateResource(robot, ipX, ipY, 0);
sleep(3000);
checkTest(host, "test1", 21);
unmigrateResource(robot, ipX, ipY, 0);
sleep(3000);
checkTest(host, "test1", 22);
/* Group cont. */
stopResource(robot, gx, gy, 15);
sleep(10000);
checkTest(host, "test1", 23);
startResource(robot, gx, gy, 15);
sleep(8000);
checkTest(host, "test1", 24);
unmanageResource(robot, gx, gy, 15);
sleep(5000);
checkTest(host, "test1", 25);
manageResource(robot, gx, gy, 15);
sleep(5000);
checkTest(host, "test1", 26);
migrateResource(robot, gx, gy, 25);
sleep(5000);
checkTest(host, "test1", 27);
unmigrateResource(robot, gx, gy, 25);
sleep(5000);
checkTest(host, "test1", 28);
stopResource(robot, ipX, ipY, 0);
sleep(5000);
stopGroup(robot, gx, gy, 15);
sleep(5000);
stopGroup(robot, statefulX, statefulY, 0);
stopEverything(robot); /* to be sure */
sleep(5000);
checkTest(host, "test1", 29);
if (true) {
removeResource(robot, ipX, ipY, -15);
sleep(5000);
removeGroup(robot, gx, gy, 0);
sleep(5000);
removeGroup(robot, statefulX, statefulY, -15);
} else {
removeEverything(robot);
}
if (!aborted) {
Tools.sleep(240000);
}
checkTest(host, "test1", 1);
}
|
diff --git a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/FeedServlet.java b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/FeedServlet.java
index feb60e767..6f1f19447 100644
--- a/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/FeedServlet.java
+++ b/dspace-jspui/src/main/java/org/dspace/app/webui/servlet/FeedServlet.java
@@ -1,665 +1,666 @@
/*
* FeedServlet.java
*
* Version: $Revision$
*
* Date: $Date$
*
* Copyright (c) 2002-2005, 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.webui.servlet;
import java.io.IOException;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.dspace.app.webui.util.JSPManager;
import org.dspace.authorize.AuthorizeException;
import org.dspace.browse.BrowseEngine;
import org.dspace.browse.BrowseException;
import org.dspace.browse.BrowseIndex;
import org.dspace.browse.BrowseInfo;
import org.dspace.browse.BrowserScope;
import org.dspace.browse.SortOption;
import org.dspace.content.Bitstream;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DCDate;
import org.dspace.content.DCValue;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
import org.dspace.handle.HandleManager;
import org.dspace.search.Harvest;
import com.sun.syndication.feed.rss.Channel;
import com.sun.syndication.feed.rss.Description;
import com.sun.syndication.feed.rss.Image;
import com.sun.syndication.feed.rss.TextInput;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.WireFeedOutput;
/**
* Servlet for handling requests for a syndication feed. The Handle of the collection
* or community is extracted from the URL, e.g: <code>/feed/rss_1.0/1234/5678</code>.
* Currently supports only RSS feed formats.
*
* @author Ben Bosman, Richard Rodgers
* @version $Revision$
*/
public class FeedServlet extends DSpaceServlet
{
// key for site-wide feed
public static final String SITE_FEED_KEY = "site";
// one hour in milliseconds
private static final long HOUR_MSECS = 60 * 60 * 1000;
/** log4j category */
private static Logger log = Logger.getLogger(FeedServlet.class);
private String clazz = "org.dspace.app.webui.servlet.FeedServlet";
// are syndication feeds enabled?
private static boolean enabled = false;
// number of DSpace items per feed
private static int itemCount = 0;
// optional cache of feeds
private static Map feedCache = null;
// maximum size of cache - 0 means caching disabled
private static int cacheSize = 0;
// how many days to keep a feed in cache before checking currency
private static int cacheAge = 0;
// supported syndication formats
private static List formats = null;
// localized resource bundle
private static ResourceBundle labels = null;
//default fields to display in item description
private static String defaultDescriptionFields = "dc.title, dc.contributor.author, dc.contributor.editor, dc.description.abstract, dc.description";
static
{
enabled = ConfigurationManager.getBooleanProperty("webui.feed.enable");
}
public void init()
{
// read rest of config info if enabled
if (enabled)
{
String fmtsStr = ConfigurationManager.getProperty("webui.feed.formats");
if ( fmtsStr != null )
{
formats = new ArrayList();
String[] fmts = fmtsStr.split(",");
for (int i = 0; i < fmts.length; i++)
{
formats.add(fmts[i]);
}
}
itemCount = ConfigurationManager.getIntProperty("webui.feed.items");
cacheSize = ConfigurationManager.getIntProperty("webui.feed.cache.size");
if (cacheSize > 0)
{
feedCache = new HashMap();
cacheAge = ConfigurationManager.getIntProperty("webui.feed.cache.age");
}
}
}
protected void doDSGet(Context context, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException,
SQLException, AuthorizeException
{
String path = request.getPathInfo();
String feedType = null;
String handle = null;
if(labels==null)
{
// Get access to the localized resource bundle
Locale locale = request.getLocale();
labels = ResourceBundle.getBundle("Messages", locale);
}
if (path != null)
{
// substring(1) is to remove initial '/'
path = path.substring(1);
int split = path.indexOf("/");
if (split != -1)
{
feedType = path.substring(0,split);
handle = path.substring(split+1);
}
}
DSpaceObject dso = null;
//as long as this is not a site wide feed,
//attempt to retrieve the Collection or Community object
if(!handle.equals(SITE_FEED_KEY))
{
// Determine if handle is a valid reference
dso = HandleManager.resolveToObject(context, handle);
}
if (! enabled || (dso != null &&
(dso.getType() != Constants.COLLECTION && dso.getType() != Constants.COMMUNITY)) )
{
log.info(LogManager.getHeader(context, "invalid_id", "path=" + path));
JSPManager.showInvalidIDError(request, response, path, -1);
return;
}
// Determine if requested format is supported
if( feedType == null || ! formats.contains( feedType ) )
{
log.info(LogManager.getHeader(context, "invalid_syndformat", "path=" + path));
JSPManager.showInvalidIDError(request, response, path, -1);
return;
}
// Lookup or generate the feed
Channel channel = null;
if (feedCache != null)
{
// Cache key is handle
CacheFeed cFeed = (CacheFeed)feedCache.get(handle);
if (cFeed != null) // cache hit, but...
{
// Is the feed current?
boolean cacheFeedCurrent = false;
if (cFeed.timeStamp + (cacheAge * HOUR_MSECS) < System.currentTimeMillis())
{
cacheFeedCurrent = true;
}
// Not current, but have any items changed since feed was created/last checked?
else if ( ! itemsChanged(context, dso, cFeed.timeStamp))
{
// no items have changed, re-stamp feed and use it
cFeed.timeStamp = System.currentTimeMillis();
cacheFeedCurrent = true;
}
if (cacheFeedCurrent)
{
channel = cFeed.access();
}
}
}
// either not caching, not found in cache, or feed in cache not current
if (channel == null)
{
channel = generateFeed(context, dso);
if (feedCache != null)
{
cache(handle, new CacheFeed(channel));
}
}
// set the feed to the requested type & return it
channel.setFeedType(feedType);
WireFeedOutput feedWriter = new WireFeedOutput();
try
{
response.setContentType("text/xml; charset=UTF-8");
feedWriter.output(channel, response.getWriter());
}
catch( FeedException fex )
{
throw new IOException(fex.getMessage());
}
}
private boolean itemsChanged(Context context, DSpaceObject dso, long timeStamp)
throws SQLException
{
// construct start and end dates
DCDate dcStartDate = new DCDate( new Date(timeStamp) );
DCDate dcEndDate = new DCDate( new Date(System.currentTimeMillis()) );
// convert dates to ISO 8601, stripping the time
String startDate = dcStartDate.toString().substring(0, 10);
String endDate = dcEndDate.toString().substring(0, 10);
// this invocation should return a non-empty list if even 1 item has changed
try {
return (Harvest.harvest(context, dso, startDate, endDate,
0, 1, false, false, false).size() > 0);
}
catch (ParseException pe)
{
// This should never get thrown as we have generated the dates ourselves
return false;
}
}
/**
* Generate a syndication feed for a collection or community
* or community
*
* @param context the DSpace context object
*
* @param dso DSpace object - collection or community
*
* @return an object representing the feed
*/
private Channel generateFeed(Context context, DSpaceObject dso)
throws IOException, SQLException
{
try
{
// container-level elements
String dspaceUrl = ConfigurationManager.getProperty("dspace.url");
String type = null;
String description = null;
String title = null;
Bitstream logo = null;
// browse scope
// BrowseScope scope = new BrowseScope(context);
// new method of doing the browse:
String idx = ConfigurationManager.getProperty("recent.submissions.sort-option");
if (idx == null)
{
throw new IOException("There is no configuration supplied for: recent.submissions.sort-option");
}
BrowseIndex bix = BrowseIndex.getItemBrowseIndex();
if (bix == null)
{
throw new IOException("There is no browse index with the name: " + idx);
}
BrowserScope scope = new BrowserScope(context);
scope.setBrowseIndex(bix);
for (SortOption so : SortOption.getSortOptions())
{
if (so.getName().equals(idx))
scope.setSortBy(so.getNumber());
}
+ scope.setOrder(SortOption.DESCENDING);
- // the feed
+ // the feed
Channel channel = new Channel();
//Special Case: if DSpace Object passed in is null,
//generate a feed for the entire DSpace site!
if(dso == null)
{
channel.setTitle(ConfigurationManager.getProperty("dspace.name"));
channel.setLink(dspaceUrl);
channel.setDescription(labels.getString(clazz + ".general-feed.description"));
}
else //otherwise, this is a Collection or Community specific feed
{
if (dso.getType() == Constants.COLLECTION)
{
type = labels.getString(clazz + ".feed-type.collection");
Collection col = (Collection)dso;
description = col.getMetadata("short_description");
title = col.getMetadata("name");
logo = col.getLogo();
// scope.setScope(col);
scope.setBrowseContainer(col);
}
else if (dso.getType() == Constants.COMMUNITY)
{
type = labels.getString(clazz + ".feed-type.community");
Community comm = (Community)dso;
description = comm.getMetadata("short_description");
title = comm.getMetadata("name");
logo = comm.getLogo();
// scope.setScope(comm);
scope.setBrowseContainer(comm);
}
String objectUrl = ConfigurationManager.getBooleanProperty("webui.feed.localresolve")
? HandleManager.resolveToURL(context, dso.getHandle())
: HandleManager.getCanonicalForm(dso.getHandle());
// put in container-level data
channel.setDescription(description);
channel.setLink(objectUrl);
//build channel title by passing in type and title
String channelTitle = MessageFormat.format(labels.getString(clazz + ".feed.title"),
new Object[]{type, title});
channel.setTitle(channelTitle);
//if collection or community has a logo
if (logo != null)
{
// we use the path to the logo for this, the logo itself cannot
// be contained in the rdf. Not all RSS-viewers show this logo.
Image image = new Image();
image.setLink(objectUrl);
image.setTitle(labels.getString(clazz + ".logo.title"));
image.setUrl(dspaceUrl + "/retrieve/" + logo.getID());
channel.setImage(image);
}
}
// this is a direct link to the search-engine of dspace. It searches
// in the current collection. Since the current version of DSpace
// can't search within collections anymore, this works only in older
// version until this bug is fixed.
TextInput input = new TextInput();
input.setLink(dspaceUrl + "/simple-search");
input.setDescription( labels.getString(clazz + ".search.description") );
String searchTitle = "";
//if a "type" of feed was specified, build search title off that
if(type!=null)
{
searchTitle = MessageFormat.format(labels.getString(clazz + ".search.title"),
new Object[]{type});
}
else //otherwise, default to a more generic search title
{
searchTitle = labels.getString(clazz + ".search.title.default");
}
input.setTitle(searchTitle);
input.setName(labels.getString(clazz + ".search.name"));
channel.setTextInput(input);
// gather & add items to the feed.
scope.setResultsPerPage(itemCount);
BrowseEngine be = new BrowseEngine(context);
BrowseInfo bi = be.browseMini(scope);
Item[] results = bi.getItemResults(context);
List items = new ArrayList();
for (int i = 0; i < results.length; i++)
{
items.add(itemFromDSpaceItem(context, results[i]));
}
channel.setItems(items);
// If the description is null, replace it with an empty string
// to avoid a FeedException
if (channel.getDescription() == null)
channel.setDescription("");
return channel;
}
catch (BrowseException e)
{
log.error("caught exception: ", e);
throw new IOException(e.getMessage());
}
}
/**
* The metadata fields of the given item will be added to the given feed.
*
* @param context DSpace context object
*
* @param dspaceItem DSpace Item
*
* @return an object representing a feed entry
*/
private com.sun.syndication.feed.rss.Item itemFromDSpaceItem(Context context,
Item dspaceItem)
throws SQLException
{
com.sun.syndication.feed.rss.Item rssItem =
new com.sun.syndication.feed.rss.Item();
//get the title and date fields
String titleField = ConfigurationManager.getProperty("webui.feed.item.title");
if (titleField == null)
{
titleField = "dc.title";
}
String dateField = ConfigurationManager.getProperty("webui.feed.item.date");
if (dateField == null)
{
dateField = "dc.date.issued";
}
//Set item handle
String itHandle = ConfigurationManager.getBooleanProperty("webui.feed.localresolve")
? HandleManager.resolveToURL(context, dspaceItem.getHandle())
: HandleManager.getCanonicalForm(dspaceItem.getHandle());
rssItem.setLink(itHandle);
//get first title
String title = null;
try
{
title = dspaceItem.getMetadata(titleField)[0].value;
}
catch (ArrayIndexOutOfBoundsException e)
{
title = labels.getString(clazz + ".notitle");
}
rssItem.setTitle(title);
// We put some metadata in the description field. This field is
// displayed by most RSS viewers
String descriptionFields = ConfigurationManager
.getProperty("webui.feed.item.description");
if (descriptionFields == null)
{
descriptionFields = defaultDescriptionFields;
}
//loop through all the metadata fields to put in the description
StringBuffer descBuf = new StringBuffer();
StringTokenizer st = new StringTokenizer(descriptionFields, ",");
while (st.hasMoreTokens())
{
String field = st.nextToken().trim();
boolean isDate = false;
// Find out if the field should rendered as a date
if (field.indexOf("(date)") > 0)
{
field = field.replaceAll("\\(date\\)", "");
isDate = true;
}
//print out this field, along with its value(s)
DCValue[] values = dspaceItem.getMetadata(field);
if(values != null && values.length>0)
{
//as long as there is already something in the description
//buffer, print out a few line breaks before the next field
if(descBuf.length() > 0)
{
descBuf.append("\n<br/>");
descBuf.append("\n<br/>");
}
String fieldLabel = null;
try
{
fieldLabel = labels.getString("metadata." + field);
}
catch(java.util.MissingResourceException e) {}
if(fieldLabel !=null && fieldLabel.length()>0)
descBuf.append(fieldLabel + ": ");
for(int i=0; i<values.length; i++)
{
String fieldValue = values[i].value;
if(isDate)
fieldValue = (new DCDate(fieldValue)).toString();
descBuf.append(fieldValue);
if (i < values.length - 1)
{
descBuf.append("; ");
}
}
}
}//end while
Description descrip = new Description();
descrip.setValue(descBuf.toString());
rssItem.setDescription(descrip);
// set date field
String dcDate = null;
try
{
dcDate = dspaceItem.getMetadata(dateField)[0].value;
}
catch (ArrayIndexOutOfBoundsException e)
{
}
if (dcDate != null)
{
rssItem.setPubDate((new DCDate(dcDate)).toDate());
}
return rssItem;
}
/************************************************
* private cache management classes and methods *
************************************************/
/**
* Add a feed to the cache - reducing the size of the cache by 1 to make room if
* necessary. The removed entry has an access count equal to the minumum in the cache.
* @param feedKey
* The cache key for the feed
* @param newFeed
* The CacheFeed feed to be cached
*/
private static void cache(String feedKey, CacheFeed newFeed)
{
// remove older feed to make room if cache full
if (feedCache.size() >= cacheSize)
{
// cache profiling data
int total = 0;
String minKey = null;
CacheFeed minFeed = null;
CacheFeed maxFeed = null;
Iterator iter = feedCache.keySet().iterator();
while (iter.hasNext())
{
String key = (String)iter.next();
CacheFeed feed = (CacheFeed)feedCache.get(key);
if (minKey != null)
{
if (feed.hits < minFeed.hits)
{
minKey = key;
minFeed = feed;
}
if (feed.hits >= maxFeed.hits)
{
maxFeed = feed;
}
}
else
{
minKey = key;
minFeed = maxFeed = feed;
}
total += feed.hits;
}
// log a profile of the cache to assist administrator in tuning it
int avg = total / feedCache.size();
String logMsg = "feedCache() - size: " + feedCache.size() +
" Hits - total: " + total + " avg: " + avg +
" max: " + maxFeed.hits + " min: " + minFeed.hits;
log.info(logMsg);
// remove minimum hits entry
feedCache.remove(minKey);
}
// add feed to cache
feedCache.put(feedKey, newFeed);
}
/**
* Class to instrument accesses & currency of a given feed in cache
*/
private class CacheFeed
{
// currency timestamp
public long timeStamp = 0L;
// access count
public int hits = 0;
// the feed
private Channel feed = null;
public CacheFeed(Channel feed)
{
this.feed = feed;
timeStamp = System.currentTimeMillis();
}
public Channel access()
{
++hits;
return feed;
}
}
}
| false | true | private Channel generateFeed(Context context, DSpaceObject dso)
throws IOException, SQLException
{
try
{
// container-level elements
String dspaceUrl = ConfigurationManager.getProperty("dspace.url");
String type = null;
String description = null;
String title = null;
Bitstream logo = null;
// browse scope
// BrowseScope scope = new BrowseScope(context);
// new method of doing the browse:
String idx = ConfigurationManager.getProperty("recent.submissions.sort-option");
if (idx == null)
{
throw new IOException("There is no configuration supplied for: recent.submissions.sort-option");
}
BrowseIndex bix = BrowseIndex.getItemBrowseIndex();
if (bix == null)
{
throw new IOException("There is no browse index with the name: " + idx);
}
BrowserScope scope = new BrowserScope(context);
scope.setBrowseIndex(bix);
for (SortOption so : SortOption.getSortOptions())
{
if (so.getName().equals(idx))
scope.setSortBy(so.getNumber());
}
// the feed
Channel channel = new Channel();
//Special Case: if DSpace Object passed in is null,
//generate a feed for the entire DSpace site!
if(dso == null)
{
channel.setTitle(ConfigurationManager.getProperty("dspace.name"));
channel.setLink(dspaceUrl);
channel.setDescription(labels.getString(clazz + ".general-feed.description"));
}
else //otherwise, this is a Collection or Community specific feed
{
if (dso.getType() == Constants.COLLECTION)
{
type = labels.getString(clazz + ".feed-type.collection");
Collection col = (Collection)dso;
description = col.getMetadata("short_description");
title = col.getMetadata("name");
logo = col.getLogo();
// scope.setScope(col);
scope.setBrowseContainer(col);
}
else if (dso.getType() == Constants.COMMUNITY)
{
type = labels.getString(clazz + ".feed-type.community");
Community comm = (Community)dso;
description = comm.getMetadata("short_description");
title = comm.getMetadata("name");
logo = comm.getLogo();
// scope.setScope(comm);
scope.setBrowseContainer(comm);
}
String objectUrl = ConfigurationManager.getBooleanProperty("webui.feed.localresolve")
? HandleManager.resolveToURL(context, dso.getHandle())
: HandleManager.getCanonicalForm(dso.getHandle());
// put in container-level data
channel.setDescription(description);
channel.setLink(objectUrl);
//build channel title by passing in type and title
String channelTitle = MessageFormat.format(labels.getString(clazz + ".feed.title"),
new Object[]{type, title});
channel.setTitle(channelTitle);
//if collection or community has a logo
if (logo != null)
{
// we use the path to the logo for this, the logo itself cannot
// be contained in the rdf. Not all RSS-viewers show this logo.
Image image = new Image();
image.setLink(objectUrl);
image.setTitle(labels.getString(clazz + ".logo.title"));
image.setUrl(dspaceUrl + "/retrieve/" + logo.getID());
channel.setImage(image);
}
}
// this is a direct link to the search-engine of dspace. It searches
// in the current collection. Since the current version of DSpace
// can't search within collections anymore, this works only in older
// version until this bug is fixed.
TextInput input = new TextInput();
input.setLink(dspaceUrl + "/simple-search");
input.setDescription( labels.getString(clazz + ".search.description") );
String searchTitle = "";
//if a "type" of feed was specified, build search title off that
if(type!=null)
{
searchTitle = MessageFormat.format(labels.getString(clazz + ".search.title"),
new Object[]{type});
}
else //otherwise, default to a more generic search title
{
searchTitle = labels.getString(clazz + ".search.title.default");
}
input.setTitle(searchTitle);
input.setName(labels.getString(clazz + ".search.name"));
channel.setTextInput(input);
// gather & add items to the feed.
scope.setResultsPerPage(itemCount);
BrowseEngine be = new BrowseEngine(context);
BrowseInfo bi = be.browseMini(scope);
Item[] results = bi.getItemResults(context);
List items = new ArrayList();
for (int i = 0; i < results.length; i++)
{
items.add(itemFromDSpaceItem(context, results[i]));
}
channel.setItems(items);
// If the description is null, replace it with an empty string
// to avoid a FeedException
if (channel.getDescription() == null)
channel.setDescription("");
return channel;
}
catch (BrowseException e)
{
log.error("caught exception: ", e);
throw new IOException(e.getMessage());
}
}
| private Channel generateFeed(Context context, DSpaceObject dso)
throws IOException, SQLException
{
try
{
// container-level elements
String dspaceUrl = ConfigurationManager.getProperty("dspace.url");
String type = null;
String description = null;
String title = null;
Bitstream logo = null;
// browse scope
// BrowseScope scope = new BrowseScope(context);
// new method of doing the browse:
String idx = ConfigurationManager.getProperty("recent.submissions.sort-option");
if (idx == null)
{
throw new IOException("There is no configuration supplied for: recent.submissions.sort-option");
}
BrowseIndex bix = BrowseIndex.getItemBrowseIndex();
if (bix == null)
{
throw new IOException("There is no browse index with the name: " + idx);
}
BrowserScope scope = new BrowserScope(context);
scope.setBrowseIndex(bix);
for (SortOption so : SortOption.getSortOptions())
{
if (so.getName().equals(idx))
scope.setSortBy(so.getNumber());
}
scope.setOrder(SortOption.DESCENDING);
// the feed
Channel channel = new Channel();
//Special Case: if DSpace Object passed in is null,
//generate a feed for the entire DSpace site!
if(dso == null)
{
channel.setTitle(ConfigurationManager.getProperty("dspace.name"));
channel.setLink(dspaceUrl);
channel.setDescription(labels.getString(clazz + ".general-feed.description"));
}
else //otherwise, this is a Collection or Community specific feed
{
if (dso.getType() == Constants.COLLECTION)
{
type = labels.getString(clazz + ".feed-type.collection");
Collection col = (Collection)dso;
description = col.getMetadata("short_description");
title = col.getMetadata("name");
logo = col.getLogo();
// scope.setScope(col);
scope.setBrowseContainer(col);
}
else if (dso.getType() == Constants.COMMUNITY)
{
type = labels.getString(clazz + ".feed-type.community");
Community comm = (Community)dso;
description = comm.getMetadata("short_description");
title = comm.getMetadata("name");
logo = comm.getLogo();
// scope.setScope(comm);
scope.setBrowseContainer(comm);
}
String objectUrl = ConfigurationManager.getBooleanProperty("webui.feed.localresolve")
? HandleManager.resolveToURL(context, dso.getHandle())
: HandleManager.getCanonicalForm(dso.getHandle());
// put in container-level data
channel.setDescription(description);
channel.setLink(objectUrl);
//build channel title by passing in type and title
String channelTitle = MessageFormat.format(labels.getString(clazz + ".feed.title"),
new Object[]{type, title});
channel.setTitle(channelTitle);
//if collection or community has a logo
if (logo != null)
{
// we use the path to the logo for this, the logo itself cannot
// be contained in the rdf. Not all RSS-viewers show this logo.
Image image = new Image();
image.setLink(objectUrl);
image.setTitle(labels.getString(clazz + ".logo.title"));
image.setUrl(dspaceUrl + "/retrieve/" + logo.getID());
channel.setImage(image);
}
}
// this is a direct link to the search-engine of dspace. It searches
// in the current collection. Since the current version of DSpace
// can't search within collections anymore, this works only in older
// version until this bug is fixed.
TextInput input = new TextInput();
input.setLink(dspaceUrl + "/simple-search");
input.setDescription( labels.getString(clazz + ".search.description") );
String searchTitle = "";
//if a "type" of feed was specified, build search title off that
if(type!=null)
{
searchTitle = MessageFormat.format(labels.getString(clazz + ".search.title"),
new Object[]{type});
}
else //otherwise, default to a more generic search title
{
searchTitle = labels.getString(clazz + ".search.title.default");
}
input.setTitle(searchTitle);
input.setName(labels.getString(clazz + ".search.name"));
channel.setTextInput(input);
// gather & add items to the feed.
scope.setResultsPerPage(itemCount);
BrowseEngine be = new BrowseEngine(context);
BrowseInfo bi = be.browseMini(scope);
Item[] results = bi.getItemResults(context);
List items = new ArrayList();
for (int i = 0; i < results.length; i++)
{
items.add(itemFromDSpaceItem(context, results[i]));
}
channel.setItems(items);
// If the description is null, replace it with an empty string
// to avoid a FeedException
if (channel.getDescription() == null)
channel.setDescription("");
return channel;
}
catch (BrowseException e)
{
log.error("caught exception: ", e);
throw new IOException(e.getMessage());
}
}
|
diff --git a/java/modules/core/src/main/java/org/apache/synapse/config/xml/SynapseXMLConfigurationFactory.java b/java/modules/core/src/main/java/org/apache/synapse/config/xml/SynapseXMLConfigurationFactory.java
index 13595faa9..3777b12e6 100644
--- a/java/modules/core/src/main/java/org/apache/synapse/config/xml/SynapseXMLConfigurationFactory.java
+++ b/java/modules/core/src/main/java/org/apache/synapse/config/xml/SynapseXMLConfigurationFactory.java
@@ -1,376 +1,376 @@
/*
* 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.synapse.config.xml;
import org.apache.axiom.om.OMElement;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.synapse.Mediator;
import org.apache.synapse.Startup;
import org.apache.synapse.SynapseConstants;
import org.apache.synapse.SynapseException;
import org.apache.synapse.config.xml.endpoints.TemplateFactory;
import org.apache.synapse.config.xml.rest.APIFactory;
import org.apache.synapse.endpoints.Template;
import org.apache.synapse.libraries.imports.SynapseImport;
import org.apache.synapse.libraries.model.Library;
import org.apache.synapse.libraries.util.LibDeployerUtils;
import org.apache.synapse.mediators.template.TemplateMediator;
import org.apache.synapse.message.processors.MessageProcessor;
import org.apache.synapse.message.store.MessageStore;
import org.apache.synapse.commons.executors.PriorityExecutor;
import org.apache.synapse.commons.executors.config.PriorityExecutorFactory;
import org.apache.synapse.config.Entry;
import org.apache.synapse.config.SynapseConfigUtils;
import org.apache.synapse.config.SynapseConfiguration;
import org.apache.synapse.config.xml.endpoints.EndpointFactory;
import org.apache.synapse.config.xml.eventing.EventSourceFactory;
import org.apache.synapse.core.axis2.ProxyService;
import org.apache.synapse.endpoints.Endpoint;
import org.apache.synapse.eventing.SynapseEventSource;
import org.apache.synapse.registry.Registry;
import org.apache.axis2.AxisFault;
import org.apache.synapse.rest.API;
import javax.xml.namespace.QName;
import java.util.Iterator;
import java.util.Properties;
public class SynapseXMLConfigurationFactory implements ConfigurationFactory {
private static Log log = LogFactory.getLog(SynapseXMLConfigurationFactory.class);
public SynapseConfiguration getConfiguration(OMElement definitions, Properties properties) {
if (!definitions.getQName().equals(XMLConfigConstants.DEFINITIONS_ELT)) {
throw new SynapseException(
"Wrong QName for this configuration factory " + definitions.getQName());
}
SynapseConfiguration config = SynapseConfigUtils.newConfiguration();
config.setDefaultQName(definitions.getQName());
Iterator itr = definitions.getChildren();
while (itr.hasNext()) {
Object o = itr.next();
if (o instanceof OMElement) {
OMElement elt = (OMElement) o;
if (XMLConfigConstants.SEQUENCE_ELT.equals(elt.getQName())) {
String key = elt.getAttributeValue(
new QName(XMLConfigConstants.NULL_NAMESPACE, "key"));
// this could be a sequence def or a referred sequence
if (key != null) {
handleException("Referred sequences are not allowed at the top level");
} else {
defineSequence(config, elt, properties);
}
} else if (XMLConfigConstants.TEMPLATE_ELT.equals(elt.getQName())) {
defineTemplate(config, elt, properties);
} else if (XMLConfigConstants.IMPORT_ELT.equals(elt.getQName())) {
defineImport(config, elt, properties);
} else if (XMLConfigConstants.ENDPOINT_ELT.equals(elt.getQName())) {
defineEndpoint(config, elt, properties);
} else if (XMLConfigConstants.ENTRY_ELT.equals(elt.getQName())) {
defineEntry(config, elt, properties);
} else if (XMLConfigConstants.PROXY_ELT.equals(elt.getQName())) {
defineProxy(config, elt, properties);
} else if (XMLConfigConstants.REGISTRY_ELT.equals(elt.getQName())) {
defineRegistry(config, elt, properties);
} else if (XMLConfigConstants.EVENT_SOURCE_ELT.equals(elt.getQName())) {
defineEventSource(config, elt, properties);
} else if (XMLConfigConstants.EXECUTOR_ELT.equals(elt.getQName())) {
defineExecutor(config, elt, properties);
} else if(XMLConfigConstants.MESSAGE_STORE_ELT.equals(elt.getQName())) {
defineMessageStore(config, elt, properties);
} else if (XMLConfigConstants.MESSAGE_PROCESSOR_ELT.equals(elt.getQName())){
defineMessageProcessor(config, elt, properties);
} else if (StartupFinder.getInstance().isStartup(elt.getQName())) {
defineStartup(config, elt, properties);
} else if (XMLConfigConstants.API_ELT.equals(elt.getQName())) {
defineAPI(config, elt);
} else if (XMLConfigConstants.DESCRIPTION_ELT.equals(elt.getQName())) {
config.setDescription(elt.getText());
} else {
handleException("Invalid configuration element at the top level, one of \'sequence\', " +
"\'endpoint\', \'proxy\', \'eventSource\', \'localEntry\', \'priorityExecutor\' " +
- "or \'registry\' is expected");
+ "or \'registry\' is expected. Found '" + elt.getQName() + "'.");
}
}
}
return config;
}
public static Registry defineRegistry(SynapseConfiguration config, OMElement elem,
Properties properties) {
if (config.getRegistry() != null) {
handleException("Only one remote registry can be defined within a configuration");
}
Registry registry = RegistryFactory.createRegistry(elem, properties);
config.setRegistry(registry);
return registry;
}
public static Startup defineStartup(SynapseConfiguration config, OMElement elem,
Properties properties) {
Startup startup = StartupFinder.getInstance().getStartup(elem, properties);
config.addStartup(startup);
return startup;
}
public static ProxyService defineProxy(SynapseConfiguration config, OMElement elem,
Properties properties) {
ProxyService proxy = null;
try {
proxy = ProxyServiceFactory.createProxy(elem, properties);
if (proxy != null) {
config.addProxyService(proxy.getName(), proxy);
}
} catch (Exception e) {
String msg = "Proxy Service configuration: " + elem.getAttributeValue((
new QName(XMLConfigConstants.NULL_NAMESPACE, "name"))) + " cannot be built";
handleConfigurationError(SynapseConstants.FAIL_SAFE_MODE_PROXY_SERVICES, msg, e);
}
return proxy;
}
public static Entry defineEntry(SynapseConfiguration config, OMElement elem,
Properties properties) {
Entry entry = null;
try {
entry = EntryFactory.createEntry(elem, properties);
if (entry != null) {
config.addEntry(entry.getKey(), entry);
}
} catch (Exception e) {
String msg = "Local entry configuration: " + elem.getAttributeValue((
new QName(XMLConfigConstants.NULL_NAMESPACE, "key"))) + " cannot be built";
handleConfigurationError(SynapseConstants.FAIL_SAFE_MODE_LOCALENTRIES, msg, e);
}
return entry;
}
public static Mediator defineSequence(SynapseConfiguration config, OMElement ele,
Properties properties) {
Mediator mediator = null;
String name = ele.getAttributeValue(new QName(XMLConfigConstants.NULL_NAMESPACE, "name"));
if (name != null) {
try {
mediator = MediatorFactoryFinder.getInstance().getMediator(ele, properties);
if (mediator != null) {
config.addSequence(name, mediator);
// mandatory sequence is treated as a special sequence because it will be fetched for
// each and every message and keeps a direct reference to that from the configuration
// this also limits the ability of the mandatory sequence to be dynamic
if (SynapseConstants.MANDATORY_SEQUENCE_KEY.equals(name)) {
config.setMandatorySequence(mediator);
}
}
} catch (Exception e) {
String msg = "Sequence configuration: " + name + " cannot be built";
handleConfigurationError(SynapseConstants.FAIL_SAFE_MODE_SEQUENCES, msg, e);
}
return mediator;
} else {
String msg = "Invalid sequence definition without a name";
handleConfigurationError(SynapseConstants.FAIL_SAFE_MODE_SEQUENCES, msg);
}
return null;
}
public static Mediator defineMediatorTemplate(SynapseConfiguration config, OMElement ele,
Properties properties) {
Mediator mediator = null;
String name = ele.getAttributeValue(new QName(XMLConfigConstants.NULL_NAMESPACE, "name"));
if (name != null) {
try {
mediator = MediatorFactoryFinder.getInstance().getMediator(ele, properties);
if (mediator != null) {
config.addSequenceTemplate(name, (TemplateMediator) mediator) ;
}
} catch (Exception e) {
String msg = "Template configuration: " + name + " cannot be built";
handleConfigurationError(SynapseConstants.FAIL_SAFE_MODE_TEMPLATES, msg, e);
}
return mediator;
} else {
String msg = "Invalid mediation template definition without a name";
handleConfigurationError(SynapseConstants.FAIL_SAFE_MODE_SEQUENCES, msg);
}
return null;
}
public static Endpoint defineEndpoint(SynapseConfiguration config, OMElement ele,
Properties properties) {
String name = ele.getAttributeValue(new QName(XMLConfigConstants.NULL_NAMESPACE, "name"));
Endpoint endpoint = null;
if (name != null) {
try {
endpoint = EndpointFactory.getEndpointFromElement(ele, false, properties);
if (endpoint != null) {
config.addEndpoint(name.trim(), endpoint);
}
} catch (Exception e) {
String msg = "Endpoint configuration: " + name + " cannot be built";
handleConfigurationError(SynapseConstants.FAIL_SAFE_MODE_EP, msg, e);
}
return endpoint;
} else {
String msg = "Invalid endpoint definition without a name";
handleConfigurationError(SynapseConstants.FAIL_SAFE_MODE_SEQUENCES, msg);
}
return null;
}
public static SynapseEventSource defineEventSource(SynapseConfiguration config,
OMElement elem, Properties properties) {
SynapseEventSource eventSource = null;
try {
eventSource = EventSourceFactory.createEventSource(elem, properties);
if (eventSource != null) {
config.addEventSource(eventSource.getName(), eventSource);
}
} catch (Exception e) {
String msg = "Event Source configuration cannot be built";
handleConfigurationError(SynapseConstants.FAIL_SAFE_MODE_EVENT_SOURCE, msg, e);
}
return eventSource;
}
public static PriorityExecutor defineExecutor(SynapseConfiguration config,
OMElement elem, Properties properties) {
PriorityExecutor executor = null;
try {
executor = PriorityExecutorFactory.createExecutor(
XMLConfigConstants.SYNAPSE_NAMESPACE, elem, true, properties);
assert executor != null;
config.addPriorityExecutor(executor.getName(), executor);
} catch (AxisFault axisFault) {
String msg = "Executor configuration cannot be built";
handleConfigurationError(SynapseConstants.FAIL_SAFE_MODE_EXECUTORS, msg, axisFault);
}
return executor;
}
public static MessageStore defineMessageStore(SynapseConfiguration config ,
OMElement elem, Properties properties) {
MessageStore messageStore = MessageStoreFactory.createMessageStore(elem, properties);
config.addMessageStore(messageStore.getName(), messageStore);
return messageStore;
}
public static MessageProcessor defineMessageProcessor(SynapseConfiguration config,
OMElement elem, Properties properties) {
MessageProcessor processor = MessageProcessorFactory.createMessageProcessor(elem);
config.addMessageProcessor(processor.getName() , processor);
return processor;
}
public static SynapseImport defineImport(SynapseConfiguration config, OMElement elt, Properties properties) {
SynapseImport synImport = SynapseImportFactory.createImport(elt, properties);
String libIndexString = LibDeployerUtils.getQualifiedName(synImport);
config.addSynapseImport(libIndexString, synImport);
//get corresponding library for loading imports if available
Library synLib = config.getSynapseLibraries().get(libIndexString);
if (synLib != null) {
LibDeployerUtils.loadLibArtifacts(synImport, synLib);
}
return synImport;
}
public static Template defineEndpointTemplate(SynapseConfiguration config,
OMElement elem, Properties properties) {
TemplateFactory templateFactory = new TemplateFactory();
String name = elem.getAttributeValue(new QName(XMLConfigConstants.NULL_NAMESPACE, "name"));
try {
Template template = templateFactory.createEndpointTemplate(elem, properties);
if (template != null) {
config.addEndpointTemplate(template.getName(), template);
}
return template;
} catch (Exception e) {
String msg = "Endpoint Template: " + name + "configuration cannot be built";
handleConfigurationError(SynapseConstants.FAIL_SAFE_MODE_TEMPLATES, msg, e);
}
return null;
}
public static void defineTemplate(SynapseConfiguration config,
OMElement elem, Properties properties) {
OMElement element = elem.getFirstChildWithName(
new QName(SynapseConstants.SYNAPSE_NAMESPACE, "sequence"));
if (element != null) {
defineMediatorTemplate(config, elem, properties);
}
element = elem.getFirstChildWithName(
new QName(SynapseConstants.SYNAPSE_NAMESPACE, "endpoint"));
if (element != null) {
defineEndpointTemplate(config, elem, properties);
}
}
public static API defineAPI(SynapseConfiguration config, OMElement elem) {
API api = APIFactory.createAPI(elem);
config.addAPI(api.getName(), api);
return api;
}
private static void handleException(String msg) {
log.error(msg);
throw new SynapseException(msg);
}
public QName getTagQName() {
return XMLConfigConstants.DEFINITIONS_ELT;
}
public Class getSerializerClass() {
return SynapseXMLConfigurationSerializer.class;
}
private static void handleConfigurationError(String componentType, String msg) {
if (SynapseConfigUtils.isFailSafeEnabled(componentType)) {
log.warn(msg + " - Continue in fail-safe mode");
} else {
handleException(msg);
}
}
private static void handleConfigurationError(String componentType, String msg, Exception e) {
if (SynapseConfigUtils.isFailSafeEnabled(componentType)) {
log.warn(msg + " - Continue in fail-safe mode", e);
} else {
log.error(msg, e);
throw new SynapseException(msg, e);
}
}
}
| true | true | public SynapseConfiguration getConfiguration(OMElement definitions, Properties properties) {
if (!definitions.getQName().equals(XMLConfigConstants.DEFINITIONS_ELT)) {
throw new SynapseException(
"Wrong QName for this configuration factory " + definitions.getQName());
}
SynapseConfiguration config = SynapseConfigUtils.newConfiguration();
config.setDefaultQName(definitions.getQName());
Iterator itr = definitions.getChildren();
while (itr.hasNext()) {
Object o = itr.next();
if (o instanceof OMElement) {
OMElement elt = (OMElement) o;
if (XMLConfigConstants.SEQUENCE_ELT.equals(elt.getQName())) {
String key = elt.getAttributeValue(
new QName(XMLConfigConstants.NULL_NAMESPACE, "key"));
// this could be a sequence def or a referred sequence
if (key != null) {
handleException("Referred sequences are not allowed at the top level");
} else {
defineSequence(config, elt, properties);
}
} else if (XMLConfigConstants.TEMPLATE_ELT.equals(elt.getQName())) {
defineTemplate(config, elt, properties);
} else if (XMLConfigConstants.IMPORT_ELT.equals(elt.getQName())) {
defineImport(config, elt, properties);
} else if (XMLConfigConstants.ENDPOINT_ELT.equals(elt.getQName())) {
defineEndpoint(config, elt, properties);
} else if (XMLConfigConstants.ENTRY_ELT.equals(elt.getQName())) {
defineEntry(config, elt, properties);
} else if (XMLConfigConstants.PROXY_ELT.equals(elt.getQName())) {
defineProxy(config, elt, properties);
} else if (XMLConfigConstants.REGISTRY_ELT.equals(elt.getQName())) {
defineRegistry(config, elt, properties);
} else if (XMLConfigConstants.EVENT_SOURCE_ELT.equals(elt.getQName())) {
defineEventSource(config, elt, properties);
} else if (XMLConfigConstants.EXECUTOR_ELT.equals(elt.getQName())) {
defineExecutor(config, elt, properties);
} else if(XMLConfigConstants.MESSAGE_STORE_ELT.equals(elt.getQName())) {
defineMessageStore(config, elt, properties);
} else if (XMLConfigConstants.MESSAGE_PROCESSOR_ELT.equals(elt.getQName())){
defineMessageProcessor(config, elt, properties);
} else if (StartupFinder.getInstance().isStartup(elt.getQName())) {
defineStartup(config, elt, properties);
} else if (XMLConfigConstants.API_ELT.equals(elt.getQName())) {
defineAPI(config, elt);
} else if (XMLConfigConstants.DESCRIPTION_ELT.equals(elt.getQName())) {
config.setDescription(elt.getText());
} else {
handleException("Invalid configuration element at the top level, one of \'sequence\', " +
"\'endpoint\', \'proxy\', \'eventSource\', \'localEntry\', \'priorityExecutor\' " +
"or \'registry\' is expected");
}
}
}
return config;
}
| public SynapseConfiguration getConfiguration(OMElement definitions, Properties properties) {
if (!definitions.getQName().equals(XMLConfigConstants.DEFINITIONS_ELT)) {
throw new SynapseException(
"Wrong QName for this configuration factory " + definitions.getQName());
}
SynapseConfiguration config = SynapseConfigUtils.newConfiguration();
config.setDefaultQName(definitions.getQName());
Iterator itr = definitions.getChildren();
while (itr.hasNext()) {
Object o = itr.next();
if (o instanceof OMElement) {
OMElement elt = (OMElement) o;
if (XMLConfigConstants.SEQUENCE_ELT.equals(elt.getQName())) {
String key = elt.getAttributeValue(
new QName(XMLConfigConstants.NULL_NAMESPACE, "key"));
// this could be a sequence def or a referred sequence
if (key != null) {
handleException("Referred sequences are not allowed at the top level");
} else {
defineSequence(config, elt, properties);
}
} else if (XMLConfigConstants.TEMPLATE_ELT.equals(elt.getQName())) {
defineTemplate(config, elt, properties);
} else if (XMLConfigConstants.IMPORT_ELT.equals(elt.getQName())) {
defineImport(config, elt, properties);
} else if (XMLConfigConstants.ENDPOINT_ELT.equals(elt.getQName())) {
defineEndpoint(config, elt, properties);
} else if (XMLConfigConstants.ENTRY_ELT.equals(elt.getQName())) {
defineEntry(config, elt, properties);
} else if (XMLConfigConstants.PROXY_ELT.equals(elt.getQName())) {
defineProxy(config, elt, properties);
} else if (XMLConfigConstants.REGISTRY_ELT.equals(elt.getQName())) {
defineRegistry(config, elt, properties);
} else if (XMLConfigConstants.EVENT_SOURCE_ELT.equals(elt.getQName())) {
defineEventSource(config, elt, properties);
} else if (XMLConfigConstants.EXECUTOR_ELT.equals(elt.getQName())) {
defineExecutor(config, elt, properties);
} else if(XMLConfigConstants.MESSAGE_STORE_ELT.equals(elt.getQName())) {
defineMessageStore(config, elt, properties);
} else if (XMLConfigConstants.MESSAGE_PROCESSOR_ELT.equals(elt.getQName())){
defineMessageProcessor(config, elt, properties);
} else if (StartupFinder.getInstance().isStartup(elt.getQName())) {
defineStartup(config, elt, properties);
} else if (XMLConfigConstants.API_ELT.equals(elt.getQName())) {
defineAPI(config, elt);
} else if (XMLConfigConstants.DESCRIPTION_ELT.equals(elt.getQName())) {
config.setDescription(elt.getText());
} else {
handleException("Invalid configuration element at the top level, one of \'sequence\', " +
"\'endpoint\', \'proxy\', \'eventSource\', \'localEntry\', \'priorityExecutor\' " +
"or \'registry\' is expected. Found '" + elt.getQName() + "'.");
}
}
}
return config;
}
|
diff --git a/jung-algorithms/src/main/java/edu/uci/ics/jung/algorithms/util/WeightedChoice.java b/jung-algorithms/src/main/java/edu/uci/ics/jung/algorithms/util/WeightedChoice.java
index d0b45de4..d9590b26 100644
--- a/jung-algorithms/src/main/java/edu/uci/ics/jung/algorithms/util/WeightedChoice.java
+++ b/jung-algorithms/src/main/java/edu/uci/ics/jung/algorithms/util/WeightedChoice.java
@@ -1,193 +1,193 @@
/**
* Copyright (c) 2009, the JUNG Project and the Regents of the University
* of California
* All rights reserved.
*
* This software is open-source under the BSD license; see either
* "license.txt" or
* http://jung.sourceforge.net/license.txt for a description.
* Created on Jan 8, 2009
*
*/
package edu.uci.ics.jung.algorithms.util;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Random;
/**
* Selects items according to their probability in an arbitrary probability
* distribution. The distribution is specified by a {@code Map} from
* items (of type {@code T}) to weights of type {@code Number}, supplied
* to the constructor; these weights are normalized internally to act as
* probabilities.
*
* <p>This implementation selects items in O(1) time, and requires O(n) space.
*
* @author Joshua O'Madadhain
*/
public class WeightedChoice<T>
{
private List<ItemPair> item_pairs;
private Random random;
/**
* The default minimum value that is treated as a valid probability
* (as opposed to rounding error from floating-point operations).
*/
public static final double DEFAULT_THRESHOLD = 0.00000000001;
/**
* Equivalent to {@code this(item_weights, new Random(), DEFAULT_THRESHOLD)}.
* @param item_weights
*/
public WeightedChoice(Map<T, ? extends Number> item_weights)
{
this(item_weights, new Random(), DEFAULT_THRESHOLD);
}
/**
* Equivalent to {@code this(item_weights, new Random(), threshold)}.
*/
public WeightedChoice(Map<T, ? extends Number> item_weights, double threshold)
{
this(item_weights, new Random(), threshold);
}
/**
* Equivalent to {@code this(item_weights, random, DEFAULT_THRESHOLD)}.
*/
public WeightedChoice(Map<T, ? extends Number> item_weights, Random random)
{
this(item_weights, random, DEFAULT_THRESHOLD);
}
/**
* Creates an instance with the specified mapping from items to weights,
* random number generator, and threshold value.
*
* <p>The mapping defines the weight for each item to be selected; this
* will be proportional to the probability of its selection.
* <p>The random number generator specifies the mechanism which will be
* used to provide uniform integer and double values.
* <p>The threshold indicates default minimum value that is treated as a valid
* probability (as opposed to rounding error from floating-point operations).
*/
public WeightedChoice(Map<T, ? extends Number> item_weights, Random random,
double threshold)
{
if (item_weights.isEmpty())
throw new IllegalArgumentException("Item weights must be non-empty");
int item_count = item_weights.size();
item_pairs = new ArrayList<ItemPair>(item_count);
double sum = 0;
for (Map.Entry<T, ? extends Number> entry : item_weights.entrySet())
{
double value = entry.getValue().doubleValue();
if (value <= 0)
throw new IllegalArgumentException("Weights must be > 0");
sum += value;
}
- double mean_weight = sum / item_weights.size();
+ double bucket_weight = 1.0 / item_weights.size();
Queue<ItemPair> light_weights = new LinkedList<ItemPair>();
Queue<ItemPair> heavy_weights = new LinkedList<ItemPair>();
for (Map.Entry<T, ? extends Number> entry : item_weights.entrySet())
{
double value = entry.getValue().doubleValue() / sum;
- enqueueItem(entry.getKey(), value, mean_weight, light_weights, heavy_weights);
+ enqueueItem(entry.getKey(), value, bucket_weight, light_weights, heavy_weights);
}
// repeat until both queues empty
while (!heavy_weights.isEmpty() || !light_weights.isEmpty())
{
ItemPair heavy_item = heavy_weights.poll();
ItemPair light_item = light_weights.poll();
double light_weight = 0;
T light = null;
T heavy = null;
if (light_item != null)
{
light_weight = light_item.weight;
light = light_item.light;
}
if (heavy_item != null)
{
heavy = heavy_item.heavy;
// put the 'left over' weight from the heavy item--what wasn't
// needed to make up the difference between the light weight and
// 1/n--back in the appropriate queue
- double new_weight = heavy_item.weight - (mean_weight - light_weight);
+ double new_weight = heavy_item.weight - (bucket_weight - light_weight);
if (new_weight > threshold)
- enqueueItem(heavy, new_weight, mean_weight, light_weights, heavy_weights);
+ enqueueItem(heavy, new_weight, bucket_weight, light_weights, heavy_weights);
}
light_weight *= item_count;
item_pairs.add(new ItemPair(light, heavy, light_weight));
}
this.random = random;
}
/**
* Adds key/value to the appropriate queue. Keys with values less than
* the threshold get added to {@code light_weights}, all others get added
* to {@code heavy_weights}.
*/
private void enqueueItem(T key, double value, double threshold,
Queue<ItemPair> light_weights, Queue<ItemPair> heavy_weights)
{
if (value < threshold)
light_weights.offer(new ItemPair(key, null, value));
else
heavy_weights.offer(new ItemPair(null, key, value));
}
/**
* Sets the seed used by the internal random number generator.
*/
public void setRandomSeed(long seed)
{
this.random.setSeed(seed);
}
/**
* Retrieves an item with probability proportional to its weight in the
* {@code Map} provided in the input.
*/
public T nextItem()
{
ItemPair item_pair = item_pairs.get(random.nextInt(item_pairs.size()));
if (random.nextDouble() < item_pair.weight)
return item_pair.light;
return item_pair.heavy;
}
/**
* Manages light object/heavy object/light conditional probability tuples.
*/
private class ItemPair
{
T light;
T heavy;
double weight;
private ItemPair(T light, T heavy, double weight)
{
this.light = light;
this.heavy = heavy;
this.weight = weight;
}
@Override
public String toString()
{
return String.format("[L:%s, H:%s, %.3f]", light, heavy, weight);
}
}
}
| false | true | public WeightedChoice(Map<T, ? extends Number> item_weights, Random random,
double threshold)
{
if (item_weights.isEmpty())
throw new IllegalArgumentException("Item weights must be non-empty");
int item_count = item_weights.size();
item_pairs = new ArrayList<ItemPair>(item_count);
double sum = 0;
for (Map.Entry<T, ? extends Number> entry : item_weights.entrySet())
{
double value = entry.getValue().doubleValue();
if (value <= 0)
throw new IllegalArgumentException("Weights must be > 0");
sum += value;
}
double mean_weight = sum / item_weights.size();
Queue<ItemPair> light_weights = new LinkedList<ItemPair>();
Queue<ItemPair> heavy_weights = new LinkedList<ItemPair>();
for (Map.Entry<T, ? extends Number> entry : item_weights.entrySet())
{
double value = entry.getValue().doubleValue() / sum;
enqueueItem(entry.getKey(), value, mean_weight, light_weights, heavy_weights);
}
// repeat until both queues empty
while (!heavy_weights.isEmpty() || !light_weights.isEmpty())
{
ItemPair heavy_item = heavy_weights.poll();
ItemPair light_item = light_weights.poll();
double light_weight = 0;
T light = null;
T heavy = null;
if (light_item != null)
{
light_weight = light_item.weight;
light = light_item.light;
}
if (heavy_item != null)
{
heavy = heavy_item.heavy;
// put the 'left over' weight from the heavy item--what wasn't
// needed to make up the difference between the light weight and
// 1/n--back in the appropriate queue
double new_weight = heavy_item.weight - (mean_weight - light_weight);
if (new_weight > threshold)
enqueueItem(heavy, new_weight, mean_weight, light_weights, heavy_weights);
}
light_weight *= item_count;
item_pairs.add(new ItemPair(light, heavy, light_weight));
}
this.random = random;
}
| public WeightedChoice(Map<T, ? extends Number> item_weights, Random random,
double threshold)
{
if (item_weights.isEmpty())
throw new IllegalArgumentException("Item weights must be non-empty");
int item_count = item_weights.size();
item_pairs = new ArrayList<ItemPair>(item_count);
double sum = 0;
for (Map.Entry<T, ? extends Number> entry : item_weights.entrySet())
{
double value = entry.getValue().doubleValue();
if (value <= 0)
throw new IllegalArgumentException("Weights must be > 0");
sum += value;
}
double bucket_weight = 1.0 / item_weights.size();
Queue<ItemPair> light_weights = new LinkedList<ItemPair>();
Queue<ItemPair> heavy_weights = new LinkedList<ItemPair>();
for (Map.Entry<T, ? extends Number> entry : item_weights.entrySet())
{
double value = entry.getValue().doubleValue() / sum;
enqueueItem(entry.getKey(), value, bucket_weight, light_weights, heavy_weights);
}
// repeat until both queues empty
while (!heavy_weights.isEmpty() || !light_weights.isEmpty())
{
ItemPair heavy_item = heavy_weights.poll();
ItemPair light_item = light_weights.poll();
double light_weight = 0;
T light = null;
T heavy = null;
if (light_item != null)
{
light_weight = light_item.weight;
light = light_item.light;
}
if (heavy_item != null)
{
heavy = heavy_item.heavy;
// put the 'left over' weight from the heavy item--what wasn't
// needed to make up the difference between the light weight and
// 1/n--back in the appropriate queue
double new_weight = heavy_item.weight - (bucket_weight - light_weight);
if (new_weight > threshold)
enqueueItem(heavy, new_weight, bucket_weight, light_weights, heavy_weights);
}
light_weight *= item_count;
item_pairs.add(new ItemPair(light, heavy, light_weight));
}
this.random = random;
}
|
diff --git a/src/GUI/SearchField.java b/src/GUI/SearchField.java
index 931a518..3a4830d 100644
--- a/src/GUI/SearchField.java
+++ b/src/GUI/SearchField.java
@@ -1,119 +1,120 @@
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;
//class for the tip box
public class SearchField extends JPanel{
private JTextField tf;
private JComboBox combo = new JComboBox();
private Vector<String> v = new Vector<String>();
public SearchField() {
super(new BorderLayout());
combo.setEditable(true);
+ combo.setPrototypeDisplayValue(" ");
combo.setUI(new BasicComboBoxUI() {
protected JButton createArrowButton() {
return new JButton() {
public int getWidth() {
return 0;
}
};
}
});
tf = (JTextField) combo.getEditor().getEditorComponent();
tf.setBorder(BorderFactory.createLineBorder(Color.GRAY));
tf.addKeyListener(new DropdownSearchListener());
String[] regions = {"England", "West Midlands", "East Midlands", "North East England",
"North West England", "South East England", "South West England", "London",
"Yorkshire and Humber"};
- for(int i=0; i < regions.length; i++){
+ for (int i = 0; i < regions.length; i++){
v.addElement(regions[i]);
}
setModel(new DefaultComboBoxModel(v), "");
JPanel p = new JPanel(new FlowLayout());
p.add(combo, BorderLayout.NORTH);
//create search button
JButton b = new JButton("Search");
p.add(b);
b.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
//perform search
}
});
//add panel to frame
add(p);
setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
//setPreferredSize(new Dimension(20, 300));
}
private boolean hide_flag = false;
private void setModel(DefaultComboBoxModel mdl, String str) {
combo.setModel(mdl);
combo.setSelectedIndex(-1);
tf.setText(str);
}
private static DefaultComboBoxModel getSuggestedModel(java.util.List<String> list, String text) {
DefaultComboBoxModel m = new DefaultComboBoxModel();
for(String s: list) {
if(s.startsWith(text)) m.addElement(s);
}
return m;
}
class DropdownSearchListener extends KeyAdapter {
public void keyTyped(KeyEvent e) {
EventQueue.invokeLater(new Runnable() {
public void run() {
String text = tf.getText();
if (text.length() == 0) {
combo.hidePopup();
setModel(new DefaultComboBoxModel(v), "");
} else {
DefaultComboBoxModel m = getSuggestedModel(v, text);
if (m.getSize() == 0 || hide_flag) {
combo.hidePopup();
hide_flag = false;
} else {
setModel(m, text);
combo.showPopup();
}
}
}
});
}
public void keyPressed(KeyEvent e) {
String text = tf.getText();
int code = e.getKeyCode();
if (code == KeyEvent.VK_ENTER) {
if (!v.contains(text)) {
v.addElement(text);
Collections.sort(v);
setModel(getSuggestedModel(v, text), text);
}
hide_flag = true;
} else if (code == KeyEvent.VK_ESCAPE) {
hide_flag = true;
} else if (code == KeyEvent.VK_RIGHT) {
for(int i = 0; i < v.size(); i++) {
String str = v.elementAt(i);
if(str.startsWith(text)) {
combo.setSelectedIndex(-1);
tf.setText(str);
return;
}
}
}
}
}
}
| false | true | public SearchField() {
super(new BorderLayout());
combo.setEditable(true);
combo.setUI(new BasicComboBoxUI() {
protected JButton createArrowButton() {
return new JButton() {
public int getWidth() {
return 0;
}
};
}
});
tf = (JTextField) combo.getEditor().getEditorComponent();
tf.setBorder(BorderFactory.createLineBorder(Color.GRAY));
tf.addKeyListener(new DropdownSearchListener());
String[] regions = {"England", "West Midlands", "East Midlands", "North East England",
"North West England", "South East England", "South West England", "London",
"Yorkshire and Humber"};
for(int i=0; i < regions.length; i++){
v.addElement(regions[i]);
}
setModel(new DefaultComboBoxModel(v), "");
JPanel p = new JPanel(new FlowLayout());
p.add(combo, BorderLayout.NORTH);
//create search button
JButton b = new JButton("Search");
p.add(b);
b.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
//perform search
}
});
//add panel to frame
add(p);
setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
//setPreferredSize(new Dimension(20, 300));
}
| public SearchField() {
super(new BorderLayout());
combo.setEditable(true);
combo.setPrototypeDisplayValue(" ");
combo.setUI(new BasicComboBoxUI() {
protected JButton createArrowButton() {
return new JButton() {
public int getWidth() {
return 0;
}
};
}
});
tf = (JTextField) combo.getEditor().getEditorComponent();
tf.setBorder(BorderFactory.createLineBorder(Color.GRAY));
tf.addKeyListener(new DropdownSearchListener());
String[] regions = {"England", "West Midlands", "East Midlands", "North East England",
"North West England", "South East England", "South West England", "London",
"Yorkshire and Humber"};
for (int i = 0; i < regions.length; i++){
v.addElement(regions[i]);
}
setModel(new DefaultComboBoxModel(v), "");
JPanel p = new JPanel(new FlowLayout());
p.add(combo, BorderLayout.NORTH);
//create search button
JButton b = new JButton("Search");
p.add(b);
b.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
//perform search
}
});
//add panel to frame
add(p);
setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
//setPreferredSize(new Dimension(20, 300));
}
|
diff --git a/RecentActivity/src/org/sleuthkit/autopsy/recentactivity/Chrome.java b/RecentActivity/src/org/sleuthkit/autopsy/recentactivity/Chrome.java
index 85fdb5648..7d05a7855 100644
--- a/RecentActivity/src/org/sleuthkit/autopsy/recentactivity/Chrome.java
+++ b/RecentActivity/src/org/sleuthkit/autopsy/recentactivity/Chrome.java
@@ -1,508 +1,508 @@
/*
*
* Autopsy Forensic Browser
*
* Copyright 2012-2013 Basis Technology Corp.
*
* Copyright 2012 42six Solutions.
*
* Project Contact/Architect: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.recentactivity;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.sleuthkit.autopsy.ingest.IngestServices;
import org.sleuthkit.datamodel.FsContent;
import org.sleuthkit.autopsy.datamodel.ContentUtils;
import java.util.logging.Level;
import org.sleuthkit.autopsy.coreutils.Logger;
import java.util.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import org.sleuthkit.autopsy.casemodule.services.FileManager;
import org.sleuthkit.autopsy.coreutils.EscapeUtil;
import org.sleuthkit.autopsy.ingest.PipelineContext;
import org.sleuthkit.autopsy.ingest.IngestImageWorkerController;
import org.sleuthkit.autopsy.ingest.IngestModuleImage;
import org.sleuthkit.autopsy.ingest.IngestModuleInit;
import org.sleuthkit.autopsy.ingest.ModuleDataEvent;
import org.sleuthkit.datamodel.BlackboardArtifact;
import org.sleuthkit.datamodel.BlackboardArtifact.ARTIFACT_TYPE;
import org.sleuthkit.datamodel.BlackboardAttribute;
import org.sleuthkit.datamodel.BlackboardAttribute.ATTRIBUTE_TYPE;
import org.sleuthkit.datamodel.Image;
import org.sleuthkit.datamodel.TskCoreException;
import org.sleuthkit.datamodel.TskData;
/**
* Chrome recent activity extraction
*/
public class Chrome extends Extract implements IngestModuleImage {
private static final String chquery = "SELECT urls.url, urls.title, urls.visit_count, urls.typed_count, "
+ "last_visit_time, urls.hidden, visits.visit_time, (SELECT urls.url FROM urls WHERE urls.id=visits.url) as from_visit, visits.transition FROM urls, visits WHERE urls.id = visits.url";
private static final String chcookiequery = "select name, value, host_key, expires_utc,last_access_utc, creation_utc from cookies";
private static final String chbookmarkquery = "SELECT starred.title, urls.url, starred.date_added, starred.date_modified, urls.typed_count,urls._last_visit_time FROM starred INNER JOIN urls ON urls.id = starred.url_id";
private static final String chdownloadquery = "select full_path, url, start_time, received_bytes from downloads";
private static final String chloginquery = "select origin_url, username_value, signon_realm from logins";
private final Logger logger = Logger.getLogger(this.getClass().getName());
public int ChromeCount = 0;
final public static String MODULE_VERSION = "1.0";
private String args;
private IngestServices services;
//hide public constructor to prevent from instantiation by ingest module loader
Chrome() {
moduleName = "Chrome";
}
@Override
public String getVersion() {
return MODULE_VERSION;
}
@Override
public String getArguments() {
return args;
}
@Override
public void setArguments(String args) {
this.args = args;
}
@Override
public void process(PipelineContext<IngestModuleImage>pipelineContext, Image image, IngestImageWorkerController controller) {
this.getHistory(image, controller);
this.getBookmark(image, controller);
this.getCookie(image, controller);
this.getLogin(image, controller);
this.getDownload(image, controller);
}
private void getHistory(Image image, IngestImageWorkerController controller) {
FileManager fileManager = currentCase.getServices().getFileManager();
List<FsContent> historyFiles = null;
try {
historyFiles = fileManager.findFiles(image, "History", "Chrome");
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Error when trying to get Chrome history files.", ex);
}
// get only the allocated ones, for now
List<FsContent> allocatedHistoryFiles = new ArrayList<>();
for (FsContent historyFile : historyFiles) {
if (historyFile.isMetaFlagSet(TskData.TSK_FS_META_FLAG_ENUM.ALLOC)) {
allocatedHistoryFiles.add(historyFile);
}
}
// log a message if we don't have any allocated history files
if (allocatedHistoryFiles.size() == 0) {
logger.log(Level.INFO, "Could not find any allocated Chrome history files.");
return;
}
int j = 0;
while (j < historyFiles.size()) {
String temps = currentCase.getTempDirectory() + File.separator + historyFiles.get(j).getName().toString() + j + ".db";
int errors = 0;
final FsContent historyFile = historyFiles.get(j++);
if (historyFile.getSize() == 0) {
continue;
}
try {
ContentUtils.writeToFile(historyFile, new File(temps));
} catch (IOException ex) {
logger.log(Level.SEVERE, "Error writing temp sqlite db for Chrome web history artifacts.{0}", ex);
this.addErrorMessage(this.getName() + ": Error while trying to analyze file:" + historyFile.getName());
}
File dbFile = new File(temps);
if (controller.isCancelled()) {
dbFile.delete();
break;
}
List<HashMap<String, Object>> tempList = null;
tempList = this.dbConnect(temps, chquery);
logger.log(Level.INFO, moduleName + "- Now getting history from " + temps + " with " + tempList.size() + "artifacts identified.");
for (HashMap<String, Object> result : tempList) {
Collection<BlackboardAttribute> bbattributes = new ArrayList<BlackboardAttribute>();
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL.getTypeID(), "Recent Activity", ((result.get("url").toString() != null) ? result.get("url").toString() : "")));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL_DECODED.getTypeID(), "Recent Activity", ((result.get("url").toString() != null) ? EscapeUtil.decodeURL(result.get("url").toString()) : "")));
//TODO Revisit usage of deprecated constructor per TSK-583
//bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_LAST_ACCESSED.getTypeID(), "Recent Activity", "Last Visited", ((Long.valueOf(result.get("last_visit_time").toString())) / 10000000)));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DATETIME_ACCESSED.getTypeID(), "Recent Activity", ((Long.valueOf(result.get("last_visit_time").toString())) / 10000000)));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_REFERRER.getTypeID(), "Recent Activity", ((result.get("from_visit").toString() != null) ? result.get("from_visit").toString() : "")));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_NAME.getTypeID(), "Recent Activity", ((result.get("title").toString() != null) ? result.get("title").toString() : "")));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID(), "Recent Activity", "Chrome"));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DOMAIN.getTypeID(), "Recent Activity", (Util.extractDomain((result.get("url").toString() != null) ? result.get("url").toString() : ""))));
this.addArtifact(ARTIFACT_TYPE.TSK_WEB_HISTORY, historyFile, bbattributes);
}
if (errors > 0) {
this.addErrorMessage(this.getName() + ": Error parsing " + errors + " Chrome web history artifacts.");
}
dbFile.delete();
}
services.fireModuleDataEvent(new ModuleDataEvent("Recent Activity", BlackboardArtifact.ARTIFACT_TYPE.TSK_WEB_HISTORY));
}
private void getBookmark(Image image, IngestImageWorkerController controller) {
FileManager fileManager = currentCase.getServices().getFileManager();
List<FsContent> bookmarkFiles = null;
try {
bookmarkFiles = fileManager.findFiles(image, "Bookmarks", "Chrome");
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Error when trying to get Chrome history files.", ex);
}
int j = 0;
if (bookmarkFiles != null && !bookmarkFiles.isEmpty()) {
while (j < bookmarkFiles.size()) {
FsContent bookmarkFile = bookmarkFiles.get(j++);
String temps = currentCase.getTempDirectory() + File.separator + bookmarkFile.getName().toString() + j + ".db";
int errors = 0;
try {
ContentUtils.writeToFile(bookmarkFile, new File(temps));
} catch (IOException ex) {
logger.log(Level.SEVERE, "Error writing temp sqlite db for Chrome bookmark artifacts.{0}", ex);
this.addErrorMessage(this.getName() + ": Error while trying to analyze file:" + bookmarkFile.getName());
}
logger.log(Level.INFO, moduleName + "- Now getting Bookmarks from " + temps);
File dbFile = new File(temps);
if (controller.isCancelled()) {
dbFile.delete();
break;
}
try {
final JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(new FileReader(temps));
JsonObject jElement = jsonElement.getAsJsonObject();
JsonObject jRoot = jElement.get("roots").getAsJsonObject();
JsonObject jBookmark = jRoot.get("bookmark_bar").getAsJsonObject();
JsonArray jBookmarkArray = jBookmark.getAsJsonArray("children");
for (JsonElement result : jBookmarkArray) {
try {
JsonObject address = result.getAsJsonObject();
if (address == null) {
continue;
}
JsonElement urlEl = address.get("url");
String url = null;
if (urlEl != null) {
url = urlEl.getAsString();
}
else {
url = "";
}
String name = null;
JsonElement nameEl = address.get("name");
if (nameEl != null) {
name = nameEl.getAsString();
}
else {
name = "";
}
Long date = null;
JsonElement dateEl = address.get("date_added");
if (dateEl != null) {
date = dateEl.getAsLong();
}
else {
date = Long.valueOf(0);
}
String domain = Util.extractDomain(url);
BlackboardArtifact bbart = bookmarkFile.newArtifact(ARTIFACT_TYPE.TSK_WEB_BOOKMARK);
Collection<BlackboardAttribute> bbattributes = new ArrayList<BlackboardAttribute>();
//TODO Revisit usage of deprecated constructor as per TSK-583
//bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_LAST_ACCESSED.getTypeID(), "Recent Activity", "Last Visited", (date / 10000000)));
- bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DATETIME_ACCESSED.getTypeID(), "Last Visited", (date / 10000000)));
+ bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DATETIME_ACCESSED.getTypeID(), "Recent Activity", (date / 10000000)));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL.getTypeID(), "Recent Activity", url));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL_DECODED.getTypeID(), "Recent Activity", EscapeUtil.decodeURL(url)));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_NAME.getTypeID(), "Recent Activity", name));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID(), "Recent Activity", "Chrome"));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DOMAIN.getTypeID(), "Recent Activity", domain));
bbart.addAttributes(bbattributes);
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Error while trying to insert Chrom bookmark artifact{0}", ex);
errors++;
}
}
if (errors > 0) {
this.addErrorMessage(this.getName() + ": Error parsing " + errors + " Chrome bookmark artifacts.");
}
} catch (FileNotFoundException ex) {
logger.log(Level.SEVERE, "Error while trying to read into the Bookmarks for Chrome." + ex);
}
dbFile.delete();
}
services.fireModuleDataEvent(new ModuleDataEvent("Recent Activity", BlackboardArtifact.ARTIFACT_TYPE.TSK_WEB_BOOKMARK));
}
}
//COOKIES section
// This gets the cookie info
private void getCookie(Image image, IngestImageWorkerController controller) {
FileManager fileManager = currentCase.getServices().getFileManager();
List<FsContent> cookiesFiles = null;
try {
cookiesFiles = fileManager.findFiles(image, "Cookies", "Chrome");
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Error when trying to get Chrome history files.", ex);
}
int j = 0;
if (cookiesFiles != null && !cookiesFiles.isEmpty()) {
while (j < cookiesFiles.size()) {
FsContent cookiesFile = cookiesFiles.get(j++);
String temps = currentCase.getTempDirectory() + File.separator + cookiesFile.getName().toString() + j + ".db";
int errors = 0;
try {
ContentUtils.writeToFile(cookiesFile, new File(temps));
} catch (IOException ex) {
logger.log(Level.SEVERE, "Error writing temp sqlite db for Chrome cookie artifacts.{0}", ex);
this.addErrorMessage(this.getName() + ": Error while trying to analyze file:" + cookiesFile.getName());
}
File dbFile = new File(temps);
if (controller.isCancelled()) {
dbFile.delete();
break;
}
List<HashMap<String, Object>> tempList = this.dbConnect(temps, chcookiequery);
logger.log(Level.INFO, moduleName + "- Now getting cookies from " + temps + " with " + tempList.size() + "artifacts identified.");
for (HashMap<String, Object> result : tempList) {
Collection<BlackboardAttribute> bbattributes = new ArrayList<BlackboardAttribute>();
//TODO Revisit usage of deprecated constructor as per TSK-583
//bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_NAME.getTypeID(), "Recent Activity", "Title", ((result.get("name").toString() != null) ? result.get("name").toString() : "")));
//bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID(), "Recent Activity", "Last Visited", ((Long.valueOf(result.get("last_access_utc").toString())) / 10000000)));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_NAME.getTypeID(), "Recent Activity", ((result.get("name").toString() != null) ? result.get("name").toString() : "")));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID(), "Recent Activity", ((Long.valueOf(result.get("last_access_utc").toString())) / 10000000)));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_VALUE.getTypeID(), "Recent Activity", ((result.get("value").toString() != null) ? result.get("value").toString() : "")));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID(), "Recent Activity", "Chrome"));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL.getTypeID(), "Recent Activity", ((result.get("host_key").toString() != null) ? result.get("host_key").toString() : "")));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL_DECODED.getTypeID(), "Recent Activity", ((result.get("host_key").toString() != null) ? EscapeUtil.decodeURL(result.get("host_key").toString()) : "")));
String domain = result.get("host_key").toString();
domain = domain.replaceFirst("^\\.+(?!$)", "");
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DOMAIN.getTypeID(), "Recent Activity", domain));
this.addArtifact(ARTIFACT_TYPE.TSK_WEB_COOKIE, cookiesFile, bbattributes);
}
if (errors > 0) {
this.addErrorMessage(this.getName() + ": Error parsing " + errors + " Chrome cookie artifacts.");
}
dbFile.delete();
}
services.fireModuleDataEvent(new ModuleDataEvent("Recent Activity", BlackboardArtifact.ARTIFACT_TYPE.TSK_WEB_COOKIE));
}
}
//Downloads section
// This gets the downloads info
private void getDownload(Image image, IngestImageWorkerController controller) {
FileManager fileManager = currentCase.getServices().getFileManager();
List<FsContent> historyFiles = null;
try {
historyFiles = fileManager.findFiles(image, "History", "Chrome");
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Error when trying to get Chrome history files.", ex);
}
int j = 0;
if (historyFiles != null && !historyFiles.isEmpty()) {
while (j < historyFiles.size()) {
FsContent historyFile = historyFiles.get(j++);
if (historyFile.getSize() == 0) {
continue;
}
String temps = currentCase.getTempDirectory() + File.separator + historyFile.getName().toString() + j + ".db";
int errors = 0;
try {
ContentUtils.writeToFile(historyFile, new File(temps));
} catch (IOException ex) {
logger.log(Level.SEVERE, "Error writing temp sqlite db for Chrome download artifacts.{0}", ex);
this.addErrorMessage(this.getName() + ": Error while trying to analyze file:" + historyFile.getName());
}
File dbFile = new File(temps);
if (controller.isCancelled()) {
dbFile.delete();
break;
}
List<HashMap<String, Object>> tempList = this.dbConnect(temps, chdownloadquery);
logger.log(Level.INFO, moduleName + "- Now getting downloads from " + temps + " with " + tempList.size() + "artifacts identified.");
for (HashMap<String, Object> result : tempList) {
Collection<BlackboardAttribute> bbattributes = new ArrayList<BlackboardAttribute>();
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_PATH.getTypeID(), "Recent Activity", (result.get("full_path").toString())));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_PATH_ID.getTypeID(), "Recent Activity", Util.findID(image, (result.get("full_path").toString()))));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL.getTypeID(), "Recent Activity", ((result.get("url").toString() != null) ? result.get("url").toString() : "")));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL_DECODED.getTypeID(), "Recent Activity", ((result.get("url").toString() != null) ? EscapeUtil.decodeURL(result.get("url").toString()) : "")));
Long time = (Long.valueOf(result.get("start_time").toString()));
String Tempdate = time.toString();
time = Long.valueOf(Tempdate) / 10000000;
//TODO Revisit usage of deprecated constructor as per TSK-583
//bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_LAST_ACCESSED.getTypeID(), "Recent Activity", "Last Visited", time));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DATETIME_ACCESSED.getTypeID(), "Recent Activity", time));
String domain = Util.extractDomain((result.get("url").toString() != null) ? result.get("url").toString() : "");
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DOMAIN.getTypeID(), "Recent Activity", domain));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID(), "Recent Activity", "Chrome"));
this.addArtifact(ARTIFACT_TYPE.TSK_WEB_DOWNLOAD, historyFile, bbattributes);
}
if (errors > 0) {
this.addErrorMessage(this.getName() + ": Error parsing " + errors + " Chrome download artifacts.");
}
dbFile.delete();
}
services.fireModuleDataEvent(new ModuleDataEvent("Recent Activity", BlackboardArtifact.ARTIFACT_TYPE.TSK_WEB_DOWNLOAD));
}
}
//Login/Password section
// This gets the user info
private void getLogin(Image image, IngestImageWorkerController controller) {
FileManager fileManager = currentCase.getServices().getFileManager();
List<FsContent> signonFiles = null;
try {
signonFiles = fileManager.findFiles(image, "signons.sqlite", "Chrome");
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Error when trying to get Chrome history files.", ex);
}
int j = 0;
if (signonFiles != null && !signonFiles.isEmpty()) {
while (j < signonFiles.size()) {
FsContent signonFile = signonFiles.get(j++);
String temps = currentCase.getTempDirectory() + File.separator + signonFile.getName().toString() + j + ".db";
int errors = 0;
try {
ContentUtils.writeToFile(signonFile, new File(temps));
} catch (IOException ex) {
logger.log(Level.SEVERE, "Error writing temp sqlite db for Chrome login artifacts.{0}", ex);
this.addErrorMessage(this.getName() + ": Error while trying to analyze file:" + signonFile.getName());
}
File dbFile = new File(temps);
if (controller.isCancelled()) {
dbFile.delete();
break;
}
List<HashMap<String, Object>> tempList = this.dbConnect(temps, chloginquery);
logger.log(Level.INFO, moduleName + "- Now getting login information from " + temps + " with " + tempList.size() + "artifacts identified.");
for (HashMap<String, Object> result : tempList) {
Collection<BlackboardAttribute> bbattributes = new ArrayList<BlackboardAttribute>();
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL.getTypeID(), "Recent Activity", ((result.get("origin_url").toString() != null) ? result.get("origin_url").toString() : "")));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL_DECODED.getTypeID(), "Recent Activity", ((result.get("origin_url").toString() != null) ? EscapeUtil.decodeURL(result.get("origin_url").toString()) : "")));
//TODO Revisit usage of deprecated constructor as per TSK-583
//bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DATETIME_ACCESSED.getTypeID(), "Recent Activity", "Last Visited", ((Long.valueOf(result.get("last_visit_time").toString())) / 1000000)));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DATETIME_ACCESSED.getTypeID(), "Recent Activity", ((Long.valueOf(result.get("last_visit_time").toString())) / 1000000)));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_REFERRER.getTypeID(), "Recent Activity", ((result.get("from_visit").toString() != null) ? result.get("from_visit").toString() : "")));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_NAME.getTypeID(), "Recent Activity", ((result.get("title").toString() != null) ? result.get("title").toString() : "")));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID(), "Recent Activity", "Chrome"));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DOMAIN.getTypeID(), "Recent Activity", (Util.extractDomain((result.get("origin_url").toString() != null) ? result.get("url").toString() : ""))));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_USER_NAME.getTypeID(), "Recent Activity", ((result.get("username_value").toString() != null) ? result.get("username_value").toString().replaceAll("'", "''") : "")));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DOMAIN.getTypeID(), "Recent Activity", result.get("signon_realm").toString()));
this.addArtifact(ARTIFACT_TYPE.TSK_WEB_HISTORY, signonFile, bbattributes);
}
if (errors > 0) {
this.addErrorMessage(this.getName() + ": Error parsing " + errors + " Chrome login artifacts.");
}
dbFile.delete();
}
services.fireModuleDataEvent(new ModuleDataEvent("Recent Activity", BlackboardArtifact.ARTIFACT_TYPE.TSK_WEB_HISTORY));
}
}
@Override
public void init(IngestModuleInit initContext) {
services = IngestServices.getDefault();
}
@Override
public void complete() {
logger.info("Chrome Extract has completed");
}
@Override
public void stop() {
logger.info("Attmped to stop chrome extract, but operation is not supported; skipping...");
}
@Override
public String getDescription() {
return "Extracts activity from the Google Chrome browser.";
}
@Override
public ModuleType getType() {
return ModuleType.Image;
}
@Override
public boolean hasSimpleConfiguration() {
return false;
}
@Override
public boolean hasAdvancedConfiguration() {
return false;
}
@Override
public javax.swing.JPanel getSimpleConfiguration() {
return null;
}
@Override
public javax.swing.JPanel getAdvancedConfiguration() {
return null;
}
@Override
public void saveAdvancedConfiguration() {
}
@Override
public void saveSimpleConfiguration() {
}
@Override
public boolean hasBackgroundJobsRunning() {
return false;
}
}
| true | true | private void getBookmark(Image image, IngestImageWorkerController controller) {
FileManager fileManager = currentCase.getServices().getFileManager();
List<FsContent> bookmarkFiles = null;
try {
bookmarkFiles = fileManager.findFiles(image, "Bookmarks", "Chrome");
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Error when trying to get Chrome history files.", ex);
}
int j = 0;
if (bookmarkFiles != null && !bookmarkFiles.isEmpty()) {
while (j < bookmarkFiles.size()) {
FsContent bookmarkFile = bookmarkFiles.get(j++);
String temps = currentCase.getTempDirectory() + File.separator + bookmarkFile.getName().toString() + j + ".db";
int errors = 0;
try {
ContentUtils.writeToFile(bookmarkFile, new File(temps));
} catch (IOException ex) {
logger.log(Level.SEVERE, "Error writing temp sqlite db for Chrome bookmark artifacts.{0}", ex);
this.addErrorMessage(this.getName() + ": Error while trying to analyze file:" + bookmarkFile.getName());
}
logger.log(Level.INFO, moduleName + "- Now getting Bookmarks from " + temps);
File dbFile = new File(temps);
if (controller.isCancelled()) {
dbFile.delete();
break;
}
try {
final JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(new FileReader(temps));
JsonObject jElement = jsonElement.getAsJsonObject();
JsonObject jRoot = jElement.get("roots").getAsJsonObject();
JsonObject jBookmark = jRoot.get("bookmark_bar").getAsJsonObject();
JsonArray jBookmarkArray = jBookmark.getAsJsonArray("children");
for (JsonElement result : jBookmarkArray) {
try {
JsonObject address = result.getAsJsonObject();
if (address == null) {
continue;
}
JsonElement urlEl = address.get("url");
String url = null;
if (urlEl != null) {
url = urlEl.getAsString();
}
else {
url = "";
}
String name = null;
JsonElement nameEl = address.get("name");
if (nameEl != null) {
name = nameEl.getAsString();
}
else {
name = "";
}
Long date = null;
JsonElement dateEl = address.get("date_added");
if (dateEl != null) {
date = dateEl.getAsLong();
}
else {
date = Long.valueOf(0);
}
String domain = Util.extractDomain(url);
BlackboardArtifact bbart = bookmarkFile.newArtifact(ARTIFACT_TYPE.TSK_WEB_BOOKMARK);
Collection<BlackboardAttribute> bbattributes = new ArrayList<BlackboardAttribute>();
//TODO Revisit usage of deprecated constructor as per TSK-583
//bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_LAST_ACCESSED.getTypeID(), "Recent Activity", "Last Visited", (date / 10000000)));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DATETIME_ACCESSED.getTypeID(), "Last Visited", (date / 10000000)));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL.getTypeID(), "Recent Activity", url));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL_DECODED.getTypeID(), "Recent Activity", EscapeUtil.decodeURL(url)));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_NAME.getTypeID(), "Recent Activity", name));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID(), "Recent Activity", "Chrome"));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DOMAIN.getTypeID(), "Recent Activity", domain));
bbart.addAttributes(bbattributes);
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Error while trying to insert Chrom bookmark artifact{0}", ex);
errors++;
}
}
if (errors > 0) {
this.addErrorMessage(this.getName() + ": Error parsing " + errors + " Chrome bookmark artifacts.");
}
} catch (FileNotFoundException ex) {
logger.log(Level.SEVERE, "Error while trying to read into the Bookmarks for Chrome." + ex);
}
dbFile.delete();
}
services.fireModuleDataEvent(new ModuleDataEvent("Recent Activity", BlackboardArtifact.ARTIFACT_TYPE.TSK_WEB_BOOKMARK));
}
}
| private void getBookmark(Image image, IngestImageWorkerController controller) {
FileManager fileManager = currentCase.getServices().getFileManager();
List<FsContent> bookmarkFiles = null;
try {
bookmarkFiles = fileManager.findFiles(image, "Bookmarks", "Chrome");
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Error when trying to get Chrome history files.", ex);
}
int j = 0;
if (bookmarkFiles != null && !bookmarkFiles.isEmpty()) {
while (j < bookmarkFiles.size()) {
FsContent bookmarkFile = bookmarkFiles.get(j++);
String temps = currentCase.getTempDirectory() + File.separator + bookmarkFile.getName().toString() + j + ".db";
int errors = 0;
try {
ContentUtils.writeToFile(bookmarkFile, new File(temps));
} catch (IOException ex) {
logger.log(Level.SEVERE, "Error writing temp sqlite db for Chrome bookmark artifacts.{0}", ex);
this.addErrorMessage(this.getName() + ": Error while trying to analyze file:" + bookmarkFile.getName());
}
logger.log(Level.INFO, moduleName + "- Now getting Bookmarks from " + temps);
File dbFile = new File(temps);
if (controller.isCancelled()) {
dbFile.delete();
break;
}
try {
final JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(new FileReader(temps));
JsonObject jElement = jsonElement.getAsJsonObject();
JsonObject jRoot = jElement.get("roots").getAsJsonObject();
JsonObject jBookmark = jRoot.get("bookmark_bar").getAsJsonObject();
JsonArray jBookmarkArray = jBookmark.getAsJsonArray("children");
for (JsonElement result : jBookmarkArray) {
try {
JsonObject address = result.getAsJsonObject();
if (address == null) {
continue;
}
JsonElement urlEl = address.get("url");
String url = null;
if (urlEl != null) {
url = urlEl.getAsString();
}
else {
url = "";
}
String name = null;
JsonElement nameEl = address.get("name");
if (nameEl != null) {
name = nameEl.getAsString();
}
else {
name = "";
}
Long date = null;
JsonElement dateEl = address.get("date_added");
if (dateEl != null) {
date = dateEl.getAsLong();
}
else {
date = Long.valueOf(0);
}
String domain = Util.extractDomain(url);
BlackboardArtifact bbart = bookmarkFile.newArtifact(ARTIFACT_TYPE.TSK_WEB_BOOKMARK);
Collection<BlackboardAttribute> bbattributes = new ArrayList<BlackboardAttribute>();
//TODO Revisit usage of deprecated constructor as per TSK-583
//bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_LAST_ACCESSED.getTypeID(), "Recent Activity", "Last Visited", (date / 10000000)));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DATETIME_ACCESSED.getTypeID(), "Recent Activity", (date / 10000000)));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL.getTypeID(), "Recent Activity", url));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL_DECODED.getTypeID(), "Recent Activity", EscapeUtil.decodeURL(url)));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_NAME.getTypeID(), "Recent Activity", name));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID(), "Recent Activity", "Chrome"));
bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DOMAIN.getTypeID(), "Recent Activity", domain));
bbart.addAttributes(bbattributes);
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Error while trying to insert Chrom bookmark artifact{0}", ex);
errors++;
}
}
if (errors > 0) {
this.addErrorMessage(this.getName() + ": Error parsing " + errors + " Chrome bookmark artifacts.");
}
} catch (FileNotFoundException ex) {
logger.log(Level.SEVERE, "Error while trying to read into the Bookmarks for Chrome." + ex);
}
dbFile.delete();
}
services.fireModuleDataEvent(new ModuleDataEvent("Recent Activity", BlackboardArtifact.ARTIFACT_TYPE.TSK_WEB_BOOKMARK));
}
}
|
diff --git a/src/main/java/net/fluxo/updater/processor/KMLReader.java b/src/main/java/net/fluxo/updater/processor/KMLReader.java
index 1859046..8d1d6da 100644
--- a/src/main/java/net/fluxo/updater/processor/KMLReader.java
+++ b/src/main/java/net/fluxo/updater/processor/KMLReader.java
@@ -1,104 +1,104 @@
package net.fluxo.updater.processor;
import net.fluxo.updater.dbo.KMLSchema;
import net.fluxo.updater.dbo.KMLSchemaField;
import org.apache.log4j.Logger;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.XMLEvent;
import java.io.InputStream;
/**
* Created with IntelliJ IDEA.
* User: Ronald Kurniawan (viper)
* Date: 14/07/13
* Time: 12:51 PM
*/
public class KMLReader {
private XMLInputFactory _inputFactory;
private XMLEventReader _eventReader;
private Logger _logger = Logger.getLogger("net.fluxo");
public KMLReader(InputStream input) throws XMLStreamException {
_inputFactory = XMLInputFactory.newInstance();
_eventReader = _inputFactory.createXMLEventReader(input);
KMLSchema schema = readKMLSchema();
// DEBUG
if (schema != null) {
System.out.println("name: " + schema.getName());
System.out.println("parent: " + schema.getParent());
for (KMLSchemaField field : schema.getSchema()) {
System.out.println("field: " + field.getName() + "->" + field.getType());
}
}
}
public KMLSchema readKMLSchema() throws XMLStreamException {
boolean insideDocument = false;
boolean insideSchema = false;
boolean insideSimpleField = false;
KMLSchema kmlSchema = null;
String sfName = null;
String sfType = null;
while (_eventReader.hasNext()) {
XMLEvent xEvent = _eventReader.nextEvent();
if (xEvent.isStartElement()) {
String localPart = xEvent.asStartElement().getName().getLocalPart();
if (localPart.equalsIgnoreCase("Document")) {
insideDocument = true;
} else if (localPart.equalsIgnoreCase("Schema")) {
insideSchema = true;
kmlSchema = new KMLSchema();
} else if (localPart.equalsIgnoreCase("SimpleField")) {
insideSimpleField = true;
- } else if (localPart.equalsIgnoreCase("name") && insideDocument && insideSchema) {
+ } else if (localPart.equalsIgnoreCase("name") && insideDocument && insideSchema && !insideSimpleField) {
xEvent = _eventReader.nextEvent();
String data = (xEvent instanceof Characters ? xEvent.asCharacters().getData() : null);
if (data != null && kmlSchema != null) {
kmlSchema.setName(data);
}
} else if (localPart.equalsIgnoreCase("name") && insideDocument && insideSchema && insideSimpleField) {
xEvent = _eventReader.nextEvent();
String data = (xEvent instanceof Characters ? xEvent.asCharacters().getData() : null);
if (data != null && kmlSchema != null) {
sfName = data;
}
- } else if (localPart.equalsIgnoreCase("parent") && insideDocument && insideSchema) {
+ } else if (localPart.equalsIgnoreCase("parent") && insideDocument && insideSchema && !insideSimpleField) {
xEvent = _eventReader.nextEvent();
String data = (xEvent instanceof Characters ? xEvent.asCharacters().getData() : null);
if (data != null && kmlSchema != null) {
kmlSchema.setParent(data);
}
} else if (localPart.equalsIgnoreCase("type") && insideDocument && insideSchema && insideSimpleField) {
xEvent = _eventReader.nextEvent();
String data = (xEvent instanceof Characters ? xEvent.asCharacters().getData() : null);
if (data != null && kmlSchema != null) {
sfType = data;
}
}
} else if (xEvent.isEndElement()) {
String localPart = xEvent.asEndElement().getName().getLocalPart();
if (localPart.equalsIgnoreCase("Document")) {
insideDocument = false;
} else if (localPart.equalsIgnoreCase("Schema")) {
insideSchema = false;
break;
} else if (localPart.equalsIgnoreCase("SimpleField")) {
insideSimpleField = false;
if (sfName != null && sfType != null) {
KMLSchemaField field = new KMLSchemaField(sfName, sfType);
kmlSchema.addSchema(field);
sfName = sfType = null;
}
}
}
}
return kmlSchema;
}
}
| false | true | public KMLSchema readKMLSchema() throws XMLStreamException {
boolean insideDocument = false;
boolean insideSchema = false;
boolean insideSimpleField = false;
KMLSchema kmlSchema = null;
String sfName = null;
String sfType = null;
while (_eventReader.hasNext()) {
XMLEvent xEvent = _eventReader.nextEvent();
if (xEvent.isStartElement()) {
String localPart = xEvent.asStartElement().getName().getLocalPart();
if (localPart.equalsIgnoreCase("Document")) {
insideDocument = true;
} else if (localPart.equalsIgnoreCase("Schema")) {
insideSchema = true;
kmlSchema = new KMLSchema();
} else if (localPart.equalsIgnoreCase("SimpleField")) {
insideSimpleField = true;
} else if (localPart.equalsIgnoreCase("name") && insideDocument && insideSchema) {
xEvent = _eventReader.nextEvent();
String data = (xEvent instanceof Characters ? xEvent.asCharacters().getData() : null);
if (data != null && kmlSchema != null) {
kmlSchema.setName(data);
}
} else if (localPart.equalsIgnoreCase("name") && insideDocument && insideSchema && insideSimpleField) {
xEvent = _eventReader.nextEvent();
String data = (xEvent instanceof Characters ? xEvent.asCharacters().getData() : null);
if (data != null && kmlSchema != null) {
sfName = data;
}
} else if (localPart.equalsIgnoreCase("parent") && insideDocument && insideSchema) {
xEvent = _eventReader.nextEvent();
String data = (xEvent instanceof Characters ? xEvent.asCharacters().getData() : null);
if (data != null && kmlSchema != null) {
kmlSchema.setParent(data);
}
} else if (localPart.equalsIgnoreCase("type") && insideDocument && insideSchema && insideSimpleField) {
xEvent = _eventReader.nextEvent();
String data = (xEvent instanceof Characters ? xEvent.asCharacters().getData() : null);
if (data != null && kmlSchema != null) {
sfType = data;
}
}
} else if (xEvent.isEndElement()) {
String localPart = xEvent.asEndElement().getName().getLocalPart();
if (localPart.equalsIgnoreCase("Document")) {
insideDocument = false;
} else if (localPart.equalsIgnoreCase("Schema")) {
insideSchema = false;
break;
} else if (localPart.equalsIgnoreCase("SimpleField")) {
insideSimpleField = false;
if (sfName != null && sfType != null) {
KMLSchemaField field = new KMLSchemaField(sfName, sfType);
kmlSchema.addSchema(field);
sfName = sfType = null;
}
}
}
}
return kmlSchema;
}
| public KMLSchema readKMLSchema() throws XMLStreamException {
boolean insideDocument = false;
boolean insideSchema = false;
boolean insideSimpleField = false;
KMLSchema kmlSchema = null;
String sfName = null;
String sfType = null;
while (_eventReader.hasNext()) {
XMLEvent xEvent = _eventReader.nextEvent();
if (xEvent.isStartElement()) {
String localPart = xEvent.asStartElement().getName().getLocalPart();
if (localPart.equalsIgnoreCase("Document")) {
insideDocument = true;
} else if (localPart.equalsIgnoreCase("Schema")) {
insideSchema = true;
kmlSchema = new KMLSchema();
} else if (localPart.equalsIgnoreCase("SimpleField")) {
insideSimpleField = true;
} else if (localPart.equalsIgnoreCase("name") && insideDocument && insideSchema && !insideSimpleField) {
xEvent = _eventReader.nextEvent();
String data = (xEvent instanceof Characters ? xEvent.asCharacters().getData() : null);
if (data != null && kmlSchema != null) {
kmlSchema.setName(data);
}
} else if (localPart.equalsIgnoreCase("name") && insideDocument && insideSchema && insideSimpleField) {
xEvent = _eventReader.nextEvent();
String data = (xEvent instanceof Characters ? xEvent.asCharacters().getData() : null);
if (data != null && kmlSchema != null) {
sfName = data;
}
} else if (localPart.equalsIgnoreCase("parent") && insideDocument && insideSchema && !insideSimpleField) {
xEvent = _eventReader.nextEvent();
String data = (xEvent instanceof Characters ? xEvent.asCharacters().getData() : null);
if (data != null && kmlSchema != null) {
kmlSchema.setParent(data);
}
} else if (localPart.equalsIgnoreCase("type") && insideDocument && insideSchema && insideSimpleField) {
xEvent = _eventReader.nextEvent();
String data = (xEvent instanceof Characters ? xEvent.asCharacters().getData() : null);
if (data != null && kmlSchema != null) {
sfType = data;
}
}
} else if (xEvent.isEndElement()) {
String localPart = xEvent.asEndElement().getName().getLocalPart();
if (localPart.equalsIgnoreCase("Document")) {
insideDocument = false;
} else if (localPart.equalsIgnoreCase("Schema")) {
insideSchema = false;
break;
} else if (localPart.equalsIgnoreCase("SimpleField")) {
insideSimpleField = false;
if (sfName != null && sfType != null) {
KMLSchemaField field = new KMLSchemaField(sfName, sfType);
kmlSchema.addSchema(field);
sfName = sfType = null;
}
}
}
}
return kmlSchema;
}
|
diff --git a/tour/product/db/src/main/java/com/tourapp/tour/product/base/db/StatusDescConverter.java b/tour/product/db/src/main/java/com/tourapp/tour/product/base/db/StatusDescConverter.java
index 01609e03..f1d457fb 100644
--- a/tour/product/db/src/main/java/com/tourapp/tour/product/base/db/StatusDescConverter.java
+++ b/tour/product/db/src/main/java/com/tourapp/tour/product/base/db/StatusDescConverter.java
@@ -1,113 +1,113 @@
/**
* @(#)StatusDescConverter.
* Copyright © 2012 tourapp.com. All rights reserved.
* GPL3 Open Source Software License.
*/
package com.tourapp.tour.product.base.db;
import java.util.*;
import org.jbundle.base.db.*;
import org.jbundle.thin.base.util.*;
import org.jbundle.thin.base.db.*;
import org.jbundle.base.db.event.*;
import org.jbundle.base.db.filter.*;
import org.jbundle.base.field.*;
import org.jbundle.base.field.convert.*;
import org.jbundle.base.field.event.*;
import org.jbundle.base.model.*;
import org.jbundle.base.util.*;
import org.jbundle.model.*;
import org.jbundle.model.db.*;
import org.jbundle.model.screen.*;
import org.jbundle.base.screen.model.util.*;
import com.tourapp.thin.app.booking.entry.*;
import org.jbundle.base.screen.model.*;
import com.tourapp.model.tour.booking.detail.db.*;
/**
* StatusDescConverter - .
*/
public class StatusDescConverter extends DescConverter
{
/**
* Default constructor.
*/
public StatusDescConverter()
{
super();
}
/**
* Constructor.
*/
public StatusDescConverter(Converter converter)
{
this();
this.init(converter);
}
/**
* Initialize class fields.
*/
public void init(BaseField field)
{
super.init(field);
}
/**
* GetMaxLength Method.
*/
public int getMaxLength()
{
return 30;
}
/**
* GetProductType Method.
*/
public String getProductType()
{
BookingDetailModel recCustSaleDetail = (BookingDetailModel)((BaseField)this.getField()).getRecord();
String strProductType = recCustSaleDetail.getField(BookingDetailModel.PRODUCT_TYPE).toString();
if ((strProductType == null) || (strProductType.length() == 0))
strProductType = ProductType.ITEM;
return strProductType;
}
/**
* GetString Method.
*/
public String getString()
{
ResourceBundle resources = null;
if ((((BaseField)this.getField()).getRecord().getRecordOwner()) != null)
- if ((((BaseField)this.getField()).getRecord().getRecordOwner().getTask()) != null)
- if ((((BaseField)this.getField()).getRecord().getRecordOwner().getTask().getApplication()) != null)
- resources = ((BaseApplication)((BaseField)this.getField()).getRecord().getRecordOwner().getTask().getApplication()).getResources(ResourceConstants.BOOKING_RESOURCE, true);
+ if ((((BaseField)this.getField()).getRecord().getRecordOwner().getTask()) != null)
+ if ((((BaseField)this.getField()).getRecord().getRecordOwner().getTask().getApplication()) != null)
+ resources = ((BaseApplication)((BaseField)this.getField()).getRecord().getRecordOwner().getTask().getApplication()).getResources(ResourceConstants.BOOKING_RESOURCE, true);
String strProductType = this.getProductType();
if (resources != null)
- strProductType = resources.getString(this.getProductType());
+ strProductType = resources.getString(this.getProductType());
int iStatus = (int)this.getValue();
boolean bNormalStatus = true;
if ((iStatus & (1 << BookingConstants.INFO_LOOKUP)) != 0)
{
strProductType += ' ' + resources.getString(BookingConstants.INFO);
bNormalStatus = false;
}
if ((iStatus & (1 << BookingConstants.COST_LOOKUP)) != 0)
{
strProductType += ' ' + resources.getString(BookingConstants.COST);
bNormalStatus = false;
}
if ((iStatus & (1 << BookingConstants.INVENTORY_LOOKUP)) != 0)
{
strProductType += ' ' + resources.getString(BookingConstants.INVENTORY);
bNormalStatus = false;
}
if ((iStatus & (1 << BookingConstants.PRODUCT_LOOKUP)) != 0)
{
strProductType += ' ' + resources.getString(BookingConstants.PRODUCT);
bNormalStatus = false;
}
if (!bNormalStatus)
strProductType += ' ' + resources.getString("Pending");
return strProductType;
}
}
| false | true | public String getString()
{
ResourceBundle resources = null;
if ((((BaseField)this.getField()).getRecord().getRecordOwner()) != null)
if ((((BaseField)this.getField()).getRecord().getRecordOwner().getTask()) != null)
if ((((BaseField)this.getField()).getRecord().getRecordOwner().getTask().getApplication()) != null)
resources = ((BaseApplication)((BaseField)this.getField()).getRecord().getRecordOwner().getTask().getApplication()).getResources(ResourceConstants.BOOKING_RESOURCE, true);
String strProductType = this.getProductType();
if (resources != null)
strProductType = resources.getString(this.getProductType());
int iStatus = (int)this.getValue();
boolean bNormalStatus = true;
if ((iStatus & (1 << BookingConstants.INFO_LOOKUP)) != 0)
{
strProductType += ' ' + resources.getString(BookingConstants.INFO);
bNormalStatus = false;
}
if ((iStatus & (1 << BookingConstants.COST_LOOKUP)) != 0)
{
strProductType += ' ' + resources.getString(BookingConstants.COST);
bNormalStatus = false;
}
if ((iStatus & (1 << BookingConstants.INVENTORY_LOOKUP)) != 0)
{
strProductType += ' ' + resources.getString(BookingConstants.INVENTORY);
bNormalStatus = false;
}
if ((iStatus & (1 << BookingConstants.PRODUCT_LOOKUP)) != 0)
{
strProductType += ' ' + resources.getString(BookingConstants.PRODUCT);
bNormalStatus = false;
}
if (!bNormalStatus)
strProductType += ' ' + resources.getString("Pending");
return strProductType;
}
| public String getString()
{
ResourceBundle resources = null;
if ((((BaseField)this.getField()).getRecord().getRecordOwner()) != null)
if ((((BaseField)this.getField()).getRecord().getRecordOwner().getTask()) != null)
if ((((BaseField)this.getField()).getRecord().getRecordOwner().getTask().getApplication()) != null)
resources = ((BaseApplication)((BaseField)this.getField()).getRecord().getRecordOwner().getTask().getApplication()).getResources(ResourceConstants.BOOKING_RESOURCE, true);
String strProductType = this.getProductType();
if (resources != null)
strProductType = resources.getString(this.getProductType());
int iStatus = (int)this.getValue();
boolean bNormalStatus = true;
if ((iStatus & (1 << BookingConstants.INFO_LOOKUP)) != 0)
{
strProductType += ' ' + resources.getString(BookingConstants.INFO);
bNormalStatus = false;
}
if ((iStatus & (1 << BookingConstants.COST_LOOKUP)) != 0)
{
strProductType += ' ' + resources.getString(BookingConstants.COST);
bNormalStatus = false;
}
if ((iStatus & (1 << BookingConstants.INVENTORY_LOOKUP)) != 0)
{
strProductType += ' ' + resources.getString(BookingConstants.INVENTORY);
bNormalStatus = false;
}
if ((iStatus & (1 << BookingConstants.PRODUCT_LOOKUP)) != 0)
{
strProductType += ' ' + resources.getString(BookingConstants.PRODUCT);
bNormalStatus = false;
}
if (!bNormalStatus)
strProductType += ' ' + resources.getString("Pending");
return strProductType;
}
|
diff --git a/core/src/test/java/org/apache/commons/vfs2/provider/url/test/UrlProviderHttpTestCase.java b/core/src/test/java/org/apache/commons/vfs2/provider/url/test/UrlProviderHttpTestCase.java
index 28e14785..537bbce2 100644
--- a/core/src/test/java/org/apache/commons/vfs2/provider/url/test/UrlProviderHttpTestCase.java
+++ b/core/src/test/java/org/apache/commons/vfs2/provider/url/test/UrlProviderHttpTestCase.java
@@ -1,70 +1,70 @@
/*
* 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.commons.vfs2.provider.url.test;
import junit.framework.Test;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
import org.apache.commons.vfs2.provider.url.UrlFileProvider;
import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
import org.apache.commons.vfs2.test.ProviderTestSuite;
/**
* Test cases for HTTP with the default provider.
*
* @author <a href="mailto:[email protected]">Adam Murdoch</a>
*/
public class UrlProviderHttpTestCase
extends AbstractProviderTestConfig
{
private static final String TEST_URI = "test.http.uri";
public static Test suite() throws Exception
{
if (System.getProperty(TEST_URI) != null)
{
return new ProviderTestSuite(new UrlProviderTestCase());
}
else
{
- return notConfigured(UrlProviderTestCase.class);
+ return notConfigured(UrlProviderHttpTestCase.class);
}
}
/**
* Prepares the file system manager.
*/
@Override
public void prepare(final DefaultFileSystemManager manager)
throws Exception
{
manager.addProvider("http", new UrlFileProvider());
}
/**
* Returns the base folder for tests.
*/
@Override
public FileObject getBaseTestFolder(final FileSystemManager manager)
throws Exception
{
final String uri = System.getProperty(TEST_URI);
return manager.resolveFile(uri);
}
}
| true | true | public static Test suite() throws Exception
{
if (System.getProperty(TEST_URI) != null)
{
return new ProviderTestSuite(new UrlProviderTestCase());
}
else
{
return notConfigured(UrlProviderTestCase.class);
}
}
| public static Test suite() throws Exception
{
if (System.getProperty(TEST_URI) != null)
{
return new ProviderTestSuite(new UrlProviderTestCase());
}
else
{
return notConfigured(UrlProviderHttpTestCase.class);
}
}
|
diff --git a/apache-rat-core/src/test/java/org/apache/rat/ReportTest.java b/apache-rat-core/src/test/java/org/apache/rat/ReportTest.java
index 4aff29f4..e2c66230 100644
--- a/apache-rat-core/src/test/java/org/apache/rat/ReportTest.java
+++ b/apache-rat-core/src/test/java/org/apache/rat/ReportTest.java
@@ -1,120 +1,120 @@
/*
* 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.rat;
import java.io.File;
import java.io.StringWriter;
import junit.framework.TestCase;
import org.apache.rat.analysis.util.HeaderMatcherMultiplexer;
import org.apache.rat.test.utils.Resources;
public class ReportTest extends TestCase {
private static String getElementsReports(String pElementsPath) {
return
"\n" +
"*****************************************************\n" +
"Summary\n" +
"-------\n" +
"Notes: 2\n" +
"Binaries: 1\n" +
"Archives: 1\n" +
"Standards: 4\n" +
"\n" +
"Apache Licensed: 2\n" +
"Generated Documents: 0\n" +
"\n" +
"JavaDocs are generated and so license header is optional\n" +
"Generated files do not required license headers\n" +
"\n" +
"2 Unknown Licenses\n" +
"\n" +
"*******************************\n" +
"\n" +
"Unapproved licenses:\n" +
"\n" +
" " + pElementsPath + "/Source.java\n" +
" " + pElementsPath + "/sub/Empty.txt\n" +
"\n" +
"*******************************\n" +
"\n" +
- "Archives (+ indicates readable, $ unreadable): \n" +
+ "Archives:\n" +
"\n" +
" + " + pElementsPath + "/dummy.jar\n" +
" \n" +
"*****************************************************\n" +
" Files with Apache License headers will be marked AL\n" +
" Binary files (which do not require AL headers) will be marked B\n" +
" Compressed archives will be marked A\n" +
" Notices, licenses etc will be marked N\n" +
" B " + pElementsPath + "/Image.png\n" +
" N " + pElementsPath + "/LICENSE\n" +
" N " + pElementsPath + "/NOTICE\n" +
" !????? " + pElementsPath + "/Source.java\n" +
" AL " + pElementsPath + "/Text.txt\n" +
" AL " + pElementsPath + "/Xml.xml\n" +
" A " + pElementsPath + "/dummy.jar\n" +
" !????? " + pElementsPath + "/sub/Empty.txt\n" +
" \n" +
" *****************************************************\n" +
" Printing headers for files without AL header...\n" +
" \n" +
" \n" +
" =======================================================================\n" +
" ==" + pElementsPath + "/Source.java\n" +
" =======================================================================\n" +
"package elements;\n" +
"\n" +
"/*\n" +
" * This file does intentionally *NOT* contain an ASL license header,\n" +
" * because it is used in the test suite.\n" +
" */\n" +
"public class Source {\n" +
"\n" +
"}\n" +
"\n" +
" =======================================================================\n" +
" ==" + pElementsPath + "/sub/Empty.txt\n" +
" =======================================================================\n" +
"\n";
}
protected void setUp() throws Exception {
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
}
public void testPlainReport() throws Exception {
StringWriter out = new StringWriter();
HeaderMatcherMultiplexer matcherMultiplexer = new HeaderMatcherMultiplexer(Defaults.DEFAULT_MATCHERS);
final String elementsPath = Resources.getResourceDirectory("elements/Source.java");
Report.report(out, new DirectoryWalker(new File(elementsPath)),
Defaults.getPlainStyleSheet(), matcherMultiplexer, null);
String result = out.getBuffer().toString();
final String elementsReports = getElementsReports(elementsPath);
assertEquals("Report created",
elementsReports.replaceAll("\n",
System.getProperty("line.separator")),
result);
}
}
| true | true | private static String getElementsReports(String pElementsPath) {
return
"\n" +
"*****************************************************\n" +
"Summary\n" +
"-------\n" +
"Notes: 2\n" +
"Binaries: 1\n" +
"Archives: 1\n" +
"Standards: 4\n" +
"\n" +
"Apache Licensed: 2\n" +
"Generated Documents: 0\n" +
"\n" +
"JavaDocs are generated and so license header is optional\n" +
"Generated files do not required license headers\n" +
"\n" +
"2 Unknown Licenses\n" +
"\n" +
"*******************************\n" +
"\n" +
"Unapproved licenses:\n" +
"\n" +
" " + pElementsPath + "/Source.java\n" +
" " + pElementsPath + "/sub/Empty.txt\n" +
"\n" +
"*******************************\n" +
"\n" +
"Archives (+ indicates readable, $ unreadable): \n" +
"\n" +
" + " + pElementsPath + "/dummy.jar\n" +
" \n" +
"*****************************************************\n" +
" Files with Apache License headers will be marked AL\n" +
" Binary files (which do not require AL headers) will be marked B\n" +
" Compressed archives will be marked A\n" +
" Notices, licenses etc will be marked N\n" +
" B " + pElementsPath + "/Image.png\n" +
" N " + pElementsPath + "/LICENSE\n" +
" N " + pElementsPath + "/NOTICE\n" +
" !????? " + pElementsPath + "/Source.java\n" +
" AL " + pElementsPath + "/Text.txt\n" +
" AL " + pElementsPath + "/Xml.xml\n" +
" A " + pElementsPath + "/dummy.jar\n" +
" !????? " + pElementsPath + "/sub/Empty.txt\n" +
" \n" +
" *****************************************************\n" +
" Printing headers for files without AL header...\n" +
" \n" +
" \n" +
" =======================================================================\n" +
" ==" + pElementsPath + "/Source.java\n" +
" =======================================================================\n" +
"package elements;\n" +
"\n" +
"/*\n" +
" * This file does intentionally *NOT* contain an ASL license header,\n" +
" * because it is used in the test suite.\n" +
" */\n" +
"public class Source {\n" +
"\n" +
"}\n" +
"\n" +
" =======================================================================\n" +
" ==" + pElementsPath + "/sub/Empty.txt\n" +
" =======================================================================\n" +
"\n";
}
| private static String getElementsReports(String pElementsPath) {
return
"\n" +
"*****************************************************\n" +
"Summary\n" +
"-------\n" +
"Notes: 2\n" +
"Binaries: 1\n" +
"Archives: 1\n" +
"Standards: 4\n" +
"\n" +
"Apache Licensed: 2\n" +
"Generated Documents: 0\n" +
"\n" +
"JavaDocs are generated and so license header is optional\n" +
"Generated files do not required license headers\n" +
"\n" +
"2 Unknown Licenses\n" +
"\n" +
"*******************************\n" +
"\n" +
"Unapproved licenses:\n" +
"\n" +
" " + pElementsPath + "/Source.java\n" +
" " + pElementsPath + "/sub/Empty.txt\n" +
"\n" +
"*******************************\n" +
"\n" +
"Archives:\n" +
"\n" +
" + " + pElementsPath + "/dummy.jar\n" +
" \n" +
"*****************************************************\n" +
" Files with Apache License headers will be marked AL\n" +
" Binary files (which do not require AL headers) will be marked B\n" +
" Compressed archives will be marked A\n" +
" Notices, licenses etc will be marked N\n" +
" B " + pElementsPath + "/Image.png\n" +
" N " + pElementsPath + "/LICENSE\n" +
" N " + pElementsPath + "/NOTICE\n" +
" !????? " + pElementsPath + "/Source.java\n" +
" AL " + pElementsPath + "/Text.txt\n" +
" AL " + pElementsPath + "/Xml.xml\n" +
" A " + pElementsPath + "/dummy.jar\n" +
" !????? " + pElementsPath + "/sub/Empty.txt\n" +
" \n" +
" *****************************************************\n" +
" Printing headers for files without AL header...\n" +
" \n" +
" \n" +
" =======================================================================\n" +
" ==" + pElementsPath + "/Source.java\n" +
" =======================================================================\n" +
"package elements;\n" +
"\n" +
"/*\n" +
" * This file does intentionally *NOT* contain an ASL license header,\n" +
" * because it is used in the test suite.\n" +
" */\n" +
"public class Source {\n" +
"\n" +
"}\n" +
"\n" +
" =======================================================================\n" +
" ==" + pElementsPath + "/sub/Empty.txt\n" +
" =======================================================================\n" +
"\n";
}
|
diff --git a/src/main/java/com/succinctllc/hazelcast/work/bundler/DeferredWorkBundler.java b/src/main/java/com/succinctllc/hazelcast/work/bundler/DeferredWorkBundler.java
index 997a26d..de2d8fd 100644
--- a/src/main/java/com/succinctllc/hazelcast/work/bundler/DeferredWorkBundler.java
+++ b/src/main/java/com/succinctllc/hazelcast/work/bundler/DeferredWorkBundler.java
@@ -1,278 +1,278 @@
package com.succinctllc.hazelcast.work.bundler;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.hazelcast.core.IMap;
import com.hazelcast.logging.ILogger;
import com.hazelcast.logging.Logger;
import com.succinctllc.core.concurrent.BackoffTimer;
import com.succinctllc.core.metrics.MetricNamer;
import com.succinctllc.hazelcast.util.MultiMapProxy;
import com.succinctllc.hazelcast.work.HazelcastWorkTopology;
import com.succinctllc.hazelcast.work.bundler.DeferredWorkBundlerBuilder.InternalBuilderStep3;
import com.succinctllc.hazelcast.work.executor.DistributedExecutorService;
import com.succinctllc.hazelcast.work.metrics.PercentDuplicateRateGuage;
import com.succinctllc.hazelcast.work.metrics.TotalPercentDuplicateGuage;
import com.yammer.metrics.core.Counter;
import com.yammer.metrics.core.Histogram;
import com.yammer.metrics.core.Meter;
import com.yammer.metrics.core.MetricName;
import com.yammer.metrics.core.MetricsRegistry;
import com.yammer.metrics.core.TimerContext;
/**
*
*
*
* @author jclawson
*
* @param <T>
*/
public class DeferredWorkBundler<I> {
private static ILogger LOGGER = Logger.getLogger(DeferredWorkBundler.class.getName());
private static ConcurrentMap<String, DeferredWorkBundler<?>> workBundlersByTopology = new ConcurrentHashMap<String, DeferredWorkBundler<?>>();
private final AtomicBoolean isStarted = new AtomicBoolean();
// private final SetMultimap<String, I> localMultiMap;
// private final MultiMap<String, I> hcMultiMap;
private final MultiMapProxy<String, I> groupItemBuffer;
private final InternalBuilderStep3<I> config;
private final DistributedExecutorService executorService;
private final HazelcastWorkTopology topology;
private final IMap<String, Long> duplicatePreventionMap;
private final MetricNamer metricNamer;
private final MetricsRegistry metrics;
private com.yammer.metrics.core.Timer itemAddTimer;
private Meter itemActuallyAddedMeter;
private Histogram bundleSizeHistogram;
private Histogram flushSizeHistogram;
private Counter numDuplicates;
protected DeferredWorkBundler(InternalBuilderStep3<I> config, DistributedExecutorService svc, MetricNamer metricNamer, MetricsRegistry metrics) {
this.config = config;
this.topology = config.topology;
this.metricNamer = metricNamer;
this.metrics = metrics;
if (workBundlersByTopology.putIfAbsent(topology.getName(), this) != null) {
throw new IllegalArgumentException("A DistributedExecutorServiceManager already exists for the topology "
+ topology);
}
if(!config.localBuffering) {
groupItemBuffer = MultiMapProxy.<String, I>clusteredMultiMap(topology.getHazelcast().<String, I>getMultiMap(topology.createName("group-item-buffer")));
} else {
groupItemBuffer = MultiMapProxy.<String, I>localMultiMap(HashMultimap.<String,I>create());
}
if(config.preventDuplicates) {
duplicatePreventionMap = topology.getHazelcast().getMap(topology.createName("bundler-items"));
} else {
duplicatePreventionMap = null;
}
executorService = svc;
if(metrics != null) {
itemAddTimer = metrics.newTimer(createName("[add] Call timer"), TimeUnit.MILLISECONDS, TimeUnit.MINUTES);
itemActuallyAddedMeter = metrics.newMeter(createName("[add] Added to buffer"), "items added", TimeUnit.MINUTES);
bundleSizeHistogram = metrics.newHistogram(createName("[flush] Bundle size"), true);
flushSizeHistogram = metrics.newHistogram(createName("[flush] Flush size"), true);
metrics.newGauge(createName("[add] Percent duplicate rate"), new PercentDuplicateRateGuage(itemActuallyAddedMeter, itemAddTimer));
metrics.newGauge(createName("[add] Percent duplicates"), new TotalPercentDuplicateGuage(itemActuallyAddedMeter, itemAddTimer));
numDuplicates = metrics.newCounter(createName("[add] Duplicate count"));
}
}
private MetricName createName(String name) {
return metricNamer.createMetricName(
"hazelcast-work",
topology.getName(),
"DeferredWorkBundler",
name
);
}
public HazelcastWorkTopology getTopology() {
return topology;
}
@SuppressWarnings("unchecked")
public static <U> DeferredWorkBundler<U> getDeferredWorkBundler(String topology) {
return (DeferredWorkBundler<U>) workBundlersByTopology.get(topology);
}
public boolean add(I o) {
TimerContext tCtx = null;
if(itemAddTimer != null) {
tCtx = itemAddTimer.time();
}
try {
boolean added = tryAdd(o);
if(added && itemActuallyAddedMeter != null)
itemActuallyAddedMeter.mark();
if(!added && numDuplicates != null)
numDuplicates.inc();
return added;
} finally {
if(tCtx != null)
tCtx.stop();
}
}
private boolean tryAdd(I o) {
String group = config.partitioner.getItemGroup(o);
boolean added = false;
if(duplicatePreventionMap != null) {
if(duplicatePreventionMap.putIfAbsent(
config.partitioner.getItemId(o),
System.currentTimeMillis(),
this.config.maxDuplicatePreventionTTL,
TimeUnit.MILLISECONDS)
!= null) {
return false;
}
}
return groupItemBuffer.put(group, o);
}
public long getFlushTTL() {
return config.flushTTL;
}
public int getFlushSize() {
return config.flushSize;
}
/**
* In order to start bundling and submitting work items to be worked on you
* must make sure to call start()
*
*/
public void startup() {
if(!isStarted.getAndSet(true)) {
//TODO: this timer sucks... is there a better way to flush (maybe with an exponential backoff?)
//it would be cool to have a timer task that we can tell to run immediately with a min-limit to how often it can
//be run in a period manually
//new Timer(buildName("bundle-flush-timer"), true)
// .schedule(new DeferredBundleTask<I>(this, metrics, metricNamer), config.flushTTL, Math.max(config.flushTTL/4, Math.min(4000, config.flushTTL)));
BackoffTimer timer = new BackoffTimer(buildName("bundle-flush-timer"));
timer.schedule(new DeferredBundleTask<I>(this, metrics, metricNamer), 200, 20000, 2);
timer.start();
executorService.startup();
}
}
private String buildName(String postfix) {
return topology + "-" + postfix;
}
public Map<String, Integer> getNonZeroLocalGroupSizes() {
Set<String> localKeys = groupItemBuffer.keySet();
Map<String, Integer> result = new HashMap<String, Integer>(localKeys.size());
for(String key : localKeys) {
int size = groupItemBuffer.get(key).size();
if(size > 0)
result.put(key, size);
}
return result;
}
protected void removePreventDuplicateItems(WorkBundle<I> work) {
if(this.duplicatePreventionMap != null) {
for(I item : work.getItems()) {
String id = config.partitioner.getItemId(item);
this.duplicatePreventionMap.remove(id);
}
}
}
/**
* TODO: Could potentially want to create HUGE bundles.
*
* Note: caller should ensure that this node owns the group partition
* @param group
* @return
*/
protected int flush(String group) {
int numNodes = topology.getReadyMembers().size();
if(numNodes == 0) {
LOGGER.log(Level.WARNING, "I want to flush the deferred item set but no members are online to do the work!");
return 0;
}
List<I> bundle = groupItemBuffer.getAsList(group);
- if(bundle.size() == 0) {
+ if(bundle == null || bundle.size() == 0) {
return 0;
}
//only track flushes that actually have something in them
if(flushSizeHistogram != null)
flushSizeHistogram.update(bundle.size());
int minBundleSize = Math.min(bundle.size(), config.minBundleSize);
int numDividedBundles = bundle.size() / minBundleSize;
numDividedBundles = Math.min(numDividedBundles, numNodes);
int targetDividedBundleSize = Math.max((int)(bundle.size() / numDividedBundles), minBundleSize);
targetDividedBundleSize = Math.min(config.maxBundleSize, targetDividedBundleSize);
List<List<I>> partitionedBundles = Lists.partition(bundle, targetDividedBundleSize);
//bundle the objects and submit them as work
//config.bundler.bundle(items)
for(List<I> partitionedBundle : partitionedBundles) {
if(bundleSizeHistogram != null)
bundleSizeHistogram.update(partitionedBundle.size());
WorkBundle<I> work = config.bundler.bundle(group, partitionedBundle);
if(this.duplicatePreventionMap != null) {
//if we are preventing duplicates, then we need to wrap it
work = new PreventDuplicatesWorkBundleWrapper<I>(topology.getName(), work);
}
executorService.execute(work);
//TODO: is it better to just wait until the end and remove it all at once?
//Remove work from multimap since its safe in the distributed work system
for(I item : partitionedBundle) {
groupItemBuffer.remove(group, item);
}
}
//System.out.println("Processed group "+group+". Total flushed: "+totalFlushed.addAndGet(bundle.size()));
return bundle.size();
}
}
| true | true | protected int flush(String group) {
int numNodes = topology.getReadyMembers().size();
if(numNodes == 0) {
LOGGER.log(Level.WARNING, "I want to flush the deferred item set but no members are online to do the work!");
return 0;
}
List<I> bundle = groupItemBuffer.getAsList(group);
if(bundle.size() == 0) {
return 0;
}
//only track flushes that actually have something in them
if(flushSizeHistogram != null)
flushSizeHistogram.update(bundle.size());
int minBundleSize = Math.min(bundle.size(), config.minBundleSize);
int numDividedBundles = bundle.size() / minBundleSize;
numDividedBundles = Math.min(numDividedBundles, numNodes);
int targetDividedBundleSize = Math.max((int)(bundle.size() / numDividedBundles), minBundleSize);
targetDividedBundleSize = Math.min(config.maxBundleSize, targetDividedBundleSize);
List<List<I>> partitionedBundles = Lists.partition(bundle, targetDividedBundleSize);
//bundle the objects and submit them as work
//config.bundler.bundle(items)
for(List<I> partitionedBundle : partitionedBundles) {
if(bundleSizeHistogram != null)
bundleSizeHistogram.update(partitionedBundle.size());
WorkBundle<I> work = config.bundler.bundle(group, partitionedBundle);
if(this.duplicatePreventionMap != null) {
//if we are preventing duplicates, then we need to wrap it
work = new PreventDuplicatesWorkBundleWrapper<I>(topology.getName(), work);
}
executorService.execute(work);
//TODO: is it better to just wait until the end and remove it all at once?
//Remove work from multimap since its safe in the distributed work system
for(I item : partitionedBundle) {
groupItemBuffer.remove(group, item);
}
}
//System.out.println("Processed group "+group+". Total flushed: "+totalFlushed.addAndGet(bundle.size()));
return bundle.size();
}
| protected int flush(String group) {
int numNodes = topology.getReadyMembers().size();
if(numNodes == 0) {
LOGGER.log(Level.WARNING, "I want to flush the deferred item set but no members are online to do the work!");
return 0;
}
List<I> bundle = groupItemBuffer.getAsList(group);
if(bundle == null || bundle.size() == 0) {
return 0;
}
//only track flushes that actually have something in them
if(flushSizeHistogram != null)
flushSizeHistogram.update(bundle.size());
int minBundleSize = Math.min(bundle.size(), config.minBundleSize);
int numDividedBundles = bundle.size() / minBundleSize;
numDividedBundles = Math.min(numDividedBundles, numNodes);
int targetDividedBundleSize = Math.max((int)(bundle.size() / numDividedBundles), minBundleSize);
targetDividedBundleSize = Math.min(config.maxBundleSize, targetDividedBundleSize);
List<List<I>> partitionedBundles = Lists.partition(bundle, targetDividedBundleSize);
//bundle the objects and submit them as work
//config.bundler.bundle(items)
for(List<I> partitionedBundle : partitionedBundles) {
if(bundleSizeHistogram != null)
bundleSizeHistogram.update(partitionedBundle.size());
WorkBundle<I> work = config.bundler.bundle(group, partitionedBundle);
if(this.duplicatePreventionMap != null) {
//if we are preventing duplicates, then we need to wrap it
work = new PreventDuplicatesWorkBundleWrapper<I>(topology.getName(), work);
}
executorService.execute(work);
//TODO: is it better to just wait until the end and remove it all at once?
//Remove work from multimap since its safe in the distributed work system
for(I item : partitionedBundle) {
groupItemBuffer.remove(group, item);
}
}
//System.out.println("Processed group "+group+". Total flushed: "+totalFlushed.addAndGet(bundle.size()));
return bundle.size();
}
|
diff --git a/jsonhome-spring/src/main/java/de/otto/jsonhome/generator/SpringResourceLinkGenerator.java b/jsonhome-spring/src/main/java/de/otto/jsonhome/generator/SpringResourceLinkGenerator.java
index 79cb68c..f6bc348 100644
--- a/jsonhome-spring/src/main/java/de/otto/jsonhome/generator/SpringResourceLinkGenerator.java
+++ b/jsonhome-spring/src/main/java/de/otto/jsonhome/generator/SpringResourceLinkGenerator.java
@@ -1,100 +1,106 @@
/*
* *
* Copyright 2012 Guido Steinacker
*
* 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.otto.jsonhome.generator;
import org.springframework.web.bind.annotation.RequestMapping;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import static java.util.Arrays.asList;
/**
* A Spring-based ResourceLinkGenerator.
*
* Used to analyse Spring MVC controllers.
*
* @author Guido Steinacker
* @since 17.10.12
*/
public class SpringResourceLinkGenerator extends ResourceLinkGenerator {
private final URI applicationBaseUri;
public SpringResourceLinkGenerator(final URI applicationBaseUri, final URI relationTypeBaseUri) {
super(
applicationBaseUri,
relationTypeBaseUri,
new SpringHintsGenerator(relationTypeBaseUri),
new SpringHrefVarsGenerator(relationTypeBaseUri)
);
this.applicationBaseUri = applicationBaseUri;
}
/**
* {@inheritDoc}
*
* A method is a candidate if there is a RequestMapping annotation.
*
* @param method the current method of the controller.
* @return true if method should be analysed
*/
@Override
public boolean isCandidateForAnalysis(final Method method) {
return method.getAnnotation(RequestMapping.class) != null;
}
@Override
protected List<String> resourcePathsFor(final Method method) {
final List<String> resourcePaths = new ArrayList<String>();
if (isCandidateForAnalysis(method)) {
final RequestMapping methodRequestMapping = method.getAnnotation(RequestMapping.class);
for (final String resourcePathPrefix : parentResourcePathsFrom(method.getDeclaringClass())) {
final String[] resourcePathSuffixes = methodRequestMapping.value().length > 0
? methodRequestMapping.value()
: new String[] {""};
for (String resourcePathSuffix : resourcePathSuffixes) {
- resourcePaths.add(applicationBaseUri + resourcePathPrefix + resourcePathSuffix + queryTemplateFrom(method));
+ final String resourcePath;
+ if (resourcePathPrefix.endsWith("/") && resourcePathSuffix.startsWith("/")) {
+ resourcePath = resourcePathPrefix + resourcePathSuffix.substring(1);
+ } else {
+ resourcePath = resourcePathPrefix + resourcePathSuffix;
+ }
+ resourcePaths.add(applicationBaseUri + resourcePath + queryTemplateFrom(method));
}
}
}
return resourcePaths;
}
/**
* Analyses the controller (possibly annotated with RequestMapping) and returns the list of resource paths defined by the mapping.
*
* @param controller the controller.
* @return list of resource paths.
*/
protected List<String> parentResourcePathsFrom(final Class<?> controller) {
final RequestMapping controllerRequestMapping = controller.getAnnotation(RequestMapping.class);
final List<String> resourcePathPrefixes;
if (controllerRequestMapping != null) {
resourcePathPrefixes = asList(controllerRequestMapping.value());
} else {
resourcePathPrefixes = asList("");
}
return resourcePathPrefixes;
}
}
| true | true | protected List<String> resourcePathsFor(final Method method) {
final List<String> resourcePaths = new ArrayList<String>();
if (isCandidateForAnalysis(method)) {
final RequestMapping methodRequestMapping = method.getAnnotation(RequestMapping.class);
for (final String resourcePathPrefix : parentResourcePathsFrom(method.getDeclaringClass())) {
final String[] resourcePathSuffixes = methodRequestMapping.value().length > 0
? methodRequestMapping.value()
: new String[] {""};
for (String resourcePathSuffix : resourcePathSuffixes) {
resourcePaths.add(applicationBaseUri + resourcePathPrefix + resourcePathSuffix + queryTemplateFrom(method));
}
}
}
return resourcePaths;
}
| protected List<String> resourcePathsFor(final Method method) {
final List<String> resourcePaths = new ArrayList<String>();
if (isCandidateForAnalysis(method)) {
final RequestMapping methodRequestMapping = method.getAnnotation(RequestMapping.class);
for (final String resourcePathPrefix : parentResourcePathsFrom(method.getDeclaringClass())) {
final String[] resourcePathSuffixes = methodRequestMapping.value().length > 0
? methodRequestMapping.value()
: new String[] {""};
for (String resourcePathSuffix : resourcePathSuffixes) {
final String resourcePath;
if (resourcePathPrefix.endsWith("/") && resourcePathSuffix.startsWith("/")) {
resourcePath = resourcePathPrefix + resourcePathSuffix.substring(1);
} else {
resourcePath = resourcePathPrefix + resourcePathSuffix;
}
resourcePaths.add(applicationBaseUri + resourcePath + queryTemplateFrom(method));
}
}
}
return resourcePaths;
}
|
diff --git a/jython/org/python/core/PyBuiltinFunction.java b/jython/org/python/core/PyBuiltinFunction.java
index f3c5cd3c..86edca37 100644
--- a/jython/org/python/core/PyBuiltinFunction.java
+++ b/jython/org/python/core/PyBuiltinFunction.java
@@ -1,157 +1,157 @@
package org.python.core;
public abstract class PyBuiltinFunction extends PyObject implements PyType.Newstyle {
/* type info */
public static final String exposed_name="builtin_function_or_method";
public static void typeSetup(PyObject dict,PyType.Newstyle marker) {
dict.__setitem__("__name__", new PyGetSetDescr("__name__",
PyBuiltinFunction.class, "fastGetName", null));
dict.__setitem__("__self__", new PyGetSetDescr("__self__",
PyBuiltinFunction.class, "getSelf", null));
dict.__setitem__("__doc__", new PyGetSetDescr("__doc__",
PyBuiltinFunction.class, "fastGetDoc", null));
}
public interface Info {
String getName();
int getMaxargs();
int getMinargs();
PyException unexpectedCall(int nargs, boolean keywords);
}
public static class DefaultInfo implements Info {
public DefaultInfo(String name,int minargs,int maxargs) {
this.name = name;
this.minargs = minargs;
this.maxargs = maxargs;
}
public DefaultInfo(String name,int nargs) {
this(name,nargs,nargs);
}
private String name;
private int maxargs, minargs;
public String getName() {
return name;
}
public int getMaxargs() {
return maxargs;
}
public int getMinargs() {
return minargs;
}
public static boolean check(int nargs,int minargs,int maxargs) {
if (nargs < minargs)
return false;
if (maxargs != -1 && nargs > maxargs)
return false;
return true;
}
public static PyException unexpectedCall(
int nargs,
boolean keywords,
String name,
int minargs,
int maxargs) {
if (keywords)
return Py.TypeError(name + "() takes no keyword arguments");
String argsblurb;
if (minargs == maxargs) {
if (minargs == 0)
argsblurb = "no arguments";
else if (minargs == 1)
argsblurb = "exactly one argument";
else
argsblurb = minargs + " arguments";
} else if (maxargs == -1) {
return Py.TypeError(name + "() requires at least " +
minargs + " (" + nargs + " given)");
} else {
if (minargs <= 0)
- argsblurb = "at most "+ maxargs + " argumens";
+ argsblurb = "at most "+ maxargs + " arguments";
else
argsblurb = minargs + "-" + maxargs + " arguments";
}
return Py.TypeError(
name + "() takes " + argsblurb + " (" + nargs + " given)");
}
public PyException unexpectedCall(int nargs, boolean keywords) {
return unexpectedCall(nargs, keywords, name, minargs, maxargs);
}
}
protected PyBuiltinFunction() {}
protected PyBuiltinFunction(Info info) {
this.info = info;
}
protected Info info;
public void setInfo(Info info) {
this.info = info;
}
abstract protected PyBuiltinFunction makeBound(PyObject self);
public PyObject getSelf() {
return null;
}
public String toString() {
PyObject self = getSelf();
if (self == null)
return "<built-in function " + info.getName() + ">";
else {
String typename = self.getType().fastGetName();
return "<built-in method "
+ info.getName()
+ " of "
+ typename
+ " object>";
}
}
abstract public PyObject inst_call(PyObject self);
abstract public PyObject inst_call(PyObject self, PyObject arg0);
abstract public PyObject inst_call(
PyObject self,
PyObject arg0,
PyObject arg1);
abstract public PyObject inst_call(
PyObject self,
PyObject arg0,
PyObject arg1,
PyObject arg2);
abstract public PyObject inst_call(
PyObject self,
PyObject arg0,
PyObject arg1,
PyObject arg2,
PyObject arg3);
abstract public PyObject inst_call(PyObject self, PyObject[] args);
abstract public PyObject inst_call(
PyObject self,
PyObject[] args,
String[] keywords);
public PyObject fastGetName() {
return Py.newString(this.info.getName());
}
public PyObject fastGetDoc() {
return Py.None;
}
}
| true | true | public static PyException unexpectedCall(
int nargs,
boolean keywords,
String name,
int minargs,
int maxargs) {
if (keywords)
return Py.TypeError(name + "() takes no keyword arguments");
String argsblurb;
if (minargs == maxargs) {
if (minargs == 0)
argsblurb = "no arguments";
else if (minargs == 1)
argsblurb = "exactly one argument";
else
argsblurb = minargs + " arguments";
} else if (maxargs == -1) {
return Py.TypeError(name + "() requires at least " +
minargs + " (" + nargs + " given)");
} else {
if (minargs <= 0)
argsblurb = "at most "+ maxargs + " argumens";
else
argsblurb = minargs + "-" + maxargs + " arguments";
}
return Py.TypeError(
name + "() takes " + argsblurb + " (" + nargs + " given)");
}
| public static PyException unexpectedCall(
int nargs,
boolean keywords,
String name,
int minargs,
int maxargs) {
if (keywords)
return Py.TypeError(name + "() takes no keyword arguments");
String argsblurb;
if (minargs == maxargs) {
if (minargs == 0)
argsblurb = "no arguments";
else if (minargs == 1)
argsblurb = "exactly one argument";
else
argsblurb = minargs + " arguments";
} else if (maxargs == -1) {
return Py.TypeError(name + "() requires at least " +
minargs + " (" + nargs + " given)");
} else {
if (minargs <= 0)
argsblurb = "at most "+ maxargs + " arguments";
else
argsblurb = minargs + "-" + maxargs + " arguments";
}
return Py.TypeError(
name + "() takes " + argsblurb + " (" + nargs + " given)");
}
|
diff --git a/htmlelements-java/src/main/java/ru/yandex/qatools/htmlelements/loader/decorator/HtmlElementClassAnnotationsHandler.java b/htmlelements-java/src/main/java/ru/yandex/qatools/htmlelements/loader/decorator/HtmlElementClassAnnotationsHandler.java
index 556517a..2a551a6 100644
--- a/htmlelements-java/src/main/java/ru/yandex/qatools/htmlelements/loader/decorator/HtmlElementClassAnnotationsHandler.java
+++ b/htmlelements-java/src/main/java/ru/yandex/qatools/htmlelements/loader/decorator/HtmlElementClassAnnotationsHandler.java
@@ -1,40 +1,41 @@
package ru.yandex.qatools.htmlelements.loader.decorator;
import org.openqa.selenium.By;
import ru.yandex.qatools.htmlelements.annotations.Block;
import ru.yandex.qatools.htmlelements.element.HtmlElement;
import ru.yandex.qatools.htmlelements.exceptions.HtmlElementsException;
import ru.yandex.qatools.htmlelements.pagefactory.AnnotationsHandler;
/**
* Handles {@link Block} annotation of {@link HtmlElement} and its successors.
*
* @author Alexander Tolmachev [email protected]
* Date: 20.08.12
*/
public class HtmlElementClassAnnotationsHandler<T extends HtmlElement> extends AnnotationsHandler {
private final Class<T> htmlElementClass;
public HtmlElementClassAnnotationsHandler(Class<T> htmlElementClass) {
this.htmlElementClass = htmlElementClass;
}
@Override
public By buildBy() {
Class<?> clazz = htmlElementClass;
while (clazz != Object.class) {
if (clazz.isAnnotationPresent(Block.class)) {
Block block = clazz.getAnnotation(Block.class);
return buildByFromFindBy(block.value());
}
clazz = clazz.getSuperclass();
}
- throw new HtmlElementsException(String.format("Cannot determine how to locate instance of %s", htmlElementClass));
+ throw new HtmlElementsException(String.format("Cannot determine how to locate instance of %s",
+ htmlElementClass));
}
@Override
public boolean shouldCache() {
return false;
}
}
| true | true | public By buildBy() {
Class<?> clazz = htmlElementClass;
while (clazz != Object.class) {
if (clazz.isAnnotationPresent(Block.class)) {
Block block = clazz.getAnnotation(Block.class);
return buildByFromFindBy(block.value());
}
clazz = clazz.getSuperclass();
}
throw new HtmlElementsException(String.format("Cannot determine how to locate instance of %s", htmlElementClass));
}
| public By buildBy() {
Class<?> clazz = htmlElementClass;
while (clazz != Object.class) {
if (clazz.isAnnotationPresent(Block.class)) {
Block block = clazz.getAnnotation(Block.class);
return buildByFromFindBy(block.value());
}
clazz = clazz.getSuperclass();
}
throw new HtmlElementsException(String.format("Cannot determine how to locate instance of %s",
htmlElementClass));
}
|
diff --git a/sky/org.kevoree.library.sky.api/src/main/java/org/kevoree/library/sky/api/execution/CommandMapper.java b/sky/org.kevoree.library.sky.api/src/main/java/org/kevoree/library/sky/api/execution/CommandMapper.java
index 55c9c2c..65ec4b1 100644
--- a/sky/org.kevoree.library.sky.api/src/main/java/org/kevoree/library/sky/api/execution/CommandMapper.java
+++ b/sky/org.kevoree.library.sky.api/src/main/java/org/kevoree/library/sky/api/execution/CommandMapper.java
@@ -1,67 +1,67 @@
package org.kevoree.library.sky.api.execution;
import org.kevoree.ContainerNode;
import org.kevoree.ContainerRoot;
import org.kevoree.api.PrimitiveCommand;
import org.kevoree.kompare.JavaSePrimitive;
import org.kevoree.library.sky.api.CloudNode;
import org.kevoree.library.sky.api.execution.command.AddNodeCommand;
import org.kevoree.library.sky.api.execution.command.RemoveNodeCommand;
import org.kevoree.library.sky.api.execution.command.StartNodeCommand;
import org.kevoree.library.sky.api.execution.command.StopNodeCommand;
import org.kevoree.log.Log;
import org.kevoreeadaptation.AdaptationPrimitive;
/**
* User: Erwan Daubert - [email protected]
* Date: 12/06/13
* Time: 13:02
*
* @author Erwan Daubert
* @version 1.0
*/
public class CommandMapper extends org.kevoree.library.defaultNodeTypes.CommandMapper {
private KevoreeNodeManager nodeManager;
public CommandMapper(KevoreeNodeManager nodeManager) {
this.nodeManager = nodeManager;
}
public PrimitiveCommand buildPrimitiveCommand(AdaptationPrimitive adaptationPrimitive, String nodeName) {
Log.debug("ask for primitiveCommand corresponding to {}", adaptationPrimitive.getPrimitiveType().getName());
PrimitiveCommand command = null;
- if (adaptationPrimitive.getPrimitiveType().getName() == CloudNode.REMOVE_NODE) {
+ if (adaptationPrimitive.getPrimitiveType().getName().equals(CloudNode.REMOVE_NODE)) {
Log.debug("add REMOVE_NODE command on {}", ((ContainerNode) adaptationPrimitive.getRef()).getName());
ContainerNode targetNode = (ContainerNode) adaptationPrimitive.getRef();
ContainerRoot targetNodeRoot = (ContainerRoot) ((ContainerNode) adaptationPrimitive.getRef()).eContainer();
command = new RemoveNodeCommand(targetNodeRoot, targetNode.getName(), nodeManager);
- } else if (adaptationPrimitive.getPrimitiveType().getName() == CloudNode.ADD_NODE) {
+ } else if (adaptationPrimitive.getPrimitiveType().getName().equals(CloudNode.ADD_NODE)) {
Log.debug("add ADD_NODE command on {}", ((ContainerNode) adaptationPrimitive.getRef()).getName());
ContainerNode targetNode = (ContainerNode) adaptationPrimitive.getRef();
ContainerRoot targetNodeRoot = (ContainerRoot) ((ContainerNode) adaptationPrimitive.getRef()).eContainer();
command = new AddNodeCommand(targetNodeRoot, targetNode.getName(), nodeManager);
- } else if (adaptationPrimitive.getPrimitiveType().getName() == JavaSePrimitive.instance$.getStartInstance() && adaptationPrimitive.getRef() instanceof ContainerNode) {
+ } else if (adaptationPrimitive.getPrimitiveType().getName().equals(JavaSePrimitive.instance$.getStartInstance()) && adaptationPrimitive.getRef() instanceof ContainerNode) {
Log.debug("add START_NODE command on {}", ((ContainerNode) adaptationPrimitive.getRef()).getName());
ContainerNode targetNode = (ContainerNode) adaptationPrimitive.getRef();
ContainerRoot targetNodeRoot = (ContainerRoot) ((ContainerNode) adaptationPrimitive.getRef()).eContainer();
command = new StartNodeCommand(targetNodeRoot, targetNode.getName(), nodeManager);
- } else if (adaptationPrimitive.getPrimitiveType().getName() == JavaSePrimitive.instance$.getStopInstance() && adaptationPrimitive.getRef() instanceof ContainerNode) {
+ } else if (adaptationPrimitive.getPrimitiveType().getName().equals(JavaSePrimitive.instance$.getStopInstance()) && adaptationPrimitive.getRef() instanceof ContainerNode) {
Log.debug("add STOP_NODE command on {}", ((ContainerNode) adaptationPrimitive.getRef()).getName());
ContainerNode targetNode = (ContainerNode) adaptationPrimitive.getRef();
ContainerRoot targetNodeRoot = (ContainerRoot) ((ContainerNode) adaptationPrimitive.getRef()).eContainer();
command = new StopNodeCommand(targetNodeRoot, targetNode.getName(), nodeManager);
}
if (command == null) {
Log.debug("AdaptationPrimitive is not managed by CloudNode, asking to JavaSeNode...");
command = super.buildPrimitiveCommand(adaptationPrimitive, nodeName);
}
return command;
}
}
| false | true | public PrimitiveCommand buildPrimitiveCommand(AdaptationPrimitive adaptationPrimitive, String nodeName) {
Log.debug("ask for primitiveCommand corresponding to {}", adaptationPrimitive.getPrimitiveType().getName());
PrimitiveCommand command = null;
if (adaptationPrimitive.getPrimitiveType().getName() == CloudNode.REMOVE_NODE) {
Log.debug("add REMOVE_NODE command on {}", ((ContainerNode) adaptationPrimitive.getRef()).getName());
ContainerNode targetNode = (ContainerNode) adaptationPrimitive.getRef();
ContainerRoot targetNodeRoot = (ContainerRoot) ((ContainerNode) adaptationPrimitive.getRef()).eContainer();
command = new RemoveNodeCommand(targetNodeRoot, targetNode.getName(), nodeManager);
} else if (adaptationPrimitive.getPrimitiveType().getName() == CloudNode.ADD_NODE) {
Log.debug("add ADD_NODE command on {}", ((ContainerNode) adaptationPrimitive.getRef()).getName());
ContainerNode targetNode = (ContainerNode) adaptationPrimitive.getRef();
ContainerRoot targetNodeRoot = (ContainerRoot) ((ContainerNode) adaptationPrimitive.getRef()).eContainer();
command = new AddNodeCommand(targetNodeRoot, targetNode.getName(), nodeManager);
} else if (adaptationPrimitive.getPrimitiveType().getName() == JavaSePrimitive.instance$.getStartInstance() && adaptationPrimitive.getRef() instanceof ContainerNode) {
Log.debug("add START_NODE command on {}", ((ContainerNode) adaptationPrimitive.getRef()).getName());
ContainerNode targetNode = (ContainerNode) adaptationPrimitive.getRef();
ContainerRoot targetNodeRoot = (ContainerRoot) ((ContainerNode) adaptationPrimitive.getRef()).eContainer();
command = new StartNodeCommand(targetNodeRoot, targetNode.getName(), nodeManager);
} else if (adaptationPrimitive.getPrimitiveType().getName() == JavaSePrimitive.instance$.getStopInstance() && adaptationPrimitive.getRef() instanceof ContainerNode) {
Log.debug("add STOP_NODE command on {}", ((ContainerNode) adaptationPrimitive.getRef()).getName());
ContainerNode targetNode = (ContainerNode) adaptationPrimitive.getRef();
ContainerRoot targetNodeRoot = (ContainerRoot) ((ContainerNode) adaptationPrimitive.getRef()).eContainer();
command = new StopNodeCommand(targetNodeRoot, targetNode.getName(), nodeManager);
}
if (command == null) {
Log.debug("AdaptationPrimitive is not managed by CloudNode, asking to JavaSeNode...");
command = super.buildPrimitiveCommand(adaptationPrimitive, nodeName);
}
return command;
}
| public PrimitiveCommand buildPrimitiveCommand(AdaptationPrimitive adaptationPrimitive, String nodeName) {
Log.debug("ask for primitiveCommand corresponding to {}", adaptationPrimitive.getPrimitiveType().getName());
PrimitiveCommand command = null;
if (adaptationPrimitive.getPrimitiveType().getName().equals(CloudNode.REMOVE_NODE)) {
Log.debug("add REMOVE_NODE command on {}", ((ContainerNode) adaptationPrimitive.getRef()).getName());
ContainerNode targetNode = (ContainerNode) adaptationPrimitive.getRef();
ContainerRoot targetNodeRoot = (ContainerRoot) ((ContainerNode) adaptationPrimitive.getRef()).eContainer();
command = new RemoveNodeCommand(targetNodeRoot, targetNode.getName(), nodeManager);
} else if (adaptationPrimitive.getPrimitiveType().getName().equals(CloudNode.ADD_NODE)) {
Log.debug("add ADD_NODE command on {}", ((ContainerNode) adaptationPrimitive.getRef()).getName());
ContainerNode targetNode = (ContainerNode) adaptationPrimitive.getRef();
ContainerRoot targetNodeRoot = (ContainerRoot) ((ContainerNode) adaptationPrimitive.getRef()).eContainer();
command = new AddNodeCommand(targetNodeRoot, targetNode.getName(), nodeManager);
} else if (adaptationPrimitive.getPrimitiveType().getName().equals(JavaSePrimitive.instance$.getStartInstance()) && adaptationPrimitive.getRef() instanceof ContainerNode) {
Log.debug("add START_NODE command on {}", ((ContainerNode) adaptationPrimitive.getRef()).getName());
ContainerNode targetNode = (ContainerNode) adaptationPrimitive.getRef();
ContainerRoot targetNodeRoot = (ContainerRoot) ((ContainerNode) adaptationPrimitive.getRef()).eContainer();
command = new StartNodeCommand(targetNodeRoot, targetNode.getName(), nodeManager);
} else if (adaptationPrimitive.getPrimitiveType().getName().equals(JavaSePrimitive.instance$.getStopInstance()) && adaptationPrimitive.getRef() instanceof ContainerNode) {
Log.debug("add STOP_NODE command on {}", ((ContainerNode) adaptationPrimitive.getRef()).getName());
ContainerNode targetNode = (ContainerNode) adaptationPrimitive.getRef();
ContainerRoot targetNodeRoot = (ContainerRoot) ((ContainerNode) adaptationPrimitive.getRef()).eContainer();
command = new StopNodeCommand(targetNodeRoot, targetNode.getName(), nodeManager);
}
if (command == null) {
Log.debug("AdaptationPrimitive is not managed by CloudNode, asking to JavaSeNode...");
command = super.buildPrimitiveCommand(adaptationPrimitive, nodeName);
}
return command;
}
|
diff --git a/src/main/java/com/xtremelabs/robolectric/shadows/ShadowFrameLayout.java b/src/main/java/com/xtremelabs/robolectric/shadows/ShadowFrameLayout.java
index dd16b3e5..d96ca345 100644
--- a/src/main/java/com/xtremelabs/robolectric/shadows/ShadowFrameLayout.java
+++ b/src/main/java/com/xtremelabs/robolectric/shadows/ShadowFrameLayout.java
@@ -1,31 +1,31 @@
package com.xtremelabs.robolectric.shadows;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import com.xtremelabs.robolectric.internal.Implementation;
import com.xtremelabs.robolectric.internal.Implements;
/**
* Shadow for {@link FrameLayout} that simulates its implementation.
*/
@SuppressWarnings("UnusedDeclaration")
@Implements(FrameLayout.class)
public class ShadowFrameLayout extends ShadowViewGroup {
public void __constructor__(Context context, AttributeSet attributeSet, int defStyle) {
setLayoutParams(new ViewGroup.MarginLayoutParams(0, 0));
super.__constructor__(context, attributeSet, defStyle);
}
@Implementation
- protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
+ public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
layout(right, top, right + width, top + height);
}
}
| true | true | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
layout(right, top, right + width, top + height);
}
| public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
layout(right, top, right + width, top + height);
}
|
diff --git a/src/com/android/mms/data/Contact.java b/src/com/android/mms/data/Contact.java
index 42f9037..d7290e4 100644
--- a/src/com/android/mms/data/Contact.java
+++ b/src/com/android/mms/data/Contact.java
@@ -1,489 +1,491 @@
package com.android.mms.data;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import android.content.ContentUris;
import android.content.Context;
import android.database.ContentObserver;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Presence;
import android.provider.Telephony.Mms;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.util.Log;
import com.android.mms.ui.MessageUtils;
import com.android.mms.util.ContactInfoCache;
import com.android.mms.util.TaskStack;
import com.android.mms.LogTag;
public class Contact {
private static final String TAG = "Contact";
private static final boolean V = false;
private static final TaskStack sTaskStack = new TaskStack();
// private static final ContentObserver sContactsObserver = new ContentObserver(new Handler()) {
// @Override
// public void onChange(boolean selfUpdate) {
// if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
// log("contact changed, invalidate cache");
// }
// invalidateCache();
// }
// };
private static final ContentObserver sPresenceObserver = new ContentObserver(new Handler()) {
@Override
public void onChange(boolean selfUpdate) {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("presence changed, invalidate cache");
}
invalidateCache();
}
};
private final HashSet<UpdateListener> mListeners = new HashSet<UpdateListener>();
private String mNumber;
private String mName;
private String mNameAndNumber; // for display, e.g. Fred Flintstone <670-782-1123>
private boolean mNumberIsModified; // true if the number is modified
private long mRecipientId; // used to find the Recipient cache entry
private String mLabel;
private long mPersonId;
private int mPresenceResId; // TODO: make this a state instead of a res ID
private String mPresenceText;
private BitmapDrawable mAvatar;
private boolean mIsStale;
@Override
public synchronized String toString() {
return String.format("{ number=%s, name=%s, nameAndNumber=%s, label=%s, person_id=%d }",
mNumber, mName, mNameAndNumber, mLabel, mPersonId);
}
public interface UpdateListener {
public void onUpdate(Contact updated);
}
private Contact(String number) {
mName = "";
setNumber(number);
mNumberIsModified = false;
mLabel = "";
mPersonId = 0;
mPresenceResId = 0;
mIsStale = true;
}
private static void logWithTrace(String msg, Object... format) {
Thread current = Thread.currentThread();
StackTraceElement[] stack = current.getStackTrace();
StringBuilder sb = new StringBuilder();
sb.append("[");
sb.append(current.getId());
sb.append("] ");
sb.append(String.format(msg, format));
sb.append(" <- ");
int stop = stack.length > 7 ? 7 : stack.length;
for (int i = 3; i < stop; i++) {
String methodName = stack[i].getMethodName();
sb.append(methodName);
if ((i+1) != stop) {
sb.append(" <- ");
}
}
Log.d(TAG, sb.toString());
}
public static Contact get(String number, boolean canBlock) {
if (V) logWithTrace("get(%s, %s)", number, canBlock);
if (TextUtils.isEmpty(number)) {
throw new IllegalArgumentException("Contact.get called with null or empty number");
}
Contact contact = Cache.get(number);
if (contact == null) {
contact = new Contact(number);
Cache.put(contact);
}
if (contact.mIsStale) {
asyncUpdateContact(contact, canBlock);
}
return contact;
}
public static void invalidateCache() {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("invalidateCache");
}
// force invalidate the contact info cache, so we will query for fresh info again.
// This is so we can get fresh presence info again on the screen, since the presence
// info changes pretty quickly, and we can't get change notifications when presence is
// updated in the ContactsProvider.
ContactInfoCache.getInstance().invalidateCache();
// While invalidating our local Cache doesn't remove the contacts, it will mark them
// stale so the next time we're asked for a particular contact, we'll return that
// stale contact and at the same time, fire off an asyncUpdateContact to update
// that contact's info in the background. UI elements using the contact typically
// call addListener() so they immediately get notified when the contact has been
// updated with the latest info. They redraw themselves when we call the
// listener's onUpdate().
Cache.invalidate();
}
private static String emptyIfNull(String s) {
return (s != null ? s : "");
}
private static boolean contactChanged(Contact orig, ContactInfoCache.CacheEntry newEntry) {
// The phone number should never change, so don't bother checking.
// TODO: Maybe update it if it has gotten longer, i.e. 650-234-5678 -> +16502345678?
String oldName = emptyIfNull(orig.mName);
String newName = emptyIfNull(newEntry.name);
if (!oldName.equals(newName)) {
if (V) Log.d(TAG, String.format("name changed: %s -> %s", oldName, newName));
return true;
}
String oldLabel = emptyIfNull(orig.mLabel);
String newLabel = emptyIfNull(newEntry.phoneLabel);
if (!oldLabel.equals(newLabel)) {
if (V) Log.d(TAG, String.format("label changed: %s -> %s", oldLabel, newLabel));
return true;
}
if (orig.mPersonId != newEntry.person_id) {
if (V) Log.d(TAG, "person id changed");
return true;
}
if (orig.mPresenceResId != newEntry.presenceResId) {
if (V) Log.d(TAG, "presence changed");
return true;
}
return false;
}
/**
* Handles the special case where the local ("Me") number is being looked up.
* Updates the contact with the "me" name and returns true if it is the
* local number, no-ops and returns false if it is not.
*/
private static boolean handleLocalNumber(Contact c) {
if (MessageUtils.isLocalNumber(c.mNumber)) {
c.mName = Cache.getContext().getString(com.android.internal.R.string.me);
c.updateNameAndNumber();
return true;
}
return false;
}
private static void asyncUpdateContact(final Contact c, boolean canBlock) {
if (c == null) {
return;
}
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("asyncUpdateContact for " + c.toString() + " canBlock: " + canBlock +
" isStale: " + c.mIsStale);
}
Runnable r = new Runnable() {
public void run() {
updateContact(c);
}
};
if (canBlock) {
r.run();
} else {
sTaskStack.push(r);
}
}
private static void updateContact(final Contact c) {
if (c == null) {
return;
}
// Check to see if this is the local ("me") number.
if (handleLocalNumber(c)) {
return;
}
ContactInfoCache cache = ContactInfoCache.getInstance();
ContactInfoCache.CacheEntry entry = cache.getContactInfo(c.mNumber);
synchronized (Cache.getInstance()) {
if (contactChanged(c, entry)) {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("updateContact: contact changed for " + entry.name);
}
//c.mNumber = entry.phoneNumber;
c.mName = entry.name;
c.updateNameAndNumber();
c.mLabel = entry.phoneLabel;
c.mPersonId = entry.person_id;
c.mPresenceResId = entry.presenceResId;
c.mPresenceText = entry.presenceText;
c.mAvatar = entry.mAvatar;
c.mIsStale = false;
for (UpdateListener l : c.mListeners) {
if (V) Log.d(TAG, "updating " + l);
l.onUpdate(c);
}
+ } else {
+ c.mIsStale = false;
}
}
}
public static String formatNameAndNumber(String name, String number) {
// Format like this: Mike Cleron <(650) 555-1234>
// Erick Tseng <(650) 555-1212>
// Tutankhamun <[email protected]>
// (408) 555-1289
String formattedNumber = number;
if (!Mms.isEmailAddress(number)) {
formattedNumber = PhoneNumberUtils.formatNumber(number);
}
if (!TextUtils.isEmpty(name) && !name.equals(number)) {
return name + " <" + formattedNumber + ">";
} else {
return formattedNumber;
}
}
public synchronized String getNumber() {
return mNumber;
}
public synchronized void setNumber(String number) {
mNumber = number;
updateNameAndNumber();
mNumberIsModified = true;
}
public boolean isNumberModified() {
return mNumberIsModified;
}
public void setIsNumberModified(boolean flag) {
mNumberIsModified = flag;
}
public synchronized String getName() {
if (TextUtils.isEmpty(mName)) {
return mNumber;
} else {
return mName;
}
}
public synchronized String getNameAndNumber() {
return mNameAndNumber;
}
private void updateNameAndNumber() {
mNameAndNumber = formatNameAndNumber(mName, mNumber);
}
public synchronized long getRecipientId() {
return mRecipientId;
}
public synchronized void setRecipientId(long id) {
mRecipientId = id;
}
public synchronized String getLabel() {
return mLabel;
}
public synchronized Uri getUri() {
return ContentUris.withAppendedId(Contacts.CONTENT_URI, mPersonId);
}
public long getPersonId() {
return mPersonId;
}
public synchronized int getPresenceResId() {
return mPresenceResId;
}
public synchronized boolean existsInDatabase() {
return (mPersonId > 0);
}
public synchronized void addListener(UpdateListener l) {
boolean added = mListeners.add(l);
if (V && added) dumpListeners();
}
public synchronized void removeListener(UpdateListener l) {
boolean removed = mListeners.remove(l);
if (V && removed) dumpListeners();
}
public synchronized void dumpListeners() {
int i=0;
Log.i(TAG, "[Contact] dumpListeners(" + mNumber + ") size=" + mListeners.size());
for (UpdateListener listener : mListeners) {
Log.i(TAG, "["+ (i++) + "]" + listener);
}
}
public synchronized boolean isEmail() {
return Mms.isEmailAddress(mNumber);
}
public String getPresenceText() {
return mPresenceText;
}
public Drawable getAvatar(Drawable defaultValue) {
return mAvatar != null ? mAvatar : defaultValue;
}
public static void init(final Context context) {
Cache.init(context);
RecipientIdCache.init(context);
// it maybe too aggressive to listen for *any* contact changes, and rebuild MMS contact
// cache each time that occurs. Unless we can get targeted updates for the contacts we
// care about(which probably won't happen for a long time), we probably should just
// invalidate cache peoridically, or surgically.
/*
context.getContentResolver().registerContentObserver(
Contacts.CONTENT_URI, true, sContactsObserver);
*/
}
public static void dump() {
Cache.dump();
}
public static void startPresenceObserver() {
Cache.getContext().getContentResolver().registerContentObserver(
Presence.CONTENT_URI, true, sPresenceObserver);
}
public static void stopPresenceObserver() {
Cache.getContext().getContentResolver().unregisterContentObserver(sPresenceObserver);
}
private static class Cache {
private static Cache sInstance;
static Cache getInstance() { return sInstance; }
private final List<Contact> mCache;
private final Context mContext;
private Cache(Context context) {
mCache = new ArrayList<Contact>();
mContext = context;
}
static void init(Context context) {
sInstance = new Cache(context);
}
static Context getContext() {
return sInstance.mContext;
}
static void dump() {
synchronized (sInstance) {
Log.d(TAG, "**** Contact cache dump ****");
for (Contact c : sInstance.mCache) {
Log.d(TAG, c.toString());
}
}
}
private static Contact getEmail(String number) {
synchronized (sInstance) {
for (Contact c : sInstance.mCache) {
if (number.equalsIgnoreCase(c.mNumber)) {
return c;
}
}
return null;
}
}
static Contact get(String number) {
if (Mms.isEmailAddress(number))
return getEmail(number);
synchronized (sInstance) {
for (Contact c : sInstance.mCache) {
// if the numbers are an exact match (i.e. Google SMS), or if the phone
// number comparison returns a match, return the contact.
if (number.equals(c.mNumber) || PhoneNumberUtils.compare(number, c.mNumber)) {
return c;
}
}
return null;
}
}
static void put(Contact c) {
synchronized (sInstance) {
// We update cache entries in place so people with long-
// held references get updated.
if (get(c.mNumber) != null) {
throw new IllegalStateException("cache already contains " + c);
}
sInstance.mCache.add(c);
}
}
static String[] getNumbers() {
synchronized (sInstance) {
String[] numbers = new String[sInstance.mCache.size()];
int i = 0;
for (Contact c : sInstance.mCache) {
numbers[i++] = c.getNumber();
}
return numbers;
}
}
static List<Contact> getContacts() {
synchronized (sInstance) {
return new ArrayList<Contact>(sInstance.mCache);
}
}
static void invalidate() {
// Don't remove the contacts. Just mark them stale so we'll update their
// info, particularly their presence.
synchronized (sInstance) {
for (Contact c : sInstance.mCache) {
c.mIsStale = true;
}
}
}
}
private static void log(String msg) {
Log.d(TAG, msg);
}
}
| true | true | private static void updateContact(final Contact c) {
if (c == null) {
return;
}
// Check to see if this is the local ("me") number.
if (handleLocalNumber(c)) {
return;
}
ContactInfoCache cache = ContactInfoCache.getInstance();
ContactInfoCache.CacheEntry entry = cache.getContactInfo(c.mNumber);
synchronized (Cache.getInstance()) {
if (contactChanged(c, entry)) {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("updateContact: contact changed for " + entry.name);
}
//c.mNumber = entry.phoneNumber;
c.mName = entry.name;
c.updateNameAndNumber();
c.mLabel = entry.phoneLabel;
c.mPersonId = entry.person_id;
c.mPresenceResId = entry.presenceResId;
c.mPresenceText = entry.presenceText;
c.mAvatar = entry.mAvatar;
c.mIsStale = false;
for (UpdateListener l : c.mListeners) {
if (V) Log.d(TAG, "updating " + l);
l.onUpdate(c);
}
}
}
}
| private static void updateContact(final Contact c) {
if (c == null) {
return;
}
// Check to see if this is the local ("me") number.
if (handleLocalNumber(c)) {
return;
}
ContactInfoCache cache = ContactInfoCache.getInstance();
ContactInfoCache.CacheEntry entry = cache.getContactInfo(c.mNumber);
synchronized (Cache.getInstance()) {
if (contactChanged(c, entry)) {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("updateContact: contact changed for " + entry.name);
}
//c.mNumber = entry.phoneNumber;
c.mName = entry.name;
c.updateNameAndNumber();
c.mLabel = entry.phoneLabel;
c.mPersonId = entry.person_id;
c.mPresenceResId = entry.presenceResId;
c.mPresenceText = entry.presenceText;
c.mAvatar = entry.mAvatar;
c.mIsStale = false;
for (UpdateListener l : c.mListeners) {
if (V) Log.d(TAG, "updating " + l);
l.onUpdate(c);
}
} else {
c.mIsStale = false;
}
}
}
|
diff --git a/swag-auth/src/main/java/at/ac/tuwien/swag/auth/AuthenticationBean.java b/swag-auth/src/main/java/at/ac/tuwien/swag/auth/AuthenticationBean.java
index 9a3446f..290983c 100644
--- a/swag-auth/src/main/java/at/ac/tuwien/swag/auth/AuthenticationBean.java
+++ b/swag-auth/src/main/java/at/ac/tuwien/swag/auth/AuthenticationBean.java
@@ -1,123 +1,125 @@
package at.ac.tuwien.swag.auth;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.persistence.NoResultException;
import at.ac.tuwien.swag.messages.auth.AuthenticationReply;
import at.ac.tuwien.swag.messages.auth.AuthenticationRequest;
import at.ac.tuwien.swag.messages.auth.StoreUserRequest;
import at.ac.tuwien.swag.messages.auth.UserExistsRequest;
import at.ac.tuwien.swag.model.dao.UserDAO;
import at.ac.tuwien.swag.model.domain.User;
import at.ac.tuwien.swag.util.PasswordHasher;
@MessageDriven( mappedName="swag.queue.Authentication" )
public class AuthenticationBean extends MessageHandler implements MessageListener {
@PostConstruct
public void initialize() throws JMSException {
users = new UserDAO( persistence.makeEntityManager() );
hasher = new PasswordHasher();
connection = connectionFactory.createConnection();
session = connection.createSession( false, Session.AUTO_ACKNOWLEDGE );
connection.start();
}
@Override
public void onMessage( Message msg ) {
try {
handleMessage( session, msg.getJMSReplyTo(), getPayload( msg ) );
} catch ( JMSException e ) {
e.printStackTrace();
}
}
public void handle( String msg ) throws JMSException {
reply( "Hi, Authentication service speaking. It was nice to hear from you" );
}
public void handle( AuthenticationRequest msg ) throws JMSException {
String username = msg.username;
String password = msg.password;
String token = "DUMMY TOKEN";
AuthenticationReply reply = new AuthenticationReply( username, null, null );
try {
String storedHash = users.findByUsername( username ).getPassword();
if ( hasher.checkPassword( password, storedHash ) ) {
- reply.roles = new String[] {"ADMIN", "USER"};
+ if ( "system".equals( username ) ) {
+ reply.roles = new String[] {"ADMIN", "USER"};
+ } else {
+ reply.roles = new String[] {"USER"};
+ }
reply.token = token;
}
} catch ( NoResultException e ) {
} catch ( Throwable t ) {
}
- reply.roles = new String[] {"ADMIN", "USER"};
- reply.token = token;
reply( reply );
}
public void handle( UserExistsRequest msg ) throws JMSException {
try {
users.findByUsername( msg.username );
reply( Boolean.TRUE );
} catch ( NoResultException e ) {
reply( Boolean.FALSE );
}
}
public void handle( StoreUserRequest msg ) throws JMSException {
User u = new User(
msg.user.getUsername(),
hasher.hash( msg.user.getPassword() ),
msg.user.getAddress(),
msg.user.getEmail(),
msg.user.getFullname(),
null,
null
);
users.beginTransaction();
users.insert( u );
users.commitTransaction();
reply( Boolean.TRUE );
}
//**** PRIVATE PARTS
private Object getPayload( Message msg ) throws JMSException {
if ( msg instanceof ObjectMessage ) {
return ((ObjectMessage) msg).getObject();
} else if ( msg instanceof TextMessage ) {
return ((TextMessage) msg).getText();
} else {
return msg;
}
}
@EJB
private PersistenceBean persistence;
@Resource(mappedName="swag.JMS")
private ConnectionFactory connectionFactory;
private UserDAO users;
private PasswordHasher hasher;
private Connection connection;
private Session session;
}
| false | true | public void handle( AuthenticationRequest msg ) throws JMSException {
String username = msg.username;
String password = msg.password;
String token = "DUMMY TOKEN";
AuthenticationReply reply = new AuthenticationReply( username, null, null );
try {
String storedHash = users.findByUsername( username ).getPassword();
if ( hasher.checkPassword( password, storedHash ) ) {
reply.roles = new String[] {"ADMIN", "USER"};
reply.token = token;
}
} catch ( NoResultException e ) {
} catch ( Throwable t ) {
}
reply.roles = new String[] {"ADMIN", "USER"};
reply.token = token;
reply( reply );
}
| public void handle( AuthenticationRequest msg ) throws JMSException {
String username = msg.username;
String password = msg.password;
String token = "DUMMY TOKEN";
AuthenticationReply reply = new AuthenticationReply( username, null, null );
try {
String storedHash = users.findByUsername( username ).getPassword();
if ( hasher.checkPassword( password, storedHash ) ) {
if ( "system".equals( username ) ) {
reply.roles = new String[] {"ADMIN", "USER"};
} else {
reply.roles = new String[] {"USER"};
}
reply.token = token;
}
} catch ( NoResultException e ) {
} catch ( Throwable t ) {
}
reply( reply );
}
|
diff --git a/src/main/java/org/lightmare/rest/RestConfig.java b/src/main/java/org/lightmare/rest/RestConfig.java
index 381322d9e..e7b5f6f8f 100644
--- a/src/main/java/org/lightmare/rest/RestConfig.java
+++ b/src/main/java/org/lightmare/rest/RestConfig.java
@@ -1,141 +1,143 @@
package org.lightmare.rest;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.model.Resource;
import org.lightmare.cache.MetaContainer;
import org.lightmare.rest.providers.JacksonFXmlFeature;
import org.lightmare.rest.providers.ObjectMapperProvider;
import org.lightmare.rest.providers.RestReloader;
import org.lightmare.rest.utils.RestUtils;
import org.lightmare.utils.ObjectUtils;
/**
* Dynamically manage REST resources
*
* @author levan
*
*/
public class RestConfig extends ResourceConfig {
private static RestConfig config;
private Set<Resource> preResources;
private RestReloader reloader = RestReloader.get();
public RestConfig() {
super();
register(ObjectMapperProvider.class);
register(JacksonFXmlFeature.class);
synchronized (RestConfig.class) {
if (reloader == null) {
reloader = new RestReloader();
}
this.registerInstances(reloader);
- this.addPreResources(config);
- Map<String, Object> properties = config.getProperties();
- if (ObjectUtils.available(properties)) {
- addProperties(properties);
+ if (ObjectUtils.notNull(config)) {
+ this.addPreResources(config);
+ Map<String, Object> properties = config.getProperties();
+ if (ObjectUtils.available(properties)) {
+ addProperties(properties);
+ }
}
config = this;
}
}
public static RestConfig get() {
synchronized (RestConfig.class) {
return config;
}
}
private void clearResources() {
Set<Resource> resources = getResources();
if (ObjectUtils.available(resources)) {
getResources().clear();
}
}
public void registerAll(RestConfig oldConfig) {
clearResources();
Set<Resource> newResources;
newResources = new HashSet<Resource>();
if (ObjectUtils.notNull(oldConfig)) {
Set<Resource> olds = oldConfig.getResources();
if (ObjectUtils.available(olds)) {
newResources.addAll(olds);
}
}
registerResources(newResources);
}
public void registerClass(Class<?> resourceClass, RestConfig oldConfig)
throws IOException {
Resource.Builder builder = Resource.builder(resourceClass);
Resource preResource = builder.build();
Resource resource = RestUtils.defineHandler(preResource);
addPreResource(resource);
MetaContainer.putResource(resourceClass, resource);
}
public void unregister(Class<?> resourceClass, RestConfig oldConfig) {
Resource resource = MetaContainer.getResource(resourceClass);
removePreResource(resource);
MetaContainer.removeResource(resourceClass);
}
public void addPreResource(Resource resource) {
if (this.preResources == null || this.preResources.isEmpty()) {
this.preResources = new HashSet<Resource>();
}
this.preResources.add(resource);
}
public void removePreResource(Resource resource) {
if (ObjectUtils.available(this.preResources)) {
this.preResources.remove(resource);
}
}
public void addPreResources(Collection<Resource> preResources) {
if (ObjectUtils.available(preResources)) {
if (this.preResources == null || this.preResources.isEmpty()) {
this.preResources = new HashSet<Resource>();
}
this.preResources.addAll(preResources);
}
}
public void addPreResources(RestConfig oldConfig) {
if (ObjectUtils.notNull(oldConfig)) {
addPreResources(oldConfig.getResources());
addPreResources(oldConfig.preResources);
}
}
public void registerPreResources() {
if (ObjectUtils.available(this.preResources)) {
registerResources(preResources);
}
}
}
| true | true | public RestConfig() {
super();
register(ObjectMapperProvider.class);
register(JacksonFXmlFeature.class);
synchronized (RestConfig.class) {
if (reloader == null) {
reloader = new RestReloader();
}
this.registerInstances(reloader);
this.addPreResources(config);
Map<String, Object> properties = config.getProperties();
if (ObjectUtils.available(properties)) {
addProperties(properties);
}
config = this;
}
}
| public RestConfig() {
super();
register(ObjectMapperProvider.class);
register(JacksonFXmlFeature.class);
synchronized (RestConfig.class) {
if (reloader == null) {
reloader = new RestReloader();
}
this.registerInstances(reloader);
if (ObjectUtils.notNull(config)) {
this.addPreResources(config);
Map<String, Object> properties = config.getProperties();
if (ObjectUtils.available(properties)) {
addProperties(properties);
}
}
config = this;
}
}
|
diff --git a/src/main/java/uk/ac/cam/cl/dtg/ldap/LDAPUser.java b/src/main/java/uk/ac/cam/cl/dtg/ldap/LDAPUser.java
index 777f19a..e055454 100644
--- a/src/main/java/uk/ac/cam/cl/dtg/ldap/LDAPUser.java
+++ b/src/main/java/uk/ac/cam/cl/dtg/ldap/LDAPUser.java
@@ -1,192 +1,192 @@
package uk.ac.cam.cl.dtg.ldap;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
/**
* A class containing all data for a particular LDAP queried user
*/
public class LDAPUser extends LDAPObject {
/**
* Fields to cache user data once looked up
*/
private String crsid;
private String regName;
private String displayName;
private String surname;
private String email;
private List<String> instID;
private List<String> institutions;
private List<String> status;
private List<String> photos;
/** Class constructor taking a crsid of the user to lookup **/
LDAPUser(String crsid, String regName, String displayName, String surname, String email, List<String> instID,
List<String> status, List<String> institutions, List<String> photos) {
super();
this.crsid = crsid;
// set default values
this.regName = ifNull(regName, "undefined");
this.displayName = ifNull(displayName, regName);
this.surname = ifNull(surname, "undefined");
this.email = ifNull(email, "undefined");
this.instID = ifNull(instID, Arrays.asList("undefined"));
this.institutions = ifNull(institutions,
Arrays.asList("undefined"));
this.status = ifNull(status, Arrays.asList("undefined"));
this.photos = ifNull(photos, Arrays.asList("undefined"));
- Collections.sort(institutions);
- Collections.sort(instID);
+ Collections.sort(this.institutions);
+ Collections.sort(this.instID);
}
/**
* Get users crsid
*
* @return String crsid
*/
@Override
public String getID() {
return crsid;
}
/**
* Get surname for trie matching
*
* @return String surname
*/
@Override
String getName() {
return surname;
}
/**
* Get users display name, defaults to registered name if not set
*
* @return String registered name
*/
public String getDisplayName() {
return displayName;
}
/**
* Old method to get display name
* @deprecated user {@link getDisplayName()} instead.
*/
@Deprecated
public String getcName() {
return displayName;
}
/**
* Get users registered name
*
* @return String registered name
*/
public String getRegName() {
return regName;
}
/**
* Get users surname
*
* @return String surname
*/
public String getSurname() {
return surname;
}
/**
* Get users email
*
* @return String email
*/
public String getEmail() {
return email;
}
/**
* Get institution id
*
* @return String instID
*/
public List<String> getInstID() {
return instID;
}
/**
* Gets a list of institutions associated with user
*
* @return String status
*/
public List<String> getInstitutions() {
return institutions;
}
/**
* Gets a list of misAffiliations associated with user If 'staff'
* misAffiliations user is present sets status as staff, otherwise student
*
* @return String status
*/
public List<String> getStatus() {
return status;
}
/**
* Gets photo as an encoded base 64 jpeg To display in soy template, use
* <img src="data:image/jpeg;base64,{$user.photo}" /> or similar
*
* @return String photo
*/
public List<String> getPhotos() {
return photos;
}
/**
* Gets cName, surname, email
*
* @return HashMap
*/
public HashMap<String, String> getEssentials() {
HashMap<String, String> data = new HashMap<String, String>();
data.put("crsid", crsid);
data.put("name", regName);
data.put("username", displayName);
data.put("surname", surname);
data.put("email", email);
return data;
}
/**
* Gets cName, surname, email
*
* @return HashMap
*/
public HashMap<String, Object> getAll() {
HashMap<String, Object> data = new HashMap<String, Object>();
data.put("crsid", crsid);
data.put("name", regName);
data.put("username", displayName);
data.put("surname", surname);
data.put("email", email);
data.put("instID", instID);
data.put("institution", institutions);
data.put("status", status.get(0));
data.put("photo", photos.get(0));
return data;
}
}
| true | true | LDAPUser(String crsid, String regName, String displayName, String surname, String email, List<String> instID,
List<String> status, List<String> institutions, List<String> photos) {
super();
this.crsid = crsid;
// set default values
this.regName = ifNull(regName, "undefined");
this.displayName = ifNull(displayName, regName);
this.surname = ifNull(surname, "undefined");
this.email = ifNull(email, "undefined");
this.instID = ifNull(instID, Arrays.asList("undefined"));
this.institutions = ifNull(institutions,
Arrays.asList("undefined"));
this.status = ifNull(status, Arrays.asList("undefined"));
this.photos = ifNull(photos, Arrays.asList("undefined"));
Collections.sort(institutions);
Collections.sort(instID);
}
| LDAPUser(String crsid, String regName, String displayName, String surname, String email, List<String> instID,
List<String> status, List<String> institutions, List<String> photos) {
super();
this.crsid = crsid;
// set default values
this.regName = ifNull(regName, "undefined");
this.displayName = ifNull(displayName, regName);
this.surname = ifNull(surname, "undefined");
this.email = ifNull(email, "undefined");
this.instID = ifNull(instID, Arrays.asList("undefined"));
this.institutions = ifNull(institutions,
Arrays.asList("undefined"));
this.status = ifNull(status, Arrays.asList("undefined"));
this.photos = ifNull(photos, Arrays.asList("undefined"));
Collections.sort(this.institutions);
Collections.sort(this.instID);
}
|
diff --git a/src/kodkod/engine/bool/BinaryInt.java b/src/kodkod/engine/bool/BinaryInt.java
index f58a160..2eaafdf 100644
--- a/src/kodkod/engine/bool/BinaryInt.java
+++ b/src/kodkod/engine/bool/BinaryInt.java
@@ -1,525 +1,525 @@
/*
* Kodkod -- Copyright (c) 2005-2007, Emina Torlak
*
* 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 kodkod.engine.bool;
import static kodkod.engine.bool.BooleanConstant.FALSE;
import static kodkod.engine.bool.BooleanConstant.TRUE;
import java.util.Arrays;
/**
* Two's complement integer representation. Supports comparisons, addition and subtraction.
* Integers are represented in little-endian (least significant bit first) order.
* @author Emina Torlak
*/
final class BinaryInt extends Int {
private final BooleanValue[] bits;
/**
* Constructs a BinaryInt out of the given factory and bits.
* @requires bits is well formed
* @effects this.factory' = factory && this.bits' = bits
*/
private BinaryInt(BooleanFactory factory, BooleanValue[] bits) {
super(factory);
this.bits = bits;
}
/**
* Constructs a BinaryInt that represents either 0 or the given number, depending on
* the value of the given bit.
* @requires factory.encoding = BINARY && bit in factory.components
* @effects this.factory' = factory
* @effects bits is a two's-complement representation of the given number
* that uses the provided bit in place of 1's
*/
BinaryInt(BooleanFactory factory, int number, BooleanValue bit) {
super(factory);
final int width = bitwidth(number);
this.bits = new BooleanValue[width];
for(int i = 0; i < width; i++) {
bits[i] = (number & (1<<i)) == 0 ? FALSE : bit;
}
}
/**
* Returns the number of bits needed/allowed to represent the given number.
* @return the number of bits needed/allowed to represent the given number.
*/
private int bitwidth(int number) {
if (number > 0)
return StrictMath.min(33 - Integer.numberOfLeadingZeros(number), factory.bitwidth);
else if (number < 0)
return StrictMath.min(33 - Integer.numberOfLeadingZeros(~number), factory.bitwidth);
else // number = 0
return 1;
}
/**
* {@inheritDoc}
* @see kodkod.engine.bool.Int#width()
*/
@Override
public int width() {
return bits.length;
}
/**
* {@inheritDoc}
* @see kodkod.engine.bool.Int#value()
*/
public final int value() {
int ret = 0;
final int max = bits.length-1;
for(int i = 0; i < max; i++) {
if (bits[i]==TRUE) ret += 1<<i;
else if (bits[i]!=FALSE)
throw new IllegalStateException(this + " is not constant.");
}
if (bits[max]==TRUE) ret -= 1<<max;
else if (bits[max]!=FALSE)
throw new IllegalStateException(this + " is not constant.");
return ret;
}
/**
* {@inheritDoc}
* @see kodkod.engine.bool.Int#bit(int)
*/
@Override
public BooleanValue bit(int i) {
return bits[StrictMath.min(i, bits.length-1)];
}
/**
* {@inheritDoc}
* @see kodkod.engine.bool.Int#lte(kodkod.engine.bool.Int)
*/
@Override
public BooleanValue lte(Int other) {
validate(other);
final BooleanAccumulator cmp = BooleanAccumulator.treeGate(Operator.AND);
final int last = StrictMath.max(width(), other.width())-1;
cmp.add(factory.implies(other.bit(last), bit(last)));
BooleanValue prevEquals = factory.iff(bit(last), other.bit(last));
for(int i = last-1; i >= 0; i--) {
BooleanValue v0 = bit(i), v1 = other.bit(i);
cmp.add(factory.implies(prevEquals, factory.implies(v0, v1)));
prevEquals = factory.and(prevEquals, factory.iff(v0, v1));
}
return factory.accumulate(cmp);
}
/**
* {@inheritDoc}
* @see kodkod.engine.bool.Int#plus(kodkod.engine.bool.Int)
*/
@Override
public Int plus(Int other) {
validate(other);
final int width = StrictMath.min(StrictMath.max(width(), other.width()) + 1, factory.bitwidth);
final BooleanValue[] plus = new BooleanValue[width];
BooleanValue carry = FALSE;
for(int i = 0; i < width; i++) {
BooleanValue v0 = bit(i), v1 = other.bit(i);
plus[i] = factory.sum(v0, v1, carry);
carry = factory.carry(v0, v1, carry);
}
return new BinaryInt(factory, plus);
}
/**
* {@inheritDoc}
* @see kodkod.engine.bool.Int#minus(kodkod.engine.bool.Int)
*/
@Override
public Int minus(Int other) {
validate(other);
final int width = StrictMath.min(StrictMath.max(width(), other.width()) + 1, factory.bitwidth);
final BooleanValue[] minus = new BooleanValue[width];
BooleanValue carry = TRUE;
for(int i = 0; i < width; i++) {
BooleanValue v0 = bit(i), v1 = other.bit(i).negation();
minus[i] = factory.sum(v0, v1, carry);
carry = factory.carry(v0, v1, carry);
}
return new BinaryInt(factory, minus);
}
/**
* Adds the newBit and the given carry to this.bits[index] and returns the new carry.
* @requires 0 <= index < this.width
* @effects this.bits'[index] = this.factory.sum(this.bits[index], newBit, cin)
* @return this.factory.carry(this.bits[index], newBit, cin)
*/
private BooleanValue addAndCarry(int index, BooleanValue newBit, BooleanValue cin) {
BooleanValue oldBit = bits[index];
bits[index] = factory.sum(oldBit, newBit, cin);
return factory.carry(oldBit, newBit, cin);
}
/**
* {@inheritDoc}
* @see kodkod.engine.bool.Int#multiply(kodkod.engine.bool.Int)
*/
@Override
public Int multiply(Int other) {
validate(other);
final int width = StrictMath.min(width()+other.width(), factory.bitwidth);
final BooleanValue[] mult = new BooleanValue[width];
final BinaryInt ret = new BinaryInt(factory, mult);
/* first partial sum */
BooleanValue iBit = bit(0), carry;
for(int j = 0; j < width; j++) {
mult[j] = factory.and(iBit, other.bit(j));
}
final int last = width-1;
/* intermediate partial sums */
for(int i = 1; i < last; i++) {
carry = FALSE;
iBit = bit(i);
for(int j = 0, jmax = width-i; j < jmax; j++) {
carry = ret.addAndCarry(j+i, factory.and(iBit, other.bit(j)), carry);
}
}
/* last partial sum is subtracted (see http://en.wikipedia.org/wiki/Multiplication_ALU) */
ret.addAndCarry(last, factory.and(this.bit(last), other.bit(0)).negation(), TRUE);
// System.out.println("this.width="+width() + ", other.width=" + other.width() + ", ret.width=" + width);
//System.out.println(ret);
return ret;
}
/**
* Returns an array of BooleanValues that represents the same
* integer as this, but using extwidth bits.
* @requires extwidth >= this.width()
* @return an array of BooleanValues that represents the same
* integer as this, but using extwidth bits.
*/
private BooleanValue[] extend(int extwidth) {
final BooleanValue[] ext = new BooleanValue[extwidth];
final int width = width();
for(int i = 0; i < width; i++) {
ext[i] = bits[i];
}
final BooleanValue sign = bits[width-1];
for(int i = width; i < extwidth; i++) {
ext[i] = sign;
}
return ext;
}
/**
* Performs non-restoring signed division of this and the given integer. Returns
* the this.factory.bitwidth low-order bits of the quotient if the quotient flag
* is true; otherwise returns the this.factory.bitwidth low-order bits of the remainder.
* Both the quotionent and the remainder are given in little endian format.
* @see Behrooz Parhami, Computer Arithmetic: Algorithms and Hardware Designs,
* Oxford University Press, 2000, pp. 218-221.
* @requires this.factory = d.factory && d instanceof BinaryInt
* @return an array of boolean values, as described above
*/
private BooleanValue[] nonRestoringDivision(Int d, boolean quotient) {
final int width = factory.bitwidth, extended = width*2 + 1;
// extend the dividend to bitwidth*2 + 1 and store it in s; the quotient will have width digits
final BooleanValue[] s = this.extend(extended), q = new BooleanValue[width];
// detects if one of the intermediate remainders is zero
final BooleanValue[] svalues = new BooleanValue[width];
BooleanValue carry, sbit, qbit, dbit;
// the sign bit of the divisor
final BooleanValue dMSB = d.bit(width);
int sleft = 0; // the index which contains the LSB of s
for(int i = 0; i < width; i++) {
svalues[i] = factory.accumulate(BooleanAccumulator.treeGate(Operator.OR, s));
int sright = (sleft + extended - 1) % extended; // the index which contains the MSB of s
// q[width-i-1] is 1 if sign(s_(i)) = sign(d), otherwise it is 0
qbit = factory.iff(s[sright], dMSB);
q[width-i-1] = qbit;
// shift s to the left by 1 -- simulated by setting sright to FALSE and sleft to sright
s[sright] = FALSE;
sleft = sright;
// if sign(s_(i)) = sign(d), form s_(i+1) by subtracting (2^width)d from s_(i);
// otherwise, form s_(i+1) by adding (2^width)d to s_(i).
carry = qbit;
for(int di = 0, si = (sleft+width) % extended; di <= width; di++, si = (si+1) % extended) {
dbit = factory.xor(qbit, d.bit(di));
sbit = s[si];
s[si] = factory.sum(sbit, dbit, carry);
carry = factory.carry(sbit, dbit, carry);
}
}
// s[0..width] holds the width+1 high order bits of s
- assert (sleft+width) % extended != 0 ;
+ assert (sleft+width) % extended == 0 ;
// correction needed if one of the intermediate remainders is zero
// or s is non-zero and its sign differs from the sign of the dividend
final BooleanValue incorrect = factory.or(
factory.not(factory.accumulate(BooleanAccumulator.treeGate(Operator.AND, svalues))),
factory.and(factory.xor(s[width], this.bit(width)),
factory.accumulate(BooleanAccumulator.treeGate(Operator.OR, s))));
final BooleanValue corrector = factory.iff(s[width], d.bit(width));
if (quotient) { // convert q to 2's complement, correct it if s is nonzero, and return
// convert q to 2's complement: shift to the left by 1 and set LSB to TRUE
System.arraycopy(q, 0, q, 1, width-1);
q[0] = TRUE;
// correct if incorrect evaluates to true as follows: if corrector evaluates to true,
// increment q; otherwise decrement q.
final BooleanValue sign = factory.and(incorrect, factory.not(corrector));
carry = factory.and(incorrect, corrector);
for(int i = 0; i < width; i++) {
qbit = q[i];
q[i] = factory.sum(qbit, sign, carry);
carry = factory.carry(qbit, sign, carry);
}
return q;
} else { // correct s if non-zero and return
// correct if incorrect evaluates to true as follows: if corrector evaluates to true,
// subtract (2^width)d from s; otherwise add (2^width)d to s
carry = factory.and(incorrect, corrector);
for(int i = 0; i <= width; i++) {
dbit = factory.and(incorrect, factory.xor(corrector, d.bit(i)));
sbit = s[i];
s[i] = factory.sum(sbit, dbit, carry);
carry = factory.carry(sbit, dbit, carry);
}
final BooleanValue[] r = new BooleanValue[width];
System.arraycopy(s, 0, r, 0, width);
return r;
}
}
/**
* {@inheritDoc}
* @see kodkod.engine.bool.Int#divide(kodkod.engine.bool.Int)
*/
@Override
public Int divide(Int other) {
validate(other);
return new BinaryInt(factory, nonRestoringDivision(other, true));
}
/**
* {@inheritDoc}
* @see kodkod.engine.bool.Int#modulo(kodkod.engine.bool.Int)
*/
@Override
public Int modulo(Int other) {
validate(other);
return new BinaryInt(factory, nonRestoringDivision(other, false));
}
/**
* {@inheritDoc}
* @see kodkod.engine.bool.Int#choice(kodkod.engine.bool.BooleanValue, kodkod.engine.bool.Int)
*/
@Override
public Int choice(BooleanValue condition, Int other) {
validate(other);
final int width = StrictMath.max(width(), other.width());
final BooleanValue[] choice = new BooleanValue[width];
for(int i = 0; i < width; i++) {
choice[i] = factory.ite(condition, bit(i), other.bit(i));
}
return new BinaryInt(factory, choice);
}
/**
* {@inheritDoc}
* @see kodkod.engine.bool.Int#and(kodkod.engine.bool.Int)
*/
@Override
public Int and(Int other) {
validate(other);
final int width = StrictMath.max(width(), other.width());
final BooleanValue[] and = new BooleanValue[width];
for(int i = 0; i < width; i++) {
and[i] = factory.and(bit(i), other.bit(i));
}
return new BinaryInt(factory, and);
}
/**
* {@inheritDoc}
* @see kodkod.engine.bool.Int#or(kodkod.engine.bool.Int)
*/
@Override
public Int or(Int other) {
validate(other);
final int width = StrictMath.max(width(), other.width());
final BooleanValue[] or = new BooleanValue[width];
for(int i = 0; i < width; i++) {
or[i] = factory.or(bit(i), other.bit(i));
}
return new BinaryInt(factory, or);
}
/**
* {@inheritDoc}
* @see kodkod.engine.bool.Int#xor(kodkod.engine.bool.Int)
*/
@Override
public Int xor(Int other) {
validate(other);
final int width = StrictMath.max(width(), other.width());
final BooleanValue[] xor = new BooleanValue[width];
for(int i = 0; i < width; i++) {
xor[i] = factory.xor(bit(i), other.bit(i));
}
return new BinaryInt(factory,xor);
}
/**
* {@inheritDoc}
* @see kodkod.engine.bool.Int#shl(kodkod.engine.bool.Int)
*/
@Override
public Int shl(Int other) {
validate(other);
final int width = factory.bitwidth;
final BinaryInt shifted = new BinaryInt(factory, extend(width));
final int max = 32 - Integer.numberOfLeadingZeros(width - 1);
for(int i = 0; i < max; i++) {
int shift = 1 << i;
BooleanValue bit = other.bit(i);
for(int j = width-1; j >= 0; j--) {
shifted.bits[j] = factory.ite(bit, j < shift ? FALSE : shifted.bit(j-shift), shifted.bits[j]);
}
}
return shifted;
}
/**
* Performs a right shift with the given extension.
*/
private Int shr(Int other, BooleanValue sign) {
validate(other);
final int width = factory.bitwidth;
final BinaryInt shifted = new BinaryInt(factory, extend(width));
final int max = 32 - Integer.numberOfLeadingZeros(width - 1);
for(int i = 0; i < max; i++) {
int shift = 1 << i;
int fill = width - shift;
BooleanValue bit = other.bit(i);
for(int j = 0; j < width; j++) {
shifted.bits[j] = factory.ite(bit, j < fill ? shifted.bit(j+shift) : sign, shifted.bits[j]);
}
}
return shifted;
}
/**
* {@inheritDoc}
* @see kodkod.engine.bool.Int#shr(kodkod.engine.bool.Int)
*/
@Override
public Int shr(Int other) {
return shr(other, FALSE);
}
/**
* {@inheritDoc}
* @see kodkod.engine.bool.Int#sha(kodkod.engine.bool.Int)
*/
@Override
public Int sha(Int other) {
return shr(other, bits[bits.length-1]);
}
/**
* {@inheritDoc}
* @see kodkod.engine.bool.Int#negate()
*/
@Override
public Int negate() {
return (new BinaryInt(factory, new BooleanValue[]{FALSE})).minus(this);
}
/**
* {@inheritDoc}
* @see kodkod.engine.bool.Int#not()
*/
@Override
public Int not() {
final int width = width();
final BooleanValue[] inverse = new BooleanValue[width];
for(int i = 0 ; i < width; i++) {
inverse[i] = factory.not(bits[i]);
}
return new BinaryInt(factory, inverse);
}
/**
* {@inheritDoc}
* @see kodkod.engine.bool.Int#abs()
*/
@Override
public Int abs() {
return choice(factory.not(bits[bits.length-1]), negate());
}
/**
* {@inheritDoc}
* @see kodkod.engine.bool.Int#sgn()
*/
@Override
public Int sgn() {
final BooleanValue[] sgn = new BooleanValue[2];
sgn[0] = factory.accumulate(BooleanAccumulator.treeGate(Operator.OR, bits));
sgn[1] = bits[bits.length-1];
return new BinaryInt(factory, sgn);
}
/**
* {@inheritDoc}
* @see java.lang.Object#toString()
*/
public String toString() {
return "b" + Arrays.toString(bits);
}
}
| true | true | private BooleanValue[] nonRestoringDivision(Int d, boolean quotient) {
final int width = factory.bitwidth, extended = width*2 + 1;
// extend the dividend to bitwidth*2 + 1 and store it in s; the quotient will have width digits
final BooleanValue[] s = this.extend(extended), q = new BooleanValue[width];
// detects if one of the intermediate remainders is zero
final BooleanValue[] svalues = new BooleanValue[width];
BooleanValue carry, sbit, qbit, dbit;
// the sign bit of the divisor
final BooleanValue dMSB = d.bit(width);
int sleft = 0; // the index which contains the LSB of s
for(int i = 0; i < width; i++) {
svalues[i] = factory.accumulate(BooleanAccumulator.treeGate(Operator.OR, s));
int sright = (sleft + extended - 1) % extended; // the index which contains the MSB of s
// q[width-i-1] is 1 if sign(s_(i)) = sign(d), otherwise it is 0
qbit = factory.iff(s[sright], dMSB);
q[width-i-1] = qbit;
// shift s to the left by 1 -- simulated by setting sright to FALSE and sleft to sright
s[sright] = FALSE;
sleft = sright;
// if sign(s_(i)) = sign(d), form s_(i+1) by subtracting (2^width)d from s_(i);
// otherwise, form s_(i+1) by adding (2^width)d to s_(i).
carry = qbit;
for(int di = 0, si = (sleft+width) % extended; di <= width; di++, si = (si+1) % extended) {
dbit = factory.xor(qbit, d.bit(di));
sbit = s[si];
s[si] = factory.sum(sbit, dbit, carry);
carry = factory.carry(sbit, dbit, carry);
}
}
// s[0..width] holds the width+1 high order bits of s
assert (sleft+width) % extended != 0 ;
// correction needed if one of the intermediate remainders is zero
// or s is non-zero and its sign differs from the sign of the dividend
final BooleanValue incorrect = factory.or(
factory.not(factory.accumulate(BooleanAccumulator.treeGate(Operator.AND, svalues))),
factory.and(factory.xor(s[width], this.bit(width)),
factory.accumulate(BooleanAccumulator.treeGate(Operator.OR, s))));
final BooleanValue corrector = factory.iff(s[width], d.bit(width));
if (quotient) { // convert q to 2's complement, correct it if s is nonzero, and return
// convert q to 2's complement: shift to the left by 1 and set LSB to TRUE
System.arraycopy(q, 0, q, 1, width-1);
q[0] = TRUE;
// correct if incorrect evaluates to true as follows: if corrector evaluates to true,
// increment q; otherwise decrement q.
final BooleanValue sign = factory.and(incorrect, factory.not(corrector));
carry = factory.and(incorrect, corrector);
for(int i = 0; i < width; i++) {
qbit = q[i];
q[i] = factory.sum(qbit, sign, carry);
carry = factory.carry(qbit, sign, carry);
}
return q;
} else { // correct s if non-zero and return
// correct if incorrect evaluates to true as follows: if corrector evaluates to true,
// subtract (2^width)d from s; otherwise add (2^width)d to s
carry = factory.and(incorrect, corrector);
for(int i = 0; i <= width; i++) {
dbit = factory.and(incorrect, factory.xor(corrector, d.bit(i)));
sbit = s[i];
s[i] = factory.sum(sbit, dbit, carry);
carry = factory.carry(sbit, dbit, carry);
}
final BooleanValue[] r = new BooleanValue[width];
System.arraycopy(s, 0, r, 0, width);
return r;
}
}
| private BooleanValue[] nonRestoringDivision(Int d, boolean quotient) {
final int width = factory.bitwidth, extended = width*2 + 1;
// extend the dividend to bitwidth*2 + 1 and store it in s; the quotient will have width digits
final BooleanValue[] s = this.extend(extended), q = new BooleanValue[width];
// detects if one of the intermediate remainders is zero
final BooleanValue[] svalues = new BooleanValue[width];
BooleanValue carry, sbit, qbit, dbit;
// the sign bit of the divisor
final BooleanValue dMSB = d.bit(width);
int sleft = 0; // the index which contains the LSB of s
for(int i = 0; i < width; i++) {
svalues[i] = factory.accumulate(BooleanAccumulator.treeGate(Operator.OR, s));
int sright = (sleft + extended - 1) % extended; // the index which contains the MSB of s
// q[width-i-1] is 1 if sign(s_(i)) = sign(d), otherwise it is 0
qbit = factory.iff(s[sright], dMSB);
q[width-i-1] = qbit;
// shift s to the left by 1 -- simulated by setting sright to FALSE and sleft to sright
s[sright] = FALSE;
sleft = sright;
// if sign(s_(i)) = sign(d), form s_(i+1) by subtracting (2^width)d from s_(i);
// otherwise, form s_(i+1) by adding (2^width)d to s_(i).
carry = qbit;
for(int di = 0, si = (sleft+width) % extended; di <= width; di++, si = (si+1) % extended) {
dbit = factory.xor(qbit, d.bit(di));
sbit = s[si];
s[si] = factory.sum(sbit, dbit, carry);
carry = factory.carry(sbit, dbit, carry);
}
}
// s[0..width] holds the width+1 high order bits of s
assert (sleft+width) % extended == 0 ;
// correction needed if one of the intermediate remainders is zero
// or s is non-zero and its sign differs from the sign of the dividend
final BooleanValue incorrect = factory.or(
factory.not(factory.accumulate(BooleanAccumulator.treeGate(Operator.AND, svalues))),
factory.and(factory.xor(s[width], this.bit(width)),
factory.accumulate(BooleanAccumulator.treeGate(Operator.OR, s))));
final BooleanValue corrector = factory.iff(s[width], d.bit(width));
if (quotient) { // convert q to 2's complement, correct it if s is nonzero, and return
// convert q to 2's complement: shift to the left by 1 and set LSB to TRUE
System.arraycopy(q, 0, q, 1, width-1);
q[0] = TRUE;
// correct if incorrect evaluates to true as follows: if corrector evaluates to true,
// increment q; otherwise decrement q.
final BooleanValue sign = factory.and(incorrect, factory.not(corrector));
carry = factory.and(incorrect, corrector);
for(int i = 0; i < width; i++) {
qbit = q[i];
q[i] = factory.sum(qbit, sign, carry);
carry = factory.carry(qbit, sign, carry);
}
return q;
} else { // correct s if non-zero and return
// correct if incorrect evaluates to true as follows: if corrector evaluates to true,
// subtract (2^width)d from s; otherwise add (2^width)d to s
carry = factory.and(incorrect, corrector);
for(int i = 0; i <= width; i++) {
dbit = factory.and(incorrect, factory.xor(corrector, d.bit(i)));
sbit = s[i];
s[i] = factory.sum(sbit, dbit, carry);
carry = factory.carry(sbit, dbit, carry);
}
final BooleanValue[] r = new BooleanValue[width];
System.arraycopy(s, 0, r, 0, width);
return r;
}
}
|
diff --git a/src/main/java/de/cismet/cids/custom/reports/wunda_blau/MauernReportBeanWithMapAndImages.java b/src/main/java/de/cismet/cids/custom/reports/wunda_blau/MauernReportBeanWithMapAndImages.java
index 14189301..f839620f 100644
--- a/src/main/java/de/cismet/cids/custom/reports/wunda_blau/MauernReportBeanWithMapAndImages.java
+++ b/src/main/java/de/cismet/cids/custom/reports/wunda_blau/MauernReportBeanWithMapAndImages.java
@@ -1,371 +1,371 @@
/***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package de.cismet.cids.custom.reports.wunda_blau;
import com.vividsolutions.jts.geom.Geometry;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.net.URL;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageInputStreamImpl;
import javax.swing.ImageIcon;
import de.cismet.cids.custom.objectrenderer.utils.CidsBeanSupport;
import de.cismet.cids.dynamics.CidsBean;
import de.cismet.cismap.commons.BoundingBox;
import de.cismet.cismap.commons.Crs;
import de.cismet.cismap.commons.XBoundingBox;
import de.cismet.cismap.commons.features.DefaultStyledFeature;
import de.cismet.cismap.commons.gui.MappingComponent;
import de.cismet.cismap.commons.gui.layerwidget.ActiveLayerModel;
import de.cismet.cismap.commons.raster.wms.simple.SimpleWMS;
import de.cismet.cismap.commons.raster.wms.simple.SimpleWmsGetMapUrl;
import de.cismet.cismap.commons.retrieval.RetrievalEvent;
import de.cismet.cismap.commons.retrieval.RetrievalListener;
import de.cismet.netutil.Proxy;
import de.cismet.security.WebDavClient;
import de.cismet.tools.CismetThreadPool;
import de.cismet.tools.PasswordEncrypter;
/**
* DOCUMENT ME!
*
* @author daniel
* @version $Revision$, $Date$
*/
public class MauernReportBeanWithMapAndImages extends MauernReportBean {
//~ Static fields/initializers ---------------------------------------------
private static final transient org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(
MauernReportBeanWithMapAndImages.class);
private static String WEB_DAV_DIRECTORY;
private static String WEB_DAV_USER;
private static String WEB_DAV_PASSWORD;
//~ Instance fields --------------------------------------------------------
Image mapImage = null;
Image img0 = null;
Image img1 = null;
private final WebDavClient webDavClient;
private boolean proceed = false;
private boolean mapError = false;
private boolean image0Error = false;
private boolean image1Error = false;
private String masstab = "";
//~ Constructors -----------------------------------------------------------
/**
* Creates a new MauernBeanWithMapAndImages object.
*
* @param mauer DOCUMENT ME!
*/
public MauernReportBeanWithMapAndImages(final CidsBean mauer) {
super(mauer);
final ResourceBundle bundle = ResourceBundle.getBundle("WebDav");
String pass = bundle.getString("password");
if ((pass != null) && pass.startsWith(PasswordEncrypter.CRYPT_PREFIX)) {
pass = PasswordEncrypter.decryptString(pass);
}
WEB_DAV_PASSWORD = pass;
WEB_DAV_USER = bundle.getString("user");
WEB_DAV_DIRECTORY = bundle.getString("url");
this.webDavClient = new WebDavClient(Proxy.fromPreferences(), WEB_DAV_USER, WEB_DAV_PASSWORD, true);
final ArrayList al = new ArrayList();
// final SimpleWMS s = new SimpleWMS(new SimpleWmsGetMapUrl("http://www.wms.nrw.de/geobasis/DOP?&VERSION=1.1.1&REQUEST=GetMap&WIDTH=<cismap:width>&HEIGHT=<cismap:height>&BBOX=<cismap:boundingBox>&SRS=EPSG:25832&FORMAT=image/png&TRANSPARENT=TRUE&BGCOLOR=0xF0F0F0&EXCEPTIONS=application/vnd.ogc.se_xml&LAYERS=WMS,0,Metadaten&STYLES="));
final SimpleWMS s = new SimpleWMS(new SimpleWmsGetMapUrl(
"http://s102x284:8399/arcgis/services/WuNDa-Orthophoto-WUP/MapServer/WMSServer?service=WMS&VERSION=1.1.1&REQUEST=GetMap&WIDTH=<cismap:width>&HEIGHT=<cismap:height>&BBOX=<cismap:boundingBox>&SRS=EPSG:25832&FORMAT=image/png&TRANSPARENT=TRUE&BGCOLOR=0xF0F0F0&EXCEPTIONS=application/vnd.ogc.se_xml&LAYERS=6&STYLES=default"));
// final SimpleWMS s = new SimpleWMS(new SimpleWmsGetMapUrl(
// "http://S102X284:8399/arcgis/services/ALKIS-EXPRESS/MapServer/WMSServer?&VERSION=1.1.1&REQUEST=GetMap&FORMAT=image/png&TRANSPARENT=FALSE&BGCOLOR=0xF0F0F0&EXCEPTIONS=application/vnd.ogc.se_xml&LAYERS=2,4,5,6,7,8,10,11,12,13,14,16,17,18,19,20,21,22,23,25,26,27,28,29,30,31,32,33,34,35,36,37,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100&STYLES=&BBOX=<cismap:boundingBox>&WIDTH=<cismap:width>&HEIGHT=<cismap:height>&SRS="));
final MappingComponent map = new MappingComponent(false);
final ActiveLayerModel mappingModel = new ActiveLayerModel();
s.addRetrievalListener(new RetrievalListener() {
@Override
public void retrievalStarted(final RetrievalEvent e) {
System.out.println("Start");
}
@Override
public void retrievalProgress(final RetrievalEvent e) {
}
@Override
public void retrievalComplete(final RetrievalEvent e) {
new Thread() {
@Override
public void run() {
try {
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
}
final java.awt.Image img = map.getCamera()
.toImage(map.getWidth(), map.getHeight(), new Color(255, 255, 255, 0));
final BufferedImage bi = new BufferedImage(
img.getWidth(null),
img.getHeight(null),
BufferedImage.TYPE_INT_RGB);
final Graphics2D g2 = bi.createGraphics();
// Draw img into bi so we can write it to file.
g2.drawImage(img, 0, 0, null);
g2.dispose();
final BoundingBox bb = map.getCurrentBoundingBox();
final String geolink = "http://localhost:" + 9098 + "/gotoBoundingBox?x1=" + bb.getX1()
+ "&y1=" + bb.getY1() + "&x2=" + bb.getX2() + "&y2=" + bb.getY2(); // NOI18N
mapImage = bi;
System.out.println("karte geladen " + bi);
} catch (Exception ex) {
Exceptions.printStackTrace(ex);
}
}
}.start();
}
@Override
public void retrievalAborted(final RetrievalEvent e) {
mapError = true;
}
@Override
public void retrievalError(final RetrievalEvent e) {
mapError = true;
}
});
// disable internal layer widget
map.setInternalLayerWidgetAvailable(false);
mappingModel.setSrs(new Crs("EPSG:25832", "", "", true, true));
mappingModel.addHome(new XBoundingBox(
374271.251964098,
5681514.032498134,
374682.9413952776,
5681773.852810634,
"EPSG:25832",
true));
// set the model
map.setMappingModel(mappingModel);
final int height = Integer.parseInt(NbBundle.getMessage(
MauernReportBeanWithMapAndImages.class,
"MauernReportBeanWithMapAndImages.mapHeight"));
final int width = Integer.parseInt(NbBundle.getMessage(
MauernReportBeanWithMapAndImages.class,
"MauernReportBeanWithMapAndImages.mapWidth"));
map.setSize(width, height);
// map.setSize(540, 219);
// initial positioning of the map
map.setAnimationDuration(0);
map.gotoInitialBoundingBox();
map.unlock();
final Geometry g = (Geometry)mauer.getProperty("georeferenz.geo_field");
final DefaultStyledFeature dsf = new DefaultStyledFeature();
dsf.setGeometry(g);
dsf.setLineWidth(5);
dsf.setLinePaint(Color.RED);
map.getFeatureCollection().addFeature(dsf);
map.zoomToFeatureCollection();
double scale;
if (map.getScaleDenominator() >= 100) {
- scale = Math.floor(map.getScaleDenominator() / 100) * 100;
+ scale = Math.round((map.getScaleDenominator() / 100) + 0.5d) * 100;
} else {
- scale = Math.floor(map.getScaleDenominator() / 10) * 10;
+ scale = Math.round((map.getScaleDenominator() / 10) + 0.5) * 10;
}
masstab = "1:" + NumberFormat.getIntegerInstance().format(scale);
if (LOG.isDebugEnabled()) {
LOG.debug("Scale for katasterblatt: " + masstab);
}
map.gotoBoundingBoxWithHistory(map.getBoundingBoxFromScale(scale));
map.setInteractionMode(MappingComponent.SELECT);
mappingModel.addLayer(s);
// TODO set correct url
final List<CidsBean> images = CidsBeanSupport.getBeanCollectionFromProperty(mauer, "bilder");
final StringBuilder url0Builder = new StringBuilder();
final StringBuilder url1Builder = new StringBuilder();
for (final CidsBean b : images) {
final Integer nr = (Integer)b.getProperty("laufende_nummer");
if (nr == 1) {
url0Builder.append(b.getProperty("url").toString());
} else if (nr == 2) {
url1Builder.append(b.getProperty("url").toString());
}
}
CismetThreadPool.execute(new Runnable() {
@Override
public void run() {
try {
if (url0Builder.toString().equals("")) {
image0Error = true;
return;
}
final InputStream iStream = webDavClient.getInputStream(
url0Builder.toString());
img0 = ImageIO.read(iStream);
if (img0 == null) {
image0Error = true;
LOG.warn("error during image retrieval from Webdav");
}
System.out.println(img0);
} catch (Exception e) {
image0Error = true;
}
}
});
CismetThreadPool.execute(new Runnable() {
@Override
public void run() {
try {
if (url1Builder.toString().equals("")) {
image1Error = true;
return;
}
final InputStream iStream = webDavClient.getInputStream(
url1Builder.toString());
img1 = ImageIO.read(iStream);
if (img1 == null) {
image1Error = true;
LOG.warn("error during image retrieval from Webdav");
}
System.out.println(img1);
} catch (Exception e) {
image1Error = true;
}
}
});
}
//~ Methods ----------------------------------------------------------------
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public Image getImg0() {
return img0;
}
/**
* DOCUMENT ME!
*
* @param img0 DOCUMENT ME!
*/
public void setImg0(final Image img0) {
this.img0 = img0;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public Image getImg1() {
return img1;
}
/**
* DOCUMENT ME!
*
* @param img1 DOCUMENT ME!
*/
public void setImg1(final Image img1) {
this.img1 = img1;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public Image getMapImage() {
return mapImage;
}
/**
* DOCUMENT ME!
*
* @param mapImage DOCUMENT ME!
*/
public void setMapImage(final Image mapImage) {
this.mapImage = mapImage;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public String getMasstab() {
return masstab;
}
/**
* DOCUMENT ME!
*
* @param masstab DOCUMENT ME!
*/
public void setMasstab(final String masstab) {
this.masstab = masstab;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
@Override
public boolean isReadyToProceed() {
return ((mapImage != null) || mapError)
&& ((img0 != null) || image0Error)
&& ((img1 != null) || image1Error);
}
}
| false | true | public MauernReportBeanWithMapAndImages(final CidsBean mauer) {
super(mauer);
final ResourceBundle bundle = ResourceBundle.getBundle("WebDav");
String pass = bundle.getString("password");
if ((pass != null) && pass.startsWith(PasswordEncrypter.CRYPT_PREFIX)) {
pass = PasswordEncrypter.decryptString(pass);
}
WEB_DAV_PASSWORD = pass;
WEB_DAV_USER = bundle.getString("user");
WEB_DAV_DIRECTORY = bundle.getString("url");
this.webDavClient = new WebDavClient(Proxy.fromPreferences(), WEB_DAV_USER, WEB_DAV_PASSWORD, true);
final ArrayList al = new ArrayList();
// final SimpleWMS s = new SimpleWMS(new SimpleWmsGetMapUrl("http://www.wms.nrw.de/geobasis/DOP?&VERSION=1.1.1&REQUEST=GetMap&WIDTH=<cismap:width>&HEIGHT=<cismap:height>&BBOX=<cismap:boundingBox>&SRS=EPSG:25832&FORMAT=image/png&TRANSPARENT=TRUE&BGCOLOR=0xF0F0F0&EXCEPTIONS=application/vnd.ogc.se_xml&LAYERS=WMS,0,Metadaten&STYLES="));
final SimpleWMS s = new SimpleWMS(new SimpleWmsGetMapUrl(
"http://s102x284:8399/arcgis/services/WuNDa-Orthophoto-WUP/MapServer/WMSServer?service=WMS&VERSION=1.1.1&REQUEST=GetMap&WIDTH=<cismap:width>&HEIGHT=<cismap:height>&BBOX=<cismap:boundingBox>&SRS=EPSG:25832&FORMAT=image/png&TRANSPARENT=TRUE&BGCOLOR=0xF0F0F0&EXCEPTIONS=application/vnd.ogc.se_xml&LAYERS=6&STYLES=default"));
// final SimpleWMS s = new SimpleWMS(new SimpleWmsGetMapUrl(
// "http://S102X284:8399/arcgis/services/ALKIS-EXPRESS/MapServer/WMSServer?&VERSION=1.1.1&REQUEST=GetMap&FORMAT=image/png&TRANSPARENT=FALSE&BGCOLOR=0xF0F0F0&EXCEPTIONS=application/vnd.ogc.se_xml&LAYERS=2,4,5,6,7,8,10,11,12,13,14,16,17,18,19,20,21,22,23,25,26,27,28,29,30,31,32,33,34,35,36,37,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100&STYLES=&BBOX=<cismap:boundingBox>&WIDTH=<cismap:width>&HEIGHT=<cismap:height>&SRS="));
final MappingComponent map = new MappingComponent(false);
final ActiveLayerModel mappingModel = new ActiveLayerModel();
s.addRetrievalListener(new RetrievalListener() {
@Override
public void retrievalStarted(final RetrievalEvent e) {
System.out.println("Start");
}
@Override
public void retrievalProgress(final RetrievalEvent e) {
}
@Override
public void retrievalComplete(final RetrievalEvent e) {
new Thread() {
@Override
public void run() {
try {
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
}
final java.awt.Image img = map.getCamera()
.toImage(map.getWidth(), map.getHeight(), new Color(255, 255, 255, 0));
final BufferedImage bi = new BufferedImage(
img.getWidth(null),
img.getHeight(null),
BufferedImage.TYPE_INT_RGB);
final Graphics2D g2 = bi.createGraphics();
// Draw img into bi so we can write it to file.
g2.drawImage(img, 0, 0, null);
g2.dispose();
final BoundingBox bb = map.getCurrentBoundingBox();
final String geolink = "http://localhost:" + 9098 + "/gotoBoundingBox?x1=" + bb.getX1()
+ "&y1=" + bb.getY1() + "&x2=" + bb.getX2() + "&y2=" + bb.getY2(); // NOI18N
mapImage = bi;
System.out.println("karte geladen " + bi);
} catch (Exception ex) {
Exceptions.printStackTrace(ex);
}
}
}.start();
}
@Override
public void retrievalAborted(final RetrievalEvent e) {
mapError = true;
}
@Override
public void retrievalError(final RetrievalEvent e) {
mapError = true;
}
});
// disable internal layer widget
map.setInternalLayerWidgetAvailable(false);
mappingModel.setSrs(new Crs("EPSG:25832", "", "", true, true));
mappingModel.addHome(new XBoundingBox(
374271.251964098,
5681514.032498134,
374682.9413952776,
5681773.852810634,
"EPSG:25832",
true));
// set the model
map.setMappingModel(mappingModel);
final int height = Integer.parseInt(NbBundle.getMessage(
MauernReportBeanWithMapAndImages.class,
"MauernReportBeanWithMapAndImages.mapHeight"));
final int width = Integer.parseInt(NbBundle.getMessage(
MauernReportBeanWithMapAndImages.class,
"MauernReportBeanWithMapAndImages.mapWidth"));
map.setSize(width, height);
// map.setSize(540, 219);
// initial positioning of the map
map.setAnimationDuration(0);
map.gotoInitialBoundingBox();
map.unlock();
final Geometry g = (Geometry)mauer.getProperty("georeferenz.geo_field");
final DefaultStyledFeature dsf = new DefaultStyledFeature();
dsf.setGeometry(g);
dsf.setLineWidth(5);
dsf.setLinePaint(Color.RED);
map.getFeatureCollection().addFeature(dsf);
map.zoomToFeatureCollection();
double scale;
if (map.getScaleDenominator() >= 100) {
scale = Math.floor(map.getScaleDenominator() / 100) * 100;
} else {
scale = Math.floor(map.getScaleDenominator() / 10) * 10;
}
masstab = "1:" + NumberFormat.getIntegerInstance().format(scale);
if (LOG.isDebugEnabled()) {
LOG.debug("Scale for katasterblatt: " + masstab);
}
map.gotoBoundingBoxWithHistory(map.getBoundingBoxFromScale(scale));
map.setInteractionMode(MappingComponent.SELECT);
mappingModel.addLayer(s);
// TODO set correct url
final List<CidsBean> images = CidsBeanSupport.getBeanCollectionFromProperty(mauer, "bilder");
final StringBuilder url0Builder = new StringBuilder();
final StringBuilder url1Builder = new StringBuilder();
for (final CidsBean b : images) {
final Integer nr = (Integer)b.getProperty("laufende_nummer");
if (nr == 1) {
url0Builder.append(b.getProperty("url").toString());
} else if (nr == 2) {
url1Builder.append(b.getProperty("url").toString());
}
}
CismetThreadPool.execute(new Runnable() {
@Override
public void run() {
try {
if (url0Builder.toString().equals("")) {
image0Error = true;
return;
}
final InputStream iStream = webDavClient.getInputStream(
url0Builder.toString());
img0 = ImageIO.read(iStream);
if (img0 == null) {
image0Error = true;
LOG.warn("error during image retrieval from Webdav");
}
System.out.println(img0);
} catch (Exception e) {
image0Error = true;
}
}
});
CismetThreadPool.execute(new Runnable() {
@Override
public void run() {
try {
if (url1Builder.toString().equals("")) {
image1Error = true;
return;
}
final InputStream iStream = webDavClient.getInputStream(
url1Builder.toString());
img1 = ImageIO.read(iStream);
if (img1 == null) {
image1Error = true;
LOG.warn("error during image retrieval from Webdav");
}
System.out.println(img1);
} catch (Exception e) {
image1Error = true;
}
}
});
}
| public MauernReportBeanWithMapAndImages(final CidsBean mauer) {
super(mauer);
final ResourceBundle bundle = ResourceBundle.getBundle("WebDav");
String pass = bundle.getString("password");
if ((pass != null) && pass.startsWith(PasswordEncrypter.CRYPT_PREFIX)) {
pass = PasswordEncrypter.decryptString(pass);
}
WEB_DAV_PASSWORD = pass;
WEB_DAV_USER = bundle.getString("user");
WEB_DAV_DIRECTORY = bundle.getString("url");
this.webDavClient = new WebDavClient(Proxy.fromPreferences(), WEB_DAV_USER, WEB_DAV_PASSWORD, true);
final ArrayList al = new ArrayList();
// final SimpleWMS s = new SimpleWMS(new SimpleWmsGetMapUrl("http://www.wms.nrw.de/geobasis/DOP?&VERSION=1.1.1&REQUEST=GetMap&WIDTH=<cismap:width>&HEIGHT=<cismap:height>&BBOX=<cismap:boundingBox>&SRS=EPSG:25832&FORMAT=image/png&TRANSPARENT=TRUE&BGCOLOR=0xF0F0F0&EXCEPTIONS=application/vnd.ogc.se_xml&LAYERS=WMS,0,Metadaten&STYLES="));
final SimpleWMS s = new SimpleWMS(new SimpleWmsGetMapUrl(
"http://s102x284:8399/arcgis/services/WuNDa-Orthophoto-WUP/MapServer/WMSServer?service=WMS&VERSION=1.1.1&REQUEST=GetMap&WIDTH=<cismap:width>&HEIGHT=<cismap:height>&BBOX=<cismap:boundingBox>&SRS=EPSG:25832&FORMAT=image/png&TRANSPARENT=TRUE&BGCOLOR=0xF0F0F0&EXCEPTIONS=application/vnd.ogc.se_xml&LAYERS=6&STYLES=default"));
// final SimpleWMS s = new SimpleWMS(new SimpleWmsGetMapUrl(
// "http://S102X284:8399/arcgis/services/ALKIS-EXPRESS/MapServer/WMSServer?&VERSION=1.1.1&REQUEST=GetMap&FORMAT=image/png&TRANSPARENT=FALSE&BGCOLOR=0xF0F0F0&EXCEPTIONS=application/vnd.ogc.se_xml&LAYERS=2,4,5,6,7,8,10,11,12,13,14,16,17,18,19,20,21,22,23,25,26,27,28,29,30,31,32,33,34,35,36,37,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100&STYLES=&BBOX=<cismap:boundingBox>&WIDTH=<cismap:width>&HEIGHT=<cismap:height>&SRS="));
final MappingComponent map = new MappingComponent(false);
final ActiveLayerModel mappingModel = new ActiveLayerModel();
s.addRetrievalListener(new RetrievalListener() {
@Override
public void retrievalStarted(final RetrievalEvent e) {
System.out.println("Start");
}
@Override
public void retrievalProgress(final RetrievalEvent e) {
}
@Override
public void retrievalComplete(final RetrievalEvent e) {
new Thread() {
@Override
public void run() {
try {
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
}
final java.awt.Image img = map.getCamera()
.toImage(map.getWidth(), map.getHeight(), new Color(255, 255, 255, 0));
final BufferedImage bi = new BufferedImage(
img.getWidth(null),
img.getHeight(null),
BufferedImage.TYPE_INT_RGB);
final Graphics2D g2 = bi.createGraphics();
// Draw img into bi so we can write it to file.
g2.drawImage(img, 0, 0, null);
g2.dispose();
final BoundingBox bb = map.getCurrentBoundingBox();
final String geolink = "http://localhost:" + 9098 + "/gotoBoundingBox?x1=" + bb.getX1()
+ "&y1=" + bb.getY1() + "&x2=" + bb.getX2() + "&y2=" + bb.getY2(); // NOI18N
mapImage = bi;
System.out.println("karte geladen " + bi);
} catch (Exception ex) {
Exceptions.printStackTrace(ex);
}
}
}.start();
}
@Override
public void retrievalAborted(final RetrievalEvent e) {
mapError = true;
}
@Override
public void retrievalError(final RetrievalEvent e) {
mapError = true;
}
});
// disable internal layer widget
map.setInternalLayerWidgetAvailable(false);
mappingModel.setSrs(new Crs("EPSG:25832", "", "", true, true));
mappingModel.addHome(new XBoundingBox(
374271.251964098,
5681514.032498134,
374682.9413952776,
5681773.852810634,
"EPSG:25832",
true));
// set the model
map.setMappingModel(mappingModel);
final int height = Integer.parseInt(NbBundle.getMessage(
MauernReportBeanWithMapAndImages.class,
"MauernReportBeanWithMapAndImages.mapHeight"));
final int width = Integer.parseInt(NbBundle.getMessage(
MauernReportBeanWithMapAndImages.class,
"MauernReportBeanWithMapAndImages.mapWidth"));
map.setSize(width, height);
// map.setSize(540, 219);
// initial positioning of the map
map.setAnimationDuration(0);
map.gotoInitialBoundingBox();
map.unlock();
final Geometry g = (Geometry)mauer.getProperty("georeferenz.geo_field");
final DefaultStyledFeature dsf = new DefaultStyledFeature();
dsf.setGeometry(g);
dsf.setLineWidth(5);
dsf.setLinePaint(Color.RED);
map.getFeatureCollection().addFeature(dsf);
map.zoomToFeatureCollection();
double scale;
if (map.getScaleDenominator() >= 100) {
scale = Math.round((map.getScaleDenominator() / 100) + 0.5d) * 100;
} else {
scale = Math.round((map.getScaleDenominator() / 10) + 0.5) * 10;
}
masstab = "1:" + NumberFormat.getIntegerInstance().format(scale);
if (LOG.isDebugEnabled()) {
LOG.debug("Scale for katasterblatt: " + masstab);
}
map.gotoBoundingBoxWithHistory(map.getBoundingBoxFromScale(scale));
map.setInteractionMode(MappingComponent.SELECT);
mappingModel.addLayer(s);
// TODO set correct url
final List<CidsBean> images = CidsBeanSupport.getBeanCollectionFromProperty(mauer, "bilder");
final StringBuilder url0Builder = new StringBuilder();
final StringBuilder url1Builder = new StringBuilder();
for (final CidsBean b : images) {
final Integer nr = (Integer)b.getProperty("laufende_nummer");
if (nr == 1) {
url0Builder.append(b.getProperty("url").toString());
} else if (nr == 2) {
url1Builder.append(b.getProperty("url").toString());
}
}
CismetThreadPool.execute(new Runnable() {
@Override
public void run() {
try {
if (url0Builder.toString().equals("")) {
image0Error = true;
return;
}
final InputStream iStream = webDavClient.getInputStream(
url0Builder.toString());
img0 = ImageIO.read(iStream);
if (img0 == null) {
image0Error = true;
LOG.warn("error during image retrieval from Webdav");
}
System.out.println(img0);
} catch (Exception e) {
image0Error = true;
}
}
});
CismetThreadPool.execute(new Runnable() {
@Override
public void run() {
try {
if (url1Builder.toString().equals("")) {
image1Error = true;
return;
}
final InputStream iStream = webDavClient.getInputStream(
url1Builder.toString());
img1 = ImageIO.read(iStream);
if (img1 == null) {
image1Error = true;
LOG.warn("error during image retrieval from Webdav");
}
System.out.println(img1);
} catch (Exception e) {
image1Error = true;
}
}
});
}
|
diff --git a/search/src/java/cz/incad/Kramerius/views/ProcessesViewObject.java b/search/src/java/cz/incad/Kramerius/views/ProcessesViewObject.java
index 97f5e0bb6..c898da0e0 100644
--- a/search/src/java/cz/incad/Kramerius/views/ProcessesViewObject.java
+++ b/search/src/java/cz/incad/Kramerius/views/ProcessesViewObject.java
@@ -1,377 +1,379 @@
package cz.incad.Kramerius.views;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import antlr.RecognitionException;
import antlr.TokenStreamException;
import cz.incad.Kramerius.processes.ParamsLexer;
import cz.incad.Kramerius.processes.ParamsParser;
import cz.incad.kramerius.processes.DefinitionManager;
import cz.incad.kramerius.processes.LRPRocessFilter;
import cz.incad.kramerius.processes.LRProcess;
import cz.incad.kramerius.processes.LRProcessDefinition;
import cz.incad.kramerius.processes.LRProcessManager;
import cz.incad.kramerius.processes.LRProcessOffset;
import cz.incad.kramerius.processes.LRProcessOrdering;
import cz.incad.kramerius.processes.States;
import cz.incad.kramerius.processes.TypeOfOrdering;
import cz.incad.kramerius.processes.LRPRocessFilter.Tripple;
import cz.incad.kramerius.service.ResourceBundleService;
public class ProcessesViewObject {
public static final java.util.logging.Logger LOGGER = java.util.logging.Logger.getLogger(ProcessesViewObject.class.getName());
private LRProcessManager processManager;
private DefinitionManager definitionManager;
private LRProcessOrdering ordering;
private LRProcessOffset offset;
private TypeOfOrdering typeOfOrdering;
private String lrUrl;
private ResourceBundleService bundleService;
private Locale locale;
private LRPRocessFilter filter;
private String filterParam;
public ProcessesViewObject(LRProcessManager processManager, DefinitionManager manager, LRProcessOrdering ordering, TypeOfOrdering typeOfOrdering, LRProcessOffset offset, String lrUrl, ResourceBundleService bundleService, Locale locale, String filterParam) throws RecognitionException {
super();
this.processManager = processManager;
this.ordering = ordering;
this.offset = offset;
this.typeOfOrdering = typeOfOrdering;
this.definitionManager = manager;
this.lrUrl = lrUrl;
this.bundleService = bundleService;
this.locale = locale;
this.filterParam = filterParam;
this.filter = this.createProcessFilter();
}
public LRPRocessFilter getFilter() {
return filter;
}
public List<ProcessViewObject> getProcesses() {
List<LRProcess> lrProcesses = this.processManager.getLongRunningProcessesAsGrouped(this.ordering, this.typeOfOrdering, this.offset, this.filter);
List<ProcessViewObject> objects = new ArrayList<ProcessViewObject>();
for (LRProcess lrProcess : lrProcesses) {
LRProcessDefinition def = this.definitionManager.getLongRunningProcessDefinition(lrProcess.getDefinitionId());
ProcessViewObject pw = new ProcessViewObject(lrProcess, def, this.ordering, this.offset, this.typeOfOrdering, this.bundleService, this.locale);
if (lrProcess.isMasterProcess()) {
List<LRProcess> childSubprecesses = this.processManager.getLongRunningProcessesByToken(lrProcess.getToken());
for (LRProcess child : childSubprecesses) {
if (!child.getUUID().equals(lrProcess.getUUID())) {
LRProcessDefinition childDef = this.definitionManager.getLongRunningProcessDefinition(child.getDefinitionId());
ProcessViewObject childPW = new ProcessViewObject(child, childDef, this.ordering, this.offset, this.typeOfOrdering, this.bundleService, this.locale);
pw.addChildProcess(childPW);
}
}
}
objects.add(pw);
}
return objects;
}
private LRPRocessFilter createProcessFilter() throws RecognitionException {
if (this.filterParam == null)
return null;
try {
ParamsParser paramsParser = new ParamsParser(new ParamsLexer(new StringReader(this.filterParam)));
List params = paramsParser.params();
List<Tripple> tripples = new ArrayList<LRPRocessFilter.Tripple>();
for (Object object : params) {
List trippleList = (List) object;
Tripple tripple = createTripple(trippleList);
if (tripple.getVal() != null) {
tripples.add(tripple);
}
}
LRPRocessFilter filter = LRPRocessFilter.createFilter(tripples);
// TODO: do it better
- Tripple statusTripple = filter.findTripple("status");
- if (((Integer) statusTripple.getVal()) == -1) {
- filter.removeTripple(statusTripple);
+ if (filter!= null) {
+ Tripple statusTripple = filter.findTripple("status");
+ if (((Integer) statusTripple.getVal()) == -1) {
+ filter.removeTripple(statusTripple);
+ }
}
return filter;
} catch (TokenStreamException te) {
te.printStackTrace();
return null;
}
}
private Tripple createTripple(List trpList) {
if (trpList.size() == 3) {
String name = (String) trpList.get(0);
String op = (String) trpList.get(1);
String val = (String) trpList.get(2);
Tripple trp = new Tripple(name, val, op);
return trp;
} else
return null;
}
public boolean getHasNext() {
int count = this.processManager.getNumberOfLongRunningProcesses();
int oset = Integer.parseInt(this.offset.getOffset());
int size = Integer.parseInt(this.offset.getSize());
return (oset + size) < count;
}
public int getOffsetValue() {
return Integer.parseInt(this.offset.getOffset());
}
public int getPageSize() {
return Integer.parseInt(this.offset.getSize());
}
public String getOrdering() {
return this.ordering.toString();
}
public String getTypeOfOrdering() {
return this.typeOfOrdering.getTypeOfOrdering();
}
public String getMoreNextAHREF() {
try {
String nextString = bundleService.getResourceBundle("labels", locale).getString("administrator.processes.next");
int count = this.processManager.getNumberOfLongRunningProcesses();
int offset = Integer.parseInt(this.offset.getOffset());
int size = Integer.parseInt(this.offset.getSize())*5;
if ((offset + size) < count) {
return "<a href=\"javascript:processes.modifyProcessDialogData('" + this.ordering + "','" + this.offset.getNextOffset() + "','" + size + "','" + this.typeOfOrdering.getTypeOfOrdering() + "');\"> " + nextString + " <img border=\"0\" src=\"img/next_arr.png\"/> </a>";
} else {
return "<span>" + nextString + "</span> <img border=\"0\" src=\"img/next_arr.png\" alt=\"next\" />";
}
} catch (IOException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
return "<img border=\"0\" src=\"img/next_arr.png\" alt=\"next\" />";
}
}
public String getNextAHREF() {
try {
String nextString = bundleService.getResourceBundle("labels", locale).getString("administrator.processes.next");
int count = this.processManager.getNumberOfLongRunningProcesses();
int offset = Integer.parseInt(this.offset.getOffset());
int size = Integer.parseInt(this.offset.getSize());
if ((offset + size) < count) {
return "<a href=\"javascript:processes.modifyProcessDialogData('" + this.ordering + "','" + this.offset.getNextOffset() + "','" + this.offset.getSize() + "','" + this.typeOfOrdering.getTypeOfOrdering() + "');\"> " + nextString + " <img border=\"0\" src=\"img/next_arr.png\"/> </a>";
} else {
return "<span>" + nextString + "</span> <img border=\"0\" src=\"img/next_arr.png\" alt=\"next\" />";
}
} catch (IOException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
return "<img border=\"0\" src=\"img/next_arr.png\" alt=\"next\" />";
}
}
public String getPrevAHREF() {
try {
String prevString = bundleService.getResourceBundle("labels", locale).getString("administrator.processes.prev");
int offset = Integer.parseInt(this.offset.getOffset());
if (offset > 0) {
return "<a href=\"javascript:processes.modifyProcessDialogData('" + this.ordering + "','" + this.offset.getPrevOffset() + "','" + this.offset.getSize() + "','" + this.typeOfOrdering.getTypeOfOrdering() + "');\"> <img border=\"0\" src=\"img/prev_arr.png\"/> " + prevString + " </a>";
} else {
return "<img border=\"0\" src=\"img/prev_arr.png\" alt=\"prev\" /> <span>" + prevString + "</span>";
}
} catch (IOException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
return "<img border=\"0\" src=\"img/prev_arr.png\" alt=\"prev\" /> ";
}
}
private TypeOfOrdering switchOrdering() {
return this.typeOfOrdering.equals(TypeOfOrdering.ASC) ? TypeOfOrdering.DESC : TypeOfOrdering.ASC;
}
public String getNameOrdering() {
try {
String nameString = bundleService.getResourceBundle("labels", locale).getString("administrator.processes.name");
LRProcessOrdering nOrdering = LRProcessOrdering.NAME;
boolean changeTypeOfOrdering = this.ordering.equals(nOrdering);
return newOrderingURL(nOrdering, nameString, changeTypeOfOrdering ? switchOrdering() : TypeOfOrdering.ASC);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
return e.getMessage();
}
}
public String getDateOrdering() {
try {
String startedString = bundleService.getResourceBundle("labels", locale).getString("administrator.processes.started");
LRProcessOrdering nOrdering = LRProcessOrdering.STARTED;
boolean changeTypeOfOrdering = this.ordering.equals(nOrdering);
return newOrderingURL(nOrdering, startedString, changeTypeOfOrdering ? switchOrdering() : TypeOfOrdering.ASC);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
return e.getMessage();
}
}
public String getPlannedDateOrdering() {
try {
String startedString = bundleService.getResourceBundle("labels", locale).getString("administrator.processes.planned");
LRProcessOrdering nOrdering = LRProcessOrdering.PLANNED;
boolean changeTypeOfOrdering = this.ordering.equals(nOrdering);
return newOrderingURL(nOrdering, startedString, changeTypeOfOrdering ? switchOrdering() : TypeOfOrdering.ASC);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
return e.getMessage();
}
}
public String getUserOrdering() {
try {
String pidString = bundleService.getResourceBundle("labels", locale).getString("administrator.processes.user");
LRProcessOrdering nOrdering = LRProcessOrdering.LOGINNAME;
boolean changeTypeOfOrdering = this.ordering.equals(nOrdering);
return newOrderingURL(nOrdering, pidString, changeTypeOfOrdering ? switchOrdering() : TypeOfOrdering.ASC);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
return e.getMessage();
}
}
public String getPidOrdering() {
try {
String pidString = bundleService.getResourceBundle("labels", locale).getString("administrator.processes.pid");
LRProcessOrdering nOrdering = LRProcessOrdering.ID;
boolean changeTypeOfOrdering = this.ordering.equals(nOrdering);
return newOrderingURL(nOrdering, pidString, changeTypeOfOrdering ? switchOrdering() : TypeOfOrdering.ASC);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
return e.getMessage();
}
}
public String getStateOrdering() {
try {
String stateString = bundleService.getResourceBundle("labels", locale).getString("administrator.processes.state");
LRProcessOrdering nOrdering = LRProcessOrdering.STATE;
boolean changeTypeOfOrdering = this.ordering.equals(nOrdering);
return newOrderingURL(nOrdering, stateString, changeTypeOfOrdering ? switchOrdering() : TypeOfOrdering.ASC);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
return e.getMessage();
}
}
private String newOrderingURL(LRProcessOrdering nOrdering, String name, TypeOfOrdering ntypeOfOrdering) {
String href = "<a href=\"javascript:processes.modifyProcessDialogData('" + nOrdering + "','" + this.offset.getOffset() + "','" + this.offset.getSize() + "','" + ntypeOfOrdering.getTypeOfOrdering() + "');\"";
if (this.ordering.equals(nOrdering)) {
// href += orderingImg(nOrdering);
if (typeOfOrdering.equals(TypeOfOrdering.DESC)) {
href += " class=\"order_down\"";
} else {
href += " class=\"order_up\"";
}
}
href += ">" + name + "</a>";
return href;
}
public String getPlannedAfter() {
if (this.filter != null) {
List<Tripple> tripples = this.filter.getTripples();
for (Tripple tripple : tripples) {
if (tripple.getName().equals("planned") && tripple.getOp().equals(LRPRocessFilter.Op.GT)) {
return LRPRocessFilter.getFormattedValue(tripple);
}
}
}
return "";
}
public String getPlannedBefore() {
if (this.filter != null) {
List<Tripple> tripples = this.filter.getTripples();
for (Tripple tripple : tripples) {
if (tripple.getName().equals("planned") && tripple.getOp().equals(LRPRocessFilter.Op.LT)) {
return LRPRocessFilter.getFormattedValue(tripple);
}
}
}
return "";
}
public String getStartedAfter() {
if (this.filter != null) {
List<Tripple> tripples = this.filter.getTripples();
for (Tripple tripple : tripples) {
if (tripple.getName().equals("started") && tripple.getOp().equals(LRPRocessFilter.Op.GT)) {
return LRPRocessFilter.getFormattedValue(tripple);
}
}
}
return "";
}
public String getStartedBefore() {
if (this.filter != null) {
List<Tripple> tripples = this.filter.getTripples();
for (Tripple tripple : tripples) {
if (tripple.getName().equals("started") && tripple.getOp().equals(LRPRocessFilter.Op.LT)) {
return LRPRocessFilter.getFormattedValue(tripple);
}
}
}
return "";
}
public String getNameLike() {
if (this.filter != null) {
List<Tripple> tripples = this.filter.getTripples();
for (Tripple tripple : tripples) {
if (tripple.getName().equals("name") && tripple.getOp().equals(LRPRocessFilter.Op.LIKE)) {
return LRPRocessFilter.getFormattedValue(tripple);
}
}
}
return "";
}
public List<ProcessStateWrapper> getStatesForFilter() {
List<ProcessStateWrapper> wrap = ProcessStateWrapper.wrap(true, States.values());
if (this.filter != null) {
Tripple tripple = this.filter.findTripple("status");
if (tripple != null) {
Integer intg = (Integer)tripple.getVal();
if (intg.intValue() >= 0) {
for (ProcessStateWrapper wrapper : wrap) {
if (wrapper.getVal() == intg.intValue()) {
wrapper.setSelected(true);
}
}
}
}
}
return wrap;
}
private String orderingImg(LRProcessOrdering nOrdering) {
if (nOrdering.equals(this.ordering)) {
if (typeOfOrdering.equals(TypeOfOrdering.DESC)) {
return "<img src=\"img/order_down.png\"></img>";
} else {
return "<img src=\"img/order_up.png\"></img>";
}
} else
return "";
}
}
| true | true | private LRPRocessFilter createProcessFilter() throws RecognitionException {
if (this.filterParam == null)
return null;
try {
ParamsParser paramsParser = new ParamsParser(new ParamsLexer(new StringReader(this.filterParam)));
List params = paramsParser.params();
List<Tripple> tripples = new ArrayList<LRPRocessFilter.Tripple>();
for (Object object : params) {
List trippleList = (List) object;
Tripple tripple = createTripple(trippleList);
if (tripple.getVal() != null) {
tripples.add(tripple);
}
}
LRPRocessFilter filter = LRPRocessFilter.createFilter(tripples);
// TODO: do it better
Tripple statusTripple = filter.findTripple("status");
if (((Integer) statusTripple.getVal()) == -1) {
filter.removeTripple(statusTripple);
}
return filter;
} catch (TokenStreamException te) {
te.printStackTrace();
return null;
}
}
| private LRPRocessFilter createProcessFilter() throws RecognitionException {
if (this.filterParam == null)
return null;
try {
ParamsParser paramsParser = new ParamsParser(new ParamsLexer(new StringReader(this.filterParam)));
List params = paramsParser.params();
List<Tripple> tripples = new ArrayList<LRPRocessFilter.Tripple>();
for (Object object : params) {
List trippleList = (List) object;
Tripple tripple = createTripple(trippleList);
if (tripple.getVal() != null) {
tripples.add(tripple);
}
}
LRPRocessFilter filter = LRPRocessFilter.createFilter(tripples);
// TODO: do it better
if (filter!= null) {
Tripple statusTripple = filter.findTripple("status");
if (((Integer) statusTripple.getVal()) == -1) {
filter.removeTripple(statusTripple);
}
}
return filter;
} catch (TokenStreamException te) {
te.printStackTrace();
return null;
}
}
|
diff --git a/technologies/BasicESB/src/java/com/pjaol/ESB/config/Initializer.java b/technologies/BasicESB/src/java/com/pjaol/ESB/config/Initializer.java
index 2b90277..b55fb74 100644
--- a/technologies/BasicESB/src/java/com/pjaol/ESB/config/Initializer.java
+++ b/technologies/BasicESB/src/java/com/pjaol/ESB/config/Initializer.java
@@ -1,275 +1,277 @@
/*******************************************************************************
* Copyright 2012 Patrick O'Leary
*
* 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.pjaol.ESB.config;
import java.io.File;
import java.io.FilenameFilter;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.log4j.Logger;
import com.pjaol.ESB.core.Controller;
import com.pjaol.ESB.core.Evaluator;
import com.pjaol.ESB.core.Module;
import com.pjaol.ESB.core.PipeLine;
public class Initializer {
private Logger _logger = Logger.getLogger(getClass());
private ESBCore core = ESBCore.getInstance();
private Map<String, Controller> uris = new HashMap<String, Controller>();
/**
* Using Components
* @throws ConfigurationException
*/
public void startup() throws ConfigurationException {
// add libs to the classpath
addLibs();
// Initialize and put pipelines in the core
try {
Map<String, PipeLineComponent> pipeComponents = core.getPipeLineComponent();
Map<String, PipeLine> pipelines = startupPipes(pipeComponents);
core.setPipelines(pipelines);
// initialize monitor after all pipelines have been init
// this gives the ESBMonitor pipeline the opportunity to start
for(Entry<String, PipeLine> k: pipelines.entrySet()){
k.getValue().initializeMonitor();
}
} catch (InstantiationException e) {
throw new ConfigurationException(e);
} catch (IllegalAccessException e) {
throw new ConfigurationException(e);
} catch (ClassNotFoundException e) {
throw new ConfigurationException(e);
}
// Initialize and put controllers in the core
try {
core.setControllers(startupControllers(core
.getControllerComponent()));
} catch (InstantiationException e) {
throw new ConfigurationException(e.getMessage());
} catch (IllegalAccessException e) {
throw new ConfigurationException(e.getMessage());
} catch (ClassNotFoundException e) {
throw new ConfigurationException(e.getMessage());
}
// uris are created in startupControllers
core.setControllerUris(uris);
}
private void initializeMonitors(){
}
private Map<String, PipeLine> startupPipes(
Map<String, PipeLineComponent> items)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
Map<String, PipeLine> result = new HashMap<String, PipeLine>();
for (PipeLineComponent c : items.values()) {
// System.out.println(c);
PipeLine pipeline = new PipeLine();
pipeline.setName(c.getName());
Evaluator evaluator = initializeEvaluator(c.getEvaluator());
pipeline.setEvaluator(evaluator);
pipeline.setTimeout(c.getTimeout());
List<ConfigurationComponent> modules = c.getModules();
List<Module> pipeModules = new ArrayList<Module>();
for (ConfigurationComponent mod : modules) {
Module m = initializeModule(mod);
pipeModules.add(m);
}
pipeline.setModules(pipeModules);
pipeline.init(c.getArgs());
//pipeline.initializeMonitor();
result.put(c.getName(), pipeline);
}
return result;
}
private Map<String, Controller> startupControllers(
Map<String, ControllerComponent> items)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
Map<String, Controller> result = new HashMap<String, Controller>();
for (ControllerComponent controllerComponent : items.values()) {
Controller controller = initializeController(controllerComponent);
result.put(controllerComponent.getName(), controller);
uris.put(controllerComponent.getUri(), controller);
}
return result;
}
private Controller initializeController(
ControllerComponent controllerComponent)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
String className = controllerComponent.getClassName();
_logger.info("Initializing controller: "
+ controllerComponent.getName() + " : " + className);
Controller controller = extracted(className);
controller.setName(controllerComponent.getName());
controller.setPipelines(controllerComponent.getPipelines());
controller.setPipes(controllerComponent.getPipes());
controller.setUri(controllerComponent.getUri());
controller.setLimitorPipeLines(controllerComponent
.getLimiterPipeLines());
controller.setLimitorName(controllerComponent.getLimiterName());
controller.setTimeout(controllerComponent.getTimeout());
controller.init(controllerComponent.getArgs());
controller.initializeMonitor();
return controller;
}
private Evaluator initializeEvaluator(EvaluatorComponent evaluatorComponent)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
String className = evaluatorComponent.getClassName();
_logger.info("Initializing evaluator: " + evaluatorComponent.getName()
+ " : " + className);
Evaluator e = extracted(className);
e.setName(evaluatorComponent.getName());
e.init(evaluatorComponent.getArgs());
return e;
}
private Module initializeModule(ConfigurationComponent module)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
String className = module.getClassName();
_logger.info("Initializing Module: " + module.getName() + " : "
+ className);
Module m = extracted(className);
m.setName(module.getName());
m.init(module.getArgs());
m.initializeMonitor();
return m;
}
@SuppressWarnings("unchecked")
private <T> T extracted(String className) throws InstantiationException,
IllegalAccessException, ClassNotFoundException {
return (T) Thread.currentThread().getContextClassLoader().getClass().forName(className).newInstance();
//return (T) Class.forName(className).newInstance();
}
private void addLibs(){
Map<String, String> globals = core.getGlobals();
String libs = globals.get("lib");
URLClassLoader urlClassLoader = (URLClassLoader)Thread.currentThread().getContextClassLoader().getParent();
URL[] urls = urlClassLoader.getURLs();
if (libs != null){
String [] libPaths = libs.split(",|\n");
for(String path : libPaths){
path = path.trim();
File f = new File(path);
if (! f.exists()){
// search for the path from the basicesb home
String home = System.getProperty(BasicESBVariables.basicESBHomeProperty);
String homePath = home+File.separatorChar+path;
+ path = homePath;
+ _logger.info("Switching path to "+path);
f = new File(homePath);
if (! f.exists()){
String cwd = new File(".").getAbsolutePath();
_logger.error("Loading lib : " + path+" failed at "+ cwd+" and "+homePath );
continue;
}
}
_logger.info("Loading path: "+ path);
String[] jars = f.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String fileName) {
// Do not load the servlet api, conflicts with servlet container
if (fileName.startsWith("servlet-api")){
_logger.info("Skipping : "+ fileName);
return false;
}
return fileName.endsWith(".jar");
}
});
for(String jar: jars){
try {
String fullPath = path+File.separator+jar;
addPath(fullPath);
_logger.info("Adding jar: "+ fullPath);
} catch (Exception e) {
_logger.error("Failed to load jar: "+jar+"\n"+ e.getMessage());
e.printStackTrace();
}
}
}
}
}
public static void addPath(String s) throws Exception {
File f = new File(s);
if (! f.exists()){
System.err.println("Cannot file file: "+ s);
}
URI fURI = f.toURI();
URL u = fURI.toURL();
URLClassLoader urlClassLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader();
Class urlClass = URLClassLoader.class;
Method method = urlClass.getDeclaredMethod("addURL", new Class[]{URL.class});
method.setAccessible(true);
method.invoke(urlClassLoader, new Object[]{u});
}
}
| true | true | private void addLibs(){
Map<String, String> globals = core.getGlobals();
String libs = globals.get("lib");
URLClassLoader urlClassLoader = (URLClassLoader)Thread.currentThread().getContextClassLoader().getParent();
URL[] urls = urlClassLoader.getURLs();
if (libs != null){
String [] libPaths = libs.split(",|\n");
for(String path : libPaths){
path = path.trim();
File f = new File(path);
if (! f.exists()){
// search for the path from the basicesb home
String home = System.getProperty(BasicESBVariables.basicESBHomeProperty);
String homePath = home+File.separatorChar+path;
f = new File(homePath);
if (! f.exists()){
String cwd = new File(".").getAbsolutePath();
_logger.error("Loading lib : " + path+" failed at "+ cwd+" and "+homePath );
continue;
}
}
_logger.info("Loading path: "+ path);
String[] jars = f.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String fileName) {
// Do not load the servlet api, conflicts with servlet container
if (fileName.startsWith("servlet-api")){
_logger.info("Skipping : "+ fileName);
return false;
}
return fileName.endsWith(".jar");
}
});
for(String jar: jars){
try {
String fullPath = path+File.separator+jar;
addPath(fullPath);
_logger.info("Adding jar: "+ fullPath);
} catch (Exception e) {
_logger.error("Failed to load jar: "+jar+"\n"+ e.getMessage());
e.printStackTrace();
}
}
}
}
}
| private void addLibs(){
Map<String, String> globals = core.getGlobals();
String libs = globals.get("lib");
URLClassLoader urlClassLoader = (URLClassLoader)Thread.currentThread().getContextClassLoader().getParent();
URL[] urls = urlClassLoader.getURLs();
if (libs != null){
String [] libPaths = libs.split(",|\n");
for(String path : libPaths){
path = path.trim();
File f = new File(path);
if (! f.exists()){
// search for the path from the basicesb home
String home = System.getProperty(BasicESBVariables.basicESBHomeProperty);
String homePath = home+File.separatorChar+path;
path = homePath;
_logger.info("Switching path to "+path);
f = new File(homePath);
if (! f.exists()){
String cwd = new File(".").getAbsolutePath();
_logger.error("Loading lib : " + path+" failed at "+ cwd+" and "+homePath );
continue;
}
}
_logger.info("Loading path: "+ path);
String[] jars = f.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String fileName) {
// Do not load the servlet api, conflicts with servlet container
if (fileName.startsWith("servlet-api")){
_logger.info("Skipping : "+ fileName);
return false;
}
return fileName.endsWith(".jar");
}
});
for(String jar: jars){
try {
String fullPath = path+File.separator+jar;
addPath(fullPath);
_logger.info("Adding jar: "+ fullPath);
} catch (Exception e) {
_logger.error("Failed to load jar: "+jar+"\n"+ e.getMessage());
e.printStackTrace();
}
}
}
}
}
|
diff --git a/src/main/java/StevenDimDoors/mod_pocketDim/tileentities/TileEntityDimDoorGold.java b/src/main/java/StevenDimDoors/mod_pocketDim/tileentities/TileEntityDimDoorGold.java
index 4bdd735..7dc1c64 100644
--- a/src/main/java/StevenDimDoors/mod_pocketDim/tileentities/TileEntityDimDoorGold.java
+++ b/src/main/java/StevenDimDoors/mod_pocketDim/tileentities/TileEntityDimDoorGold.java
@@ -1,91 +1,91 @@
package StevenDimDoors.mod_pocketDim.tileentities;
import net.minecraft.world.ChunkCoordIntPair;
import net.minecraftforge.common.ForgeChunkManager;
import net.minecraftforge.common.ForgeChunkManager.Ticket;
import net.minecraftforge.common.ForgeChunkManager.Type;
import StevenDimDoors.mod_pocketDim.IChunkLoader;
import StevenDimDoors.mod_pocketDim.mod_pocketDim;
import StevenDimDoors.mod_pocketDim.core.PocketManager;
import StevenDimDoors.mod_pocketDim.util.Point4D;
import StevenDimDoors.mod_pocketDim.world.PocketBuilder;
public class TileEntityDimDoorGold extends TileEntityDimDoor implements IChunkLoader
{
private Ticket chunkTicket;
@Override
public boolean canUpdate()
{
return true;
}
@Override
public void updateEntity()
{ // every tick?
if (PocketManager.getDimensionData(this.worldObj) != null &&
PocketManager.getDimensionData(this.worldObj).isPocketDimension() &&
!this.worldObj.isRemote)
{
if(PocketManager.getLink(this.xCoord,this.yCoord,this.zCoord,this.worldObj)==null)
{
return;
}
if (this.chunkTicket == null)
{
chunkTicket = ForgeChunkManager.requestTicket(mod_pocketDim.instance, worldObj, Type.NORMAL);
if(chunkTicket == null)
{
return;
}
chunkTicket.getModData().setInteger("goldDimDoorX", xCoord);
chunkTicket.getModData().setInteger("goldDimDoorY", yCoord);
chunkTicket.getModData().setInteger("goldDimDoorZ", zCoord);
forceChunkLoading(chunkTicket,this.xCoord,this.zCoord);
}
}
}
@Override
public void forceChunkLoading(Ticket chunkTicket,int x,int z)
{
Point4D origin = PocketManager.getDimensionData(this.worldObj).origin();
int orientation = PocketManager.getDimensionData(this.worldObj).orientation();
int xOffset=0;
int zOffset=0;
switch(orientation)
{
case 0:
xOffset = PocketBuilder.DEFAULT_POCKET_SIZE/2;
break;
case 1:
zOffset = PocketBuilder.DEFAULT_POCKET_SIZE/2;
break;
case 2:
xOffset = -PocketBuilder.DEFAULT_POCKET_SIZE/2;
break;
case 3:
zOffset = -PocketBuilder.DEFAULT_POCKET_SIZE/2;
break;
}
- for(int chunkX = -1; chunkX<2;chunkX++)
+ for(int chunkX = -2; chunkX<3;chunkX++)
{
- for(int chunkZ = -1; chunkZ<2;chunkZ++)
+ for(int chunkZ = -2; chunkZ<3;chunkZ++)
{
ForgeChunkManager.forceChunk(chunkTicket, new ChunkCoordIntPair((origin.getX()+xOffset >> 4)+chunkX, (origin.getZ()+zOffset >> 4)+chunkZ));
}
}
}
@Override
public void invalidate()
{
ForgeChunkManager.releaseTicket(chunkTicket);
super.invalidate();
}
}
| false | true | public void forceChunkLoading(Ticket chunkTicket,int x,int z)
{
Point4D origin = PocketManager.getDimensionData(this.worldObj).origin();
int orientation = PocketManager.getDimensionData(this.worldObj).orientation();
int xOffset=0;
int zOffset=0;
switch(orientation)
{
case 0:
xOffset = PocketBuilder.DEFAULT_POCKET_SIZE/2;
break;
case 1:
zOffset = PocketBuilder.DEFAULT_POCKET_SIZE/2;
break;
case 2:
xOffset = -PocketBuilder.DEFAULT_POCKET_SIZE/2;
break;
case 3:
zOffset = -PocketBuilder.DEFAULT_POCKET_SIZE/2;
break;
}
for(int chunkX = -1; chunkX<2;chunkX++)
{
for(int chunkZ = -1; chunkZ<2;chunkZ++)
{
ForgeChunkManager.forceChunk(chunkTicket, new ChunkCoordIntPair((origin.getX()+xOffset >> 4)+chunkX, (origin.getZ()+zOffset >> 4)+chunkZ));
}
}
}
| public void forceChunkLoading(Ticket chunkTicket,int x,int z)
{
Point4D origin = PocketManager.getDimensionData(this.worldObj).origin();
int orientation = PocketManager.getDimensionData(this.worldObj).orientation();
int xOffset=0;
int zOffset=0;
switch(orientation)
{
case 0:
xOffset = PocketBuilder.DEFAULT_POCKET_SIZE/2;
break;
case 1:
zOffset = PocketBuilder.DEFAULT_POCKET_SIZE/2;
break;
case 2:
xOffset = -PocketBuilder.DEFAULT_POCKET_SIZE/2;
break;
case 3:
zOffset = -PocketBuilder.DEFAULT_POCKET_SIZE/2;
break;
}
for(int chunkX = -2; chunkX<3;chunkX++)
{
for(int chunkZ = -2; chunkZ<3;chunkZ++)
{
ForgeChunkManager.forceChunk(chunkTicket, new ChunkCoordIntPair((origin.getX()+xOffset >> 4)+chunkX, (origin.getZ()+zOffset >> 4)+chunkZ));
}
}
}
|
diff --git a/orbisgis-view/src/main/java/org/orbisgis/view/toc/actions/cui/legends/components/AbsSpinner.java b/orbisgis-view/src/main/java/org/orbisgis/view/toc/actions/cui/legends/components/AbsSpinner.java
index 825b0ef12..c15e0e4d1 100644
--- a/orbisgis-view/src/main/java/org/orbisgis/view/toc/actions/cui/legends/components/AbsSpinner.java
+++ b/orbisgis-view/src/main/java/org/orbisgis/view/toc/actions/cui/legends/components/AbsSpinner.java
@@ -1,78 +1,78 @@
/**
* OrbisGIS is a GIS application dedicated to scientific spatial simulation.
* This cross-platform GIS is developed at French IRSTV institute and is able to
* manipulate and create vector and raster spatial information.
*
* OrbisGIS is distributed under GPL 3 license. It is produced by the "Atelier SIG"
* team of the IRSTV Institute <http://www.irstv.fr/> CNRS FR 2488.
*
* Copyright (C) 2007-2012 IRSTV (FR CNRS 2488)
*
* This file is part of OrbisGIS.
*
* OrbisGIS 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.
*
* OrbisGIS 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
* OrbisGIS. If not, see <http://www.gnu.org/licenses/>.
*
* For more information, please consult: <http://www.orbisgis.org/>
* or contact directly:
* info_at_ orbisgis.org
*/
package org.orbisgis.view.toc.actions.cui.legends.components;
import javax.swing.*;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
/**
* Root class for spinners. Adds a {@code MouseWheelListener} so that the user
* can update the value by means of the mouse scroll wheel.
*
* @author Adam Gouge
*/
public abstract class AbsSpinner extends JSpinner {
protected static final double SMALL_STEP = 0.1;
protected static final double LARGE_STEP = 0.5;
/**
* Constructor
*
* @param model Spinner model
*/
public AbsSpinner(final SpinnerNumberModel model) {
super(model);
// Enable the mouse scroll wheel on spinners.
addMouseWheelListener(new MouseWheelListener() {
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
// The new value is the old one minus the wheel rotation
// times the spin step.
Double newValue = ((Double) getValue())
- - e.getPreciseWheelRotation() * getSpinStep();
+ - e.getWheelRotation() * getSpinStep();
// Only update if we are within the given range.
if (model.getMaximum().compareTo(newValue) >= 0
&& model.getMinimum().compareTo(newValue) <= 0) {
setValue(newValue);
}
}
});
}
/**
* Gets the spin step for the mouse scroll wheel listener.
*
* @return The spin step.
*/
protected double getSpinStep() {
return SMALL_STEP;
}
}
| true | true | public AbsSpinner(final SpinnerNumberModel model) {
super(model);
// Enable the mouse scroll wheel on spinners.
addMouseWheelListener(new MouseWheelListener() {
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
// The new value is the old one minus the wheel rotation
// times the spin step.
Double newValue = ((Double) getValue())
- e.getPreciseWheelRotation() * getSpinStep();
// Only update if we are within the given range.
if (model.getMaximum().compareTo(newValue) >= 0
&& model.getMinimum().compareTo(newValue) <= 0) {
setValue(newValue);
}
}
});
}
| public AbsSpinner(final SpinnerNumberModel model) {
super(model);
// Enable the mouse scroll wheel on spinners.
addMouseWheelListener(new MouseWheelListener() {
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
// The new value is the old one minus the wheel rotation
// times the spin step.
Double newValue = ((Double) getValue())
- e.getWheelRotation() * getSpinStep();
// Only update if we are within the given range.
if (model.getMaximum().compareTo(newValue) >= 0
&& model.getMinimum().compareTo(newValue) <= 0) {
setValue(newValue);
}
}
});
}
|
diff --git a/src/com/barroncraft/sce/ExtensionsCommand.java b/src/com/barroncraft/sce/ExtensionsCommand.java
index d25e3a4..150673c 100644
--- a/src/com/barroncraft/sce/ExtensionsCommand.java
+++ b/src/com/barroncraft/sce/ExtensionsCommand.java
@@ -1,101 +1,101 @@
package com.barroncraft.sce;
import net.sacredlabyrinth.phaed.simpleclans.Clan;
import net.sacredlabyrinth.phaed.simpleclans.ClanPlayer;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.entity.Player;
public class ExtensionsCommand
{
SimpleClansExtensions plugin;
public ExtensionsCommand(SimpleClansExtensions plugin)
{
this.plugin = plugin;
}
public void CommandJoin(Player player, String newClanName)
{
ClanPlayer clanPlayer = plugin.manager.getCreateClanPlayer(player.getName());
Clan newClan = plugin.manager.getClan(newClanName);
Clan oldClan = clanPlayer.getClan();
if (oldClan != null)
{
- if (oldClan.getName().equalsIgnoreCase(newClan.getName()))
+ if (newClan != null && oldClan.getName().equalsIgnoreCase(newClan.getName()))
player.sendMessage(ChatColor.RED + "You can't transfer to the same team");
else if (PlayerDifference(oldClan, newClan) < plugin.maxDifference)
player.sendMessage(ChatColor.RED + "You can't transfer teams unless there is a difference of " + plugin.maxDifference + " between them");
else
{
oldClan.removeMember(player.getName());
AddPlayerToClan(clanPlayer, newClan, newClanName);
player.sendMessage(ChatColor.BLUE + "You have been transfered to team " + newClanName);
}
}
else
{
if (PlayerDifference(newClan, plugin.maxDifference) >= plugin.maxDifference)
player.sendMessage(ChatColor.RED + "That team already has too many players. Try a different one.");
else
{
AddPlayerToClan(clanPlayer, newClan, newClanName);
player.sendMessage(ChatColor.BLUE + "You have joined team " + newClanName);
}
}
}
private int PlayerDifference(Clan clan, int max)
{
int returnValue = 0;
int count = GetOnlinePlayerCount(clan);
for (String name : plugin.ClanNames)
{
int clanCount = GetOnlinePlayerCount(plugin.manager.getClan(name));
int difference = count - clanCount;
if (difference >= max)
return difference;
else if (difference > returnValue)
returnValue = difference;
}
return returnValue;
}
private int PlayerDifference(Clan firstClan, Clan secondClan)
{
return GetOnlinePlayerCount(firstClan) - GetOnlinePlayerCount(secondClan);
}
private void AddPlayerToClan(ClanPlayer player, Clan clan, String clanName)
{
if (clan == null)
{
plugin.manager.createClan(player.toPlayer(), clanName, clanName);
clan = plugin.manager.getClan(clanName);
Location location = plugin.spawnLocations.get(clanName);
if (location != null)
clan.setHomeLocation(location);
}
clan.addPlayerToClan(player);
player.toPlayer().teleport(clan.getHomeLocation());
}
private int GetOnlinePlayerCount(Clan clan)
{
if (clan == null)
return 0;
int count = 0;
for (ClanPlayer player : clan.getMembers())
{
Player onlinePlayer = player.toPlayer();
if (onlinePlayer != null && onlinePlayer.isOnline())
count++;
}
return count;
}
}
| true | true | public void CommandJoin(Player player, String newClanName)
{
ClanPlayer clanPlayer = plugin.manager.getCreateClanPlayer(player.getName());
Clan newClan = plugin.manager.getClan(newClanName);
Clan oldClan = clanPlayer.getClan();
if (oldClan != null)
{
if (oldClan.getName().equalsIgnoreCase(newClan.getName()))
player.sendMessage(ChatColor.RED + "You can't transfer to the same team");
else if (PlayerDifference(oldClan, newClan) < plugin.maxDifference)
player.sendMessage(ChatColor.RED + "You can't transfer teams unless there is a difference of " + plugin.maxDifference + " between them");
else
{
oldClan.removeMember(player.getName());
AddPlayerToClan(clanPlayer, newClan, newClanName);
player.sendMessage(ChatColor.BLUE + "You have been transfered to team " + newClanName);
}
}
else
{
if (PlayerDifference(newClan, plugin.maxDifference) >= plugin.maxDifference)
player.sendMessage(ChatColor.RED + "That team already has too many players. Try a different one.");
else
{
AddPlayerToClan(clanPlayer, newClan, newClanName);
player.sendMessage(ChatColor.BLUE + "You have joined team " + newClanName);
}
}
}
| public void CommandJoin(Player player, String newClanName)
{
ClanPlayer clanPlayer = plugin.manager.getCreateClanPlayer(player.getName());
Clan newClan = plugin.manager.getClan(newClanName);
Clan oldClan = clanPlayer.getClan();
if (oldClan != null)
{
if (newClan != null && oldClan.getName().equalsIgnoreCase(newClan.getName()))
player.sendMessage(ChatColor.RED + "You can't transfer to the same team");
else if (PlayerDifference(oldClan, newClan) < plugin.maxDifference)
player.sendMessage(ChatColor.RED + "You can't transfer teams unless there is a difference of " + plugin.maxDifference + " between them");
else
{
oldClan.removeMember(player.getName());
AddPlayerToClan(clanPlayer, newClan, newClanName);
player.sendMessage(ChatColor.BLUE + "You have been transfered to team " + newClanName);
}
}
else
{
if (PlayerDifference(newClan, plugin.maxDifference) >= plugin.maxDifference)
player.sendMessage(ChatColor.RED + "That team already has too many players. Try a different one.");
else
{
AddPlayerToClan(clanPlayer, newClan, newClanName);
player.sendMessage(ChatColor.BLUE + "You have joined team " + newClanName);
}
}
}
|
diff --git a/src/main/java/hudson/plugins/active_directory/ActiveDirectoryUnixAuthenticationProvider.java b/src/main/java/hudson/plugins/active_directory/ActiveDirectoryUnixAuthenticationProvider.java
index 971108d..f1f0b66 100644
--- a/src/main/java/hudson/plugins/active_directory/ActiveDirectoryUnixAuthenticationProvider.java
+++ b/src/main/java/hudson/plugins/active_directory/ActiveDirectoryUnixAuthenticationProvider.java
@@ -1,198 +1,200 @@
package hudson.plugins.active_directory;
import static javax.naming.directory.SearchControls.SUBTREE_SCOPE;
import hudson.plugins.active_directory.ActiveDirectorySecurityRealm.DesciprotrImpl;
import hudson.security.GroupDetails;
import hudson.security.SecurityRealm;
import hudson.security.UserMayOrMayNotExistException;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import org.acegisecurity.AuthenticationException;
import org.acegisecurity.AuthenticationServiceException;
import org.acegisecurity.BadCredentialsException;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.providers.AuthenticationProvider;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.providers.dao.AbstractUserDetailsAuthenticationProvider;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UserDetailsService;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.springframework.dao.DataAccessException;
import com.sun.jndi.ldap.LdapCtxFactory;
/**
* {@link AuthenticationProvider} with Active Directory, through LDAP.
*
* @author Kohsuke Kawaguchi
* @author James Nord
*/
public class ActiveDirectoryUnixAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider
implements UserDetailsService, GroupDetailsService {
private final String[] domainNames;
public ActiveDirectoryUnixAuthenticationProvider(String domainName) {
this.domainNames = domainName.split(",");
}
/**
* We'd like to implement {@link UserDetailsService} ideally, but in short of keeping the manager user/password,
* we can't do so. In Active Directory authentication, we should support SPNEGO/Kerberos and
* that should eliminate the need for the "remember me" service.
*/
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
throw new UsernameNotFoundException("Active-directory plugin doesn't support user retrieval");
}
protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
// active directory authentication is not by comparing clear text password,
// so there's nothing to do here.
}
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
UserDetails userDetails = null;
for (String domainName : domainNames) {
try {
userDetails = retrieveUser(username, authentication, domainName);
}
catch (BadCredentialsException bce) {
LOGGER.log(Level.WARNING,"Credential exception tying to authenticate against " + domainName + " domain",bce);
}
if (userDetails != null) {
break;
}
}
if (userDetails == null) {
LOGGER.log(Level.WARNING,"Exhausted all configured domains and could not authenticat against any.");
throw new BadCredentialsException("Either no such user '"+username+"' or incorrect password");
}
return userDetails;
}
private UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication, String domainName) throws AuthenticationException {
// when we use custom socket factory below, every LDAP operations result in a classloading via context classloader,
// so we need it to resolve.
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
try {
String password = null;
if(authentication!=null)
password = (String) authentication.getCredentials();
// bind by using the specified username/password
Hashtable props = new Hashtable();
String principalName = username + '@' + domainName;
props.put(Context.SECURITY_PRINCIPAL, principalName);
props.put(Context.SECURITY_CREDENTIALS,password);
props.put(Context.REFERRAL, "follow");
// specifying custom socket factory requires a custom classloader.
props.put("java.naming.ldap.factory.socket", TrustAllSocketFactory.class.getName());
SocketInfo ldapServer;
try {
ldapServer = DesciprotrImpl.INSTANCE.obtainLDAPServer(domainName);
} catch (NamingException e) {
LOGGER.log(Level.WARNING,"Failed to find the LDAP service",e);
throw new AuthenticationServiceException("Failed to find the LDAP service for the domain "+domainName,e);
}
DirContext context;
try {
context = LdapCtxFactory.getLdapCtxInstance("ldaps://" + ldapServer + '/', props);
} catch (NamingException e) {
LOGGER.log(Level.WARNING,"Failed to bind to "+ldapServer,e);
throw new BadCredentialsException("Either no such user '"+principalName+"' or incorrect password",e);
}
try {
// locate this user's record
SearchControls controls = new SearchControls();
controls.setSearchScope(SUBTREE_SCOPE);
- NamingEnumeration<SearchResult> renum = context.search(toDC(domainName),"(& (userPrincipalName="+principalName+")(objectClass=user))", controls);
+ NamingEnumeration<SearchResult> renum = context.search(toDC(domainName),"(& (userPrincipalName={0})(objectClass=user))",
+ new Object[]{principalName}, controls);
if(!renum.hasMore()) {
// failed to find it. Fall back to sAMAccountName.
// see http://www.nabble.com/Re%3A-Hudson-AD-plug-in-td21428668.html
- renum = context.search(toDC(domainName),"(& (sAMAccountName="+username+")(objectClass=user))", controls);
+ renum = context.search(toDC(domainName),"(& (sAMAccountName="+username+")(objectClass=user))",
+ new Object[]{username},controls);
if(!renum.hasMore()) {
throw new BadCredentialsException("Authentication was successful but cannot locate the user information for "+username);
}
}
SearchResult result = renum.next();
Attribute memberOf = result.getAttributes().get("memberOf");
Set<GrantedAuthority> groups = resolveGroups(memberOf, context);
groups.add(SecurityRealm.AUTHENTICATED_AUTHORITY);
context.close();
return new ActiveDirectoryUserDetail(
username, password,
true, true, true, true,
groups.toArray(new GrantedAuthority[groups.size()])
);
} catch (NamingException e) {
LOGGER.log(Level.WARNING,"Failed to retrieve user information for "+username,e);
throw new BadCredentialsException("Failed to retrieve user information for "+username,e);
}
} finally {
Thread.currentThread().setContextClassLoader(ccl);
}
}
private Set<GrantedAuthority> resolveGroups(Attribute memberOf, DirContext context) throws NamingException {
Set<GrantedAuthority> groups = new HashSet<GrantedAuthority>();
LinkedList<Attribute> membershipList = new LinkedList<Attribute>();
membershipList.add(memberOf);
while (!membershipList.isEmpty()) {
Attribute memberships = membershipList.removeFirst();
if (memberships != null) {
for (int i=0; i < memberships.size() ; i++) {
Attributes atts = context.getAttributes("\"" + memberships.get(i) + '"',
new String[] {"CN", "memberOf"});
Attribute cn = atts.get("CN");
if (groups.add(new GrantedAuthorityImpl(cn.get().toString()))) {
Attribute members = atts.get("memberOf");
if (members != null) {
membershipList.add(members);
}
}
}
}
}
return groups;
}
private static String toDC(String domainName) {
StringBuilder buf = new StringBuilder();
for (String token : domainName.split("\\.")) {
if(token.length()==0) continue; // defensive check
if(buf.length()>0) buf.append(",");
buf.append("DC=").append(token);
}
return buf.toString();
}
private static final Logger LOGGER = Logger.getLogger(ActiveDirectoryUnixAuthenticationProvider.class.getName());
public GroupDetails loadGroupByGroupname(String groupname) {
throw new UserMayOrMayNotExistException(groupname);
}
}
| false | true | private UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication, String domainName) throws AuthenticationException {
// when we use custom socket factory below, every LDAP operations result in a classloading via context classloader,
// so we need it to resolve.
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
try {
String password = null;
if(authentication!=null)
password = (String) authentication.getCredentials();
// bind by using the specified username/password
Hashtable props = new Hashtable();
String principalName = username + '@' + domainName;
props.put(Context.SECURITY_PRINCIPAL, principalName);
props.put(Context.SECURITY_CREDENTIALS,password);
props.put(Context.REFERRAL, "follow");
// specifying custom socket factory requires a custom classloader.
props.put("java.naming.ldap.factory.socket", TrustAllSocketFactory.class.getName());
SocketInfo ldapServer;
try {
ldapServer = DesciprotrImpl.INSTANCE.obtainLDAPServer(domainName);
} catch (NamingException e) {
LOGGER.log(Level.WARNING,"Failed to find the LDAP service",e);
throw new AuthenticationServiceException("Failed to find the LDAP service for the domain "+domainName,e);
}
DirContext context;
try {
context = LdapCtxFactory.getLdapCtxInstance("ldaps://" + ldapServer + '/', props);
} catch (NamingException e) {
LOGGER.log(Level.WARNING,"Failed to bind to "+ldapServer,e);
throw new BadCredentialsException("Either no such user '"+principalName+"' or incorrect password",e);
}
try {
// locate this user's record
SearchControls controls = new SearchControls();
controls.setSearchScope(SUBTREE_SCOPE);
NamingEnumeration<SearchResult> renum = context.search(toDC(domainName),"(& (userPrincipalName="+principalName+")(objectClass=user))", controls);
if(!renum.hasMore()) {
// failed to find it. Fall back to sAMAccountName.
// see http://www.nabble.com/Re%3A-Hudson-AD-plug-in-td21428668.html
renum = context.search(toDC(domainName),"(& (sAMAccountName="+username+")(objectClass=user))", controls);
if(!renum.hasMore()) {
throw new BadCredentialsException("Authentication was successful but cannot locate the user information for "+username);
}
}
SearchResult result = renum.next();
Attribute memberOf = result.getAttributes().get("memberOf");
Set<GrantedAuthority> groups = resolveGroups(memberOf, context);
groups.add(SecurityRealm.AUTHENTICATED_AUTHORITY);
context.close();
return new ActiveDirectoryUserDetail(
username, password,
true, true, true, true,
groups.toArray(new GrantedAuthority[groups.size()])
);
} catch (NamingException e) {
LOGGER.log(Level.WARNING,"Failed to retrieve user information for "+username,e);
throw new BadCredentialsException("Failed to retrieve user information for "+username,e);
}
} finally {
Thread.currentThread().setContextClassLoader(ccl);
}
}
| private UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication, String domainName) throws AuthenticationException {
// when we use custom socket factory below, every LDAP operations result in a classloading via context classloader,
// so we need it to resolve.
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
try {
String password = null;
if(authentication!=null)
password = (String) authentication.getCredentials();
// bind by using the specified username/password
Hashtable props = new Hashtable();
String principalName = username + '@' + domainName;
props.put(Context.SECURITY_PRINCIPAL, principalName);
props.put(Context.SECURITY_CREDENTIALS,password);
props.put(Context.REFERRAL, "follow");
// specifying custom socket factory requires a custom classloader.
props.put("java.naming.ldap.factory.socket", TrustAllSocketFactory.class.getName());
SocketInfo ldapServer;
try {
ldapServer = DesciprotrImpl.INSTANCE.obtainLDAPServer(domainName);
} catch (NamingException e) {
LOGGER.log(Level.WARNING,"Failed to find the LDAP service",e);
throw new AuthenticationServiceException("Failed to find the LDAP service for the domain "+domainName,e);
}
DirContext context;
try {
context = LdapCtxFactory.getLdapCtxInstance("ldaps://" + ldapServer + '/', props);
} catch (NamingException e) {
LOGGER.log(Level.WARNING,"Failed to bind to "+ldapServer,e);
throw new BadCredentialsException("Either no such user '"+principalName+"' or incorrect password",e);
}
try {
// locate this user's record
SearchControls controls = new SearchControls();
controls.setSearchScope(SUBTREE_SCOPE);
NamingEnumeration<SearchResult> renum = context.search(toDC(domainName),"(& (userPrincipalName={0})(objectClass=user))",
new Object[]{principalName}, controls);
if(!renum.hasMore()) {
// failed to find it. Fall back to sAMAccountName.
// see http://www.nabble.com/Re%3A-Hudson-AD-plug-in-td21428668.html
renum = context.search(toDC(domainName),"(& (sAMAccountName="+username+")(objectClass=user))",
new Object[]{username},controls);
if(!renum.hasMore()) {
throw new BadCredentialsException("Authentication was successful but cannot locate the user information for "+username);
}
}
SearchResult result = renum.next();
Attribute memberOf = result.getAttributes().get("memberOf");
Set<GrantedAuthority> groups = resolveGroups(memberOf, context);
groups.add(SecurityRealm.AUTHENTICATED_AUTHORITY);
context.close();
return new ActiveDirectoryUserDetail(
username, password,
true, true, true, true,
groups.toArray(new GrantedAuthority[groups.size()])
);
} catch (NamingException e) {
LOGGER.log(Level.WARNING,"Failed to retrieve user information for "+username,e);
throw new BadCredentialsException("Failed to retrieve user information for "+username,e);
}
} finally {
Thread.currentThread().setContextClassLoader(ccl);
}
}
|
diff --git a/src/ca/mcgill/hs/plugin/InputPlugin.java b/src/ca/mcgill/hs/plugin/InputPlugin.java
index 927d40b..4c9e3e0 100644
--- a/src/ca/mcgill/hs/plugin/InputPlugin.java
+++ b/src/ca/mcgill/hs/plugin/InputPlugin.java
@@ -1,24 +1,24 @@
package ca.mcgill.hs.plugin;
import ca.mcgill.hs.serv.HSService;
import android.content.Context;
import android.preference.Preference;
/**
* Abstract class to be extended by all InputPlugins. Provides an interface for using InputPlugins.
*
* @author Cicerone Cojocaru, Jonathan Pitre
*
*/
public abstract class InputPlugin implements Plugin{
protected void write(DataPacket dp){
- //HSService.onDataReady(dp, this);
+ HSService.onDataReady(dp, this);
}
public static Preference[] getPreferences(Context c){return null;}
public static boolean hasPreferences() {return false;}
}
| true | true | protected void write(DataPacket dp){
//HSService.onDataReady(dp, this);
}
| protected void write(DataPacket dp){
HSService.onDataReady(dp, this);
}
|
diff --git a/gerrit-gwtui/src/main/java/com/google/gerrit/client/patches/PatchScriptSettingsPanel.java b/gerrit-gwtui/src/main/java/com/google/gerrit/client/patches/PatchScriptSettingsPanel.java
index 4921f4a21..d1ce86b51 100644
--- a/gerrit-gwtui/src/main/java/com/google/gerrit/client/patches/PatchScriptSettingsPanel.java
+++ b/gerrit-gwtui/src/main/java/com/google/gerrit/client/patches/PatchScriptSettingsPanel.java
@@ -1,218 +1,218 @@
// 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.google.gerrit.client.patches;
import static com.google.gerrit.reviewdb.AccountGeneralPreferences.DEFAULT_CONTEXT;
import static com.google.gerrit.reviewdb.AccountGeneralPreferences.WHOLE_FILE_CONTEXT;
import com.google.gerrit.client.Gerrit;
import com.google.gerrit.client.ui.NpIntTextBox;
import com.google.gerrit.common.data.PatchScriptSettings;
import com.google.gerrit.common.data.PatchScriptSettings.Whitespace;
import com.google.gerrit.prettify.common.PrettySettings;
import com.google.gerrit.reviewdb.Account;
import com.google.gerrit.reviewdb.AccountGeneralPreferences;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.logical.shared.HasValueChangeHandlers;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FocusWidget;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Widget;
public class PatchScriptSettingsPanel extends Composite implements
HasValueChangeHandlers<PatchScriptSettings> {
private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);
interface MyUiBinder extends UiBinder<Widget, PatchScriptSettingsPanel> {
}
private PatchScriptSettings value;
@UiField
ListBox ignoreWhitespace;
@UiField
NpIntTextBox tabWidth;
@UiField
NpIntTextBox colWidth;
@UiField
CheckBox syntaxHighlighting;
@UiField
CheckBox intralineDifference;
@UiField
CheckBox showFullFile;
@UiField
CheckBox whitespaceErrors;
@UiField
CheckBox showTabs;
@UiField
CheckBox reviewed;
@UiField
Button update;
public PatchScriptSettingsPanel() {
initWidget(uiBinder.createAndBindUi(this));
initIgnoreWhitespace(ignoreWhitespace);
if (!Gerrit.isSignedIn()) {
reviewed.setVisible(false);
}
KeyPressHandler onEnter = new KeyPressHandler() {
@Override
public void onKeyPress(KeyPressEvent event) {
if (event.getCharCode() == KeyCodes.KEY_ENTER) {
update();
}
}
};
tabWidth.addKeyPressHandler(onEnter);
colWidth.addKeyPressHandler(onEnter);
final PatchScriptSettings s = new PatchScriptSettings();
if (Gerrit.isSignedIn()) {
final Account u = Gerrit.getUserAccount();
final AccountGeneralPreferences pref = u.getGeneralPreferences();
s.setContext(pref.getDefaultContext());
} else {
s.setContext(DEFAULT_CONTEXT);
}
setValue(s);
}
@Override
public HandlerRegistration addValueChangeHandler(
ValueChangeHandler<PatchScriptSettings> handler) {
return super.addHandler(handler, ValueChangeEvent.getType());
}
public void setEnabled(final boolean on) {
for (Widget w : (HasWidgets) getWidget()) {
if (w instanceof FocusWidget) {
((FocusWidget) w).setEnabled(on);
}
}
}
public CheckBox getReviewedCheckBox() {
return reviewed;
}
public PatchScriptSettings getValue() {
return value;
}
public void setValue(final PatchScriptSettings s) {
final PrettySettings p = s.getPrettySettings();
setIgnoreWhitespace(s.getWhitespace());
showFullFile.setValue(s.getContext() == WHOLE_FILE_CONTEXT);
tabWidth.setIntValue(p.getTabSize());
colWidth.setIntValue(p.getLineLength());
syntaxHighlighting.setValue(p.isSyntaxHighlighting());
intralineDifference.setValue(p.isIntralineDifference());
whitespaceErrors.setValue(p.isShowWhiteSpaceErrors());
showTabs.setValue(p.isShowTabs());
value = s;
}
@UiHandler("update")
void onUpdate(ClickEvent event) {
update();
}
private void update() {
PatchScriptSettings s = new PatchScriptSettings(getValue());
PrettySettings p = s.getPrettySettings();
s.setWhitespace(getIgnoreWhitespace());
if (showFullFile.getValue()) {
s.setContext(WHOLE_FILE_CONTEXT);
} else if (Gerrit.isSignedIn()) {
final Account u = Gerrit.getUserAccount();
final AccountGeneralPreferences pref = u.getGeneralPreferences();
if (pref.getDefaultContext() == WHOLE_FILE_CONTEXT) {
s.setContext(DEFAULT_CONTEXT);
} else {
s.setContext(pref.getDefaultContext());
}
} else {
s.setContext(DEFAULT_CONTEXT);
}
p.setTabSize(tabWidth.getIntValue());
p.setLineLength(colWidth.getIntValue());
p.setSyntaxHighlighting(syntaxHighlighting.getValue());
p.setIntralineDifference(intralineDifference.getValue());
p.setShowWhiteSpaceErrors(whitespaceErrors.getValue());
- p.setShowTabs(p.isShowTabs());
+ p.setShowTabs(showTabs.getValue());
value = s;
fireEvent(new ValueChangeEvent<PatchScriptSettings>(s) {});
}
private void initIgnoreWhitespace(ListBox ws) {
ws.addItem(PatchUtil.C.whitespaceIGNORE_NONE(), //
Whitespace.IGNORE_NONE.name());
ws.addItem(PatchUtil.C.whitespaceIGNORE_SPACE_AT_EOL(), //
Whitespace.IGNORE_SPACE_AT_EOL.name());
ws.addItem(PatchUtil.C.whitespaceIGNORE_SPACE_CHANGE(), //
Whitespace.IGNORE_SPACE_CHANGE.name());
ws.addItem(PatchUtil.C.whitespaceIGNORE_ALL_SPACE(), //
Whitespace.IGNORE_ALL_SPACE.name());
}
private Whitespace getIgnoreWhitespace() {
final int sel = ignoreWhitespace.getSelectedIndex();
if (0 <= sel) {
return Whitespace.valueOf(ignoreWhitespace.getValue(sel));
}
return value.getWhitespace();
}
private void setIgnoreWhitespace(Whitespace s) {
for (int i = 0; i < ignoreWhitespace.getItemCount(); i++) {
if (ignoreWhitespace.getValue(i).equals(s.name())) {
ignoreWhitespace.setSelectedIndex(i);
return;
}
}
ignoreWhitespace.setSelectedIndex(0);
}
}
| true | true | private void update() {
PatchScriptSettings s = new PatchScriptSettings(getValue());
PrettySettings p = s.getPrettySettings();
s.setWhitespace(getIgnoreWhitespace());
if (showFullFile.getValue()) {
s.setContext(WHOLE_FILE_CONTEXT);
} else if (Gerrit.isSignedIn()) {
final Account u = Gerrit.getUserAccount();
final AccountGeneralPreferences pref = u.getGeneralPreferences();
if (pref.getDefaultContext() == WHOLE_FILE_CONTEXT) {
s.setContext(DEFAULT_CONTEXT);
} else {
s.setContext(pref.getDefaultContext());
}
} else {
s.setContext(DEFAULT_CONTEXT);
}
p.setTabSize(tabWidth.getIntValue());
p.setLineLength(colWidth.getIntValue());
p.setSyntaxHighlighting(syntaxHighlighting.getValue());
p.setIntralineDifference(intralineDifference.getValue());
p.setShowWhiteSpaceErrors(whitespaceErrors.getValue());
p.setShowTabs(p.isShowTabs());
value = s;
fireEvent(new ValueChangeEvent<PatchScriptSettings>(s) {});
}
| private void update() {
PatchScriptSettings s = new PatchScriptSettings(getValue());
PrettySettings p = s.getPrettySettings();
s.setWhitespace(getIgnoreWhitespace());
if (showFullFile.getValue()) {
s.setContext(WHOLE_FILE_CONTEXT);
} else if (Gerrit.isSignedIn()) {
final Account u = Gerrit.getUserAccount();
final AccountGeneralPreferences pref = u.getGeneralPreferences();
if (pref.getDefaultContext() == WHOLE_FILE_CONTEXT) {
s.setContext(DEFAULT_CONTEXT);
} else {
s.setContext(pref.getDefaultContext());
}
} else {
s.setContext(DEFAULT_CONTEXT);
}
p.setTabSize(tabWidth.getIntValue());
p.setLineLength(colWidth.getIntValue());
p.setSyntaxHighlighting(syntaxHighlighting.getValue());
p.setIntralineDifference(intralineDifference.getValue());
p.setShowWhiteSpaceErrors(whitespaceErrors.getValue());
p.setShowTabs(showTabs.getValue());
value = s;
fireEvent(new ValueChangeEvent<PatchScriptSettings>(s) {});
}
|
diff --git a/src/main/java/grisu/control/util/AuditAdvice.java b/src/main/java/grisu/control/util/AuditAdvice.java
index f405086..255cc1e 100644
--- a/src/main/java/grisu/control/util/AuditAdvice.java
+++ b/src/main/java/grisu/control/util/AuditAdvice.java
@@ -1,106 +1,106 @@
package grisu.control.util;
import grisu.control.GrisuUserDetails;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
public class AuditAdvice implements MethodInterceptor {
public static AtomicInteger numberOfOpenMethodCalls = new AtomicInteger(0);
static final Logger myLogger = Logger
.getLogger(AuditAdvice.class.getName());
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
String method = methodInvocation.getMethod().getName();
String dn = null;
Object[] argOs = methodInvocation.getArguments();
String argList = "NO_ARGS";
if ((argOs != null) && (argOs.length > 0)) {
String[] args = new String[argOs.length];
for (int i = 0; i < args.length; i++) {
try {
if (argOs[i] == null) {
args[i] = "null";
} else {
args[i] = (argOs[i]).toString();
}
} catch (Exception e) {
args[i] = "Error serializing object";
}
}
argList = StringUtils.join(args, ";");
}
final SecurityContext securityContext = SecurityContextHolder
.getContext();
final Authentication authentication = securityContext
.getAuthentication();
if (authentication != null) {
final Object principal = authentication.getPrincipal();
if (principal instanceof GrisuUserDetails) {
GrisuUserDetails gud = (GrisuUserDetails) principal;
dn = gud.getProxyCredential().getDn();
}
}
Date start = new Date();
int number = numberOfOpenMethodCalls.incrementAndGet();
if (dn == null) {
myLogger.debug("Entering method: " + method + " arguments: "
+ argList + " time: " + start.getTime()
+ " open method calls: " + number);
} else {
myLogger.debug("Entering method: " + method + " arguments: "
+ argList + " user: " + dn + " time: " + start.getTime()
+ " open method calls: " + number);
}
- Object result = methodInvocation.proceed();
+ Object result = null;
try {
result = methodInvocation.proceed();
} catch (Throwable t) {
number = numberOfOpenMethodCalls.decrementAndGet();
Date end = new Date();
long duration = end.getTime() - start.getTime();
myLogger.debug("Method call: " + method + " failed: "
+ t.getLocalizedMessage());
myLogger.debug("Finished method: " + method + " arguments: "
+ argList + " time: " + end.getTime() + " duration: "
+ duration + " open method calls: " + number);
throw t;
}
number = numberOfOpenMethodCalls.decrementAndGet();
Date end = new Date();
long duration = end.getTime() - start.getTime();
if (dn == null) {
myLogger.debug("Finished method: " + method + " arguments: "
+ argList + " time: " + end.getTime() + " duration: "
+ duration + " open method calls: " + number);
} else {
myLogger.debug("Finished method: " + method + " arguments: "
+ argList + " user: " + dn + " time: " + end.getTime()
+ " duration: " + duration + " open method calls: "
+ number);
}
return result;
}
}
| true | true | public Object invoke(MethodInvocation methodInvocation) throws Throwable {
String method = methodInvocation.getMethod().getName();
String dn = null;
Object[] argOs = methodInvocation.getArguments();
String argList = "NO_ARGS";
if ((argOs != null) && (argOs.length > 0)) {
String[] args = new String[argOs.length];
for (int i = 0; i < args.length; i++) {
try {
if (argOs[i] == null) {
args[i] = "null";
} else {
args[i] = (argOs[i]).toString();
}
} catch (Exception e) {
args[i] = "Error serializing object";
}
}
argList = StringUtils.join(args, ";");
}
final SecurityContext securityContext = SecurityContextHolder
.getContext();
final Authentication authentication = securityContext
.getAuthentication();
if (authentication != null) {
final Object principal = authentication.getPrincipal();
if (principal instanceof GrisuUserDetails) {
GrisuUserDetails gud = (GrisuUserDetails) principal;
dn = gud.getProxyCredential().getDn();
}
}
Date start = new Date();
int number = numberOfOpenMethodCalls.incrementAndGet();
if (dn == null) {
myLogger.debug("Entering method: " + method + " arguments: "
+ argList + " time: " + start.getTime()
+ " open method calls: " + number);
} else {
myLogger.debug("Entering method: " + method + " arguments: "
+ argList + " user: " + dn + " time: " + start.getTime()
+ " open method calls: " + number);
}
Object result = methodInvocation.proceed();
try {
result = methodInvocation.proceed();
} catch (Throwable t) {
number = numberOfOpenMethodCalls.decrementAndGet();
Date end = new Date();
long duration = end.getTime() - start.getTime();
myLogger.debug("Method call: " + method + " failed: "
+ t.getLocalizedMessage());
myLogger.debug("Finished method: " + method + " arguments: "
+ argList + " time: " + end.getTime() + " duration: "
+ duration + " open method calls: " + number);
throw t;
}
number = numberOfOpenMethodCalls.decrementAndGet();
Date end = new Date();
long duration = end.getTime() - start.getTime();
if (dn == null) {
myLogger.debug("Finished method: " + method + " arguments: "
+ argList + " time: " + end.getTime() + " duration: "
+ duration + " open method calls: " + number);
} else {
myLogger.debug("Finished method: " + method + " arguments: "
+ argList + " user: " + dn + " time: " + end.getTime()
+ " duration: " + duration + " open method calls: "
+ number);
}
return result;
}
| public Object invoke(MethodInvocation methodInvocation) throws Throwable {
String method = methodInvocation.getMethod().getName();
String dn = null;
Object[] argOs = methodInvocation.getArguments();
String argList = "NO_ARGS";
if ((argOs != null) && (argOs.length > 0)) {
String[] args = new String[argOs.length];
for (int i = 0; i < args.length; i++) {
try {
if (argOs[i] == null) {
args[i] = "null";
} else {
args[i] = (argOs[i]).toString();
}
} catch (Exception e) {
args[i] = "Error serializing object";
}
}
argList = StringUtils.join(args, ";");
}
final SecurityContext securityContext = SecurityContextHolder
.getContext();
final Authentication authentication = securityContext
.getAuthentication();
if (authentication != null) {
final Object principal = authentication.getPrincipal();
if (principal instanceof GrisuUserDetails) {
GrisuUserDetails gud = (GrisuUserDetails) principal;
dn = gud.getProxyCredential().getDn();
}
}
Date start = new Date();
int number = numberOfOpenMethodCalls.incrementAndGet();
if (dn == null) {
myLogger.debug("Entering method: " + method + " arguments: "
+ argList + " time: " + start.getTime()
+ " open method calls: " + number);
} else {
myLogger.debug("Entering method: " + method + " arguments: "
+ argList + " user: " + dn + " time: " + start.getTime()
+ " open method calls: " + number);
}
Object result = null;
try {
result = methodInvocation.proceed();
} catch (Throwable t) {
number = numberOfOpenMethodCalls.decrementAndGet();
Date end = new Date();
long duration = end.getTime() - start.getTime();
myLogger.debug("Method call: " + method + " failed: "
+ t.getLocalizedMessage());
myLogger.debug("Finished method: " + method + " arguments: "
+ argList + " time: " + end.getTime() + " duration: "
+ duration + " open method calls: " + number);
throw t;
}
number = numberOfOpenMethodCalls.decrementAndGet();
Date end = new Date();
long duration = end.getTime() - start.getTime();
if (dn == null) {
myLogger.debug("Finished method: " + method + " arguments: "
+ argList + " time: " + end.getTime() + " duration: "
+ duration + " open method calls: " + number);
} else {
myLogger.debug("Finished method: " + method + " arguments: "
+ argList + " user: " + dn + " time: " + end.getTime()
+ " duration: " + duration + " open method calls: "
+ number);
}
return result;
}
|
diff --git a/src/web/org/openmrs/web/controller/user/UserFormController.java b/src/web/org/openmrs/web/controller/user/UserFormController.java
index 82e6b047..5a9aa360 100644
--- a/src/web/org/openmrs/web/controller/user/UserFormController.java
+++ b/src/web/org/openmrs/web/controller/user/UserFormController.java
@@ -1,279 +1,279 @@
/**
* The contents of this file are subject to the OpenMRS Public 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://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.web.controller.user;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Person;
import org.openmrs.PersonName;
import org.openmrs.Role;
import org.openmrs.User;
import org.openmrs.api.PasswordException;
import org.openmrs.api.UserService;
import org.openmrs.api.context.Context;
import org.openmrs.messagesource.MessageSourceService;
import org.openmrs.propertyeditor.RoleEditor;
import org.openmrs.util.OpenmrsConstants;
import org.openmrs.util.OpenmrsUtil;
import org.openmrs.validator.UserValidator;
import org.openmrs.web.WebConstants;
import org.openmrs.web.user.UserProperties;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.WebRequest;
/**
* Used for creating/editing User
*/
@Controller
public class UserFormController {
protected static final Log log = LogFactory.getLog(UserFormController.class);
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Role.class, new RoleEditor());
}
// the personId attribute is called person_id so that spring MVC doesn't try to bind it to the personId property of user
@ModelAttribute("user")
public User formBackingObject(WebRequest request,
@RequestParam(required=false, value="person_id") Integer personId) {
String userId = request.getParameter("userId");
User u = null;
try {
u = Context.getUserService().getUser(Integer.valueOf(userId));
} catch (Exception ex) { }
if (u == null) {
u = new User();
}
if (personId != null) {
u.setPerson(Context.getPersonService().getPerson(personId));
} else if (u.getPerson() == null) {
Person p = new Person();
p.addName(new PersonName());
u.setPerson(p);
}
return u;
}
@ModelAttribute("allRoles")
public List<Role> getRoles(WebRequest request) {
List<Role> roles = Context.getUserService().getAllRoles();
if (roles == null)
roles = new Vector<Role>();
for (String s : OpenmrsConstants.AUTO_ROLES()) {
Role r = new Role(s);
roles.remove(r);
}
return roles;
}
@RequestMapping(value="/admin/users/user.form", method=RequestMethod.GET)
public String showForm(@RequestParam(required=false, value="userId") Integer userId,
@RequestParam(required=false, value="createNewPerson") String createNewPerson,
@ModelAttribute("user") User user,
ModelMap model) {
// the formBackingObject method above sets up user, depending on userId and personId parameters
model.addAttribute("isNewUser", isNewUser(user));
if (isNewUser(user) || Context.hasPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS))
model.addAttribute("modifyPasswords", true);
if (createNewPerson != null)
model.addAttribute("createNewPerson", createNewPerson);
if(!isNewUser(user))
model.addAttribute("changePassword",new UserProperties(user.getUserProperties()).isSupposedToChangePassword());
// not using the default view name because I'm converting from an existing form
return "admin/users/userForm";
}
/**
* @should work for an example
*/
@RequestMapping(value="/admin/users/user.form", method=RequestMethod.POST)
public String handleSubmission(WebRequest request,
HttpSession httpSession,
ModelMap model,
@RequestParam(required=false, value="action") String action,
@RequestParam(required=false, value="userFormPassword") String password,
@RequestParam(required=false, value="secretQuestion") String secretQuestion,
@RequestParam(required=false, value="secretAnswer") String secretAnswer,
@RequestParam(required=false, value="confirm") String confirm,
@RequestParam(required=false, value="forcePassword") Boolean forcePassword,
@RequestParam(required=false, value="roleStrings") String[] roles,
@RequestParam(required=false, value="createNewPerson") String createNewPerson,
@ModelAttribute("user") User user, BindingResult errors) {
UserService us = Context.getUserService();
MessageSourceService mss = Context.getMessageSourceService();
if (!Context.isAuthenticated()) {
errors.reject("auth.invalid");
} else if (mss.getMessage("User.assumeIdentity").equals(action)) {
Context.becomeUser(user.getSystemId());
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.assumeIdentity.success");
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ARGS, user.getPersonName());
return "redirect:/index.htm";
} else if (mss.getMessage("User.delete").equals(action)) {
try {
Context.getUserService().purgeUser(user);
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.delete.success");
} catch (Exception ex) {
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.delete.failure");
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ARGS, ex.getMessage());
log.error("Failed to delete user", ex);
}
return "redirect:/index.htm";
} else if (mss.getMessage("User.retire").equals(action)) {
String retireReason = request.getParameter("retireReason");
if (!(StringUtils.hasText(retireReason))) {
errors.rejectValue("retireReason", "general.retiredReason.empty");
return showForm(user.getUserId(), createNewPerson, user, model);
} else {
us.retireUser(user, retireReason);
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.retiredMessage");
}
} else if(mss.getMessage("User.unRetire").equals(action)) {
us.unretireUser(user);
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.unRetiredMessage");
}else {
// check if username is already in the database
if (us.hasDuplicateUsername(user))
errors.rejectValue("username", "error.username.taken");
// check if password and password confirm are identical
if (password == null || password.equals("XXXXXXXXXXXXXXX"))
password = "";
if (confirm == null || confirm.equals("XXXXXXXXXXXXXXX"))
confirm = "";
if (!password.equals(confirm))
errors.reject("error.password.match");
if (password.length() == 0 && isNewUser(user))
errors.reject("error.password.weak");
//check password strength
if (password.length() > 0) {
try {
OpenmrsUtil.validatePassword(user.getUsername(), password, user.getSystemId());
}
catch (PasswordException e) {
errors.reject(e.getMessage());
}
}
Set<Role> newRoles = new HashSet<Role>();
if (roles != null) {
for (String r : roles) {
// Make sure that if we already have a detached instance of this role in the
// user's roles, that we don't fetch a second copy of that same role from
// the database, or else hibernate will throw a NonUniqueObjectException.
Role role = null;
if (user.getRoles() != null)
for (Role test : user.getRoles())
if (test.getRole().equals(r))
role = test;
if (role == null) {
role = us.getRole(r);
user.addRole(role);
}
newRoles.add(role);
}
}
if (user.getRoles() == null)
newRoles.clear();
else
user.getRoles().retainAll(newRoles);
String[] keys = request.getParameterValues("property");
String[] values = request.getParameterValues("value");
if (keys != null && values != null) {
for (int x = 0; x < keys.length; x++) {
String key = keys[x];
String val = values[x];
user.setUserProperty(key, val);
}
}
new UserProperties(user.getUserProperties()).setSupposedToChangePassword(forcePassword);
UserValidator uv = new UserValidator();
uv.validate(user, errors);
if (errors.hasErrors()) {
return showForm(user.getUserId(), createNewPerson, user, model);
}
if (isNewUser(user)){
us.saveUser(user, password);
} else {
us.saveUser(user, null);
if (!password.equals("") && Context.hasPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS)) {
if (log.isDebugEnabled())
log.debug("calling changePassword for user " + user + " by user " + Context.getAuthenticatedUser());
us.changePassword(user, password);
}
}
- if (StringUtils.hasLength(secretQuestion) || StringUtils.hasLength(secretAnswer)) {
+ if (StringUtils.hasLength(secretQuestion) && StringUtils.hasLength(secretAnswer)) {
us.changeQuestionAnswer(user, secretQuestion, secretAnswer);
}
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.saved");
}
return "redirect:user.list";
}
/**
* Superficially determines if this form is being filled out for a new user (basically just
* looks for a primary key (user_id)
*
* @param user
* @return true/false if this user is new
*/
private Boolean isNewUser(User user) {
return user == null ? true : user.getUserId() == null;
}
}
| true | true | public String handleSubmission(WebRequest request,
HttpSession httpSession,
ModelMap model,
@RequestParam(required=false, value="action") String action,
@RequestParam(required=false, value="userFormPassword") String password,
@RequestParam(required=false, value="secretQuestion") String secretQuestion,
@RequestParam(required=false, value="secretAnswer") String secretAnswer,
@RequestParam(required=false, value="confirm") String confirm,
@RequestParam(required=false, value="forcePassword") Boolean forcePassword,
@RequestParam(required=false, value="roleStrings") String[] roles,
@RequestParam(required=false, value="createNewPerson") String createNewPerson,
@ModelAttribute("user") User user, BindingResult errors) {
UserService us = Context.getUserService();
MessageSourceService mss = Context.getMessageSourceService();
if (!Context.isAuthenticated()) {
errors.reject("auth.invalid");
} else if (mss.getMessage("User.assumeIdentity").equals(action)) {
Context.becomeUser(user.getSystemId());
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.assumeIdentity.success");
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ARGS, user.getPersonName());
return "redirect:/index.htm";
} else if (mss.getMessage("User.delete").equals(action)) {
try {
Context.getUserService().purgeUser(user);
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.delete.success");
} catch (Exception ex) {
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.delete.failure");
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ARGS, ex.getMessage());
log.error("Failed to delete user", ex);
}
return "redirect:/index.htm";
} else if (mss.getMessage("User.retire").equals(action)) {
String retireReason = request.getParameter("retireReason");
if (!(StringUtils.hasText(retireReason))) {
errors.rejectValue("retireReason", "general.retiredReason.empty");
return showForm(user.getUserId(), createNewPerson, user, model);
} else {
us.retireUser(user, retireReason);
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.retiredMessage");
}
} else if(mss.getMessage("User.unRetire").equals(action)) {
us.unretireUser(user);
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.unRetiredMessage");
}else {
// check if username is already in the database
if (us.hasDuplicateUsername(user))
errors.rejectValue("username", "error.username.taken");
// check if password and password confirm are identical
if (password == null || password.equals("XXXXXXXXXXXXXXX"))
password = "";
if (confirm == null || confirm.equals("XXXXXXXXXXXXXXX"))
confirm = "";
if (!password.equals(confirm))
errors.reject("error.password.match");
if (password.length() == 0 && isNewUser(user))
errors.reject("error.password.weak");
//check password strength
if (password.length() > 0) {
try {
OpenmrsUtil.validatePassword(user.getUsername(), password, user.getSystemId());
}
catch (PasswordException e) {
errors.reject(e.getMessage());
}
}
Set<Role> newRoles = new HashSet<Role>();
if (roles != null) {
for (String r : roles) {
// Make sure that if we already have a detached instance of this role in the
// user's roles, that we don't fetch a second copy of that same role from
// the database, or else hibernate will throw a NonUniqueObjectException.
Role role = null;
if (user.getRoles() != null)
for (Role test : user.getRoles())
if (test.getRole().equals(r))
role = test;
if (role == null) {
role = us.getRole(r);
user.addRole(role);
}
newRoles.add(role);
}
}
if (user.getRoles() == null)
newRoles.clear();
else
user.getRoles().retainAll(newRoles);
String[] keys = request.getParameterValues("property");
String[] values = request.getParameterValues("value");
if (keys != null && values != null) {
for (int x = 0; x < keys.length; x++) {
String key = keys[x];
String val = values[x];
user.setUserProperty(key, val);
}
}
new UserProperties(user.getUserProperties()).setSupposedToChangePassword(forcePassword);
UserValidator uv = new UserValidator();
uv.validate(user, errors);
if (errors.hasErrors()) {
return showForm(user.getUserId(), createNewPerson, user, model);
}
if (isNewUser(user)){
us.saveUser(user, password);
} else {
us.saveUser(user, null);
if (!password.equals("") && Context.hasPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS)) {
if (log.isDebugEnabled())
log.debug("calling changePassword for user " + user + " by user " + Context.getAuthenticatedUser());
us.changePassword(user, password);
}
}
if (StringUtils.hasLength(secretQuestion) || StringUtils.hasLength(secretAnswer)) {
us.changeQuestionAnswer(user, secretQuestion, secretAnswer);
}
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.saved");
}
return "redirect:user.list";
}
| public String handleSubmission(WebRequest request,
HttpSession httpSession,
ModelMap model,
@RequestParam(required=false, value="action") String action,
@RequestParam(required=false, value="userFormPassword") String password,
@RequestParam(required=false, value="secretQuestion") String secretQuestion,
@RequestParam(required=false, value="secretAnswer") String secretAnswer,
@RequestParam(required=false, value="confirm") String confirm,
@RequestParam(required=false, value="forcePassword") Boolean forcePassword,
@RequestParam(required=false, value="roleStrings") String[] roles,
@RequestParam(required=false, value="createNewPerson") String createNewPerson,
@ModelAttribute("user") User user, BindingResult errors) {
UserService us = Context.getUserService();
MessageSourceService mss = Context.getMessageSourceService();
if (!Context.isAuthenticated()) {
errors.reject("auth.invalid");
} else if (mss.getMessage("User.assumeIdentity").equals(action)) {
Context.becomeUser(user.getSystemId());
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.assumeIdentity.success");
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ARGS, user.getPersonName());
return "redirect:/index.htm";
} else if (mss.getMessage("User.delete").equals(action)) {
try {
Context.getUserService().purgeUser(user);
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.delete.success");
} catch (Exception ex) {
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.delete.failure");
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ARGS, ex.getMessage());
log.error("Failed to delete user", ex);
}
return "redirect:/index.htm";
} else if (mss.getMessage("User.retire").equals(action)) {
String retireReason = request.getParameter("retireReason");
if (!(StringUtils.hasText(retireReason))) {
errors.rejectValue("retireReason", "general.retiredReason.empty");
return showForm(user.getUserId(), createNewPerson, user, model);
} else {
us.retireUser(user, retireReason);
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.retiredMessage");
}
} else if(mss.getMessage("User.unRetire").equals(action)) {
us.unretireUser(user);
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.unRetiredMessage");
}else {
// check if username is already in the database
if (us.hasDuplicateUsername(user))
errors.rejectValue("username", "error.username.taken");
// check if password and password confirm are identical
if (password == null || password.equals("XXXXXXXXXXXXXXX"))
password = "";
if (confirm == null || confirm.equals("XXXXXXXXXXXXXXX"))
confirm = "";
if (!password.equals(confirm))
errors.reject("error.password.match");
if (password.length() == 0 && isNewUser(user))
errors.reject("error.password.weak");
//check password strength
if (password.length() > 0) {
try {
OpenmrsUtil.validatePassword(user.getUsername(), password, user.getSystemId());
}
catch (PasswordException e) {
errors.reject(e.getMessage());
}
}
Set<Role> newRoles = new HashSet<Role>();
if (roles != null) {
for (String r : roles) {
// Make sure that if we already have a detached instance of this role in the
// user's roles, that we don't fetch a second copy of that same role from
// the database, or else hibernate will throw a NonUniqueObjectException.
Role role = null;
if (user.getRoles() != null)
for (Role test : user.getRoles())
if (test.getRole().equals(r))
role = test;
if (role == null) {
role = us.getRole(r);
user.addRole(role);
}
newRoles.add(role);
}
}
if (user.getRoles() == null)
newRoles.clear();
else
user.getRoles().retainAll(newRoles);
String[] keys = request.getParameterValues("property");
String[] values = request.getParameterValues("value");
if (keys != null && values != null) {
for (int x = 0; x < keys.length; x++) {
String key = keys[x];
String val = values[x];
user.setUserProperty(key, val);
}
}
new UserProperties(user.getUserProperties()).setSupposedToChangePassword(forcePassword);
UserValidator uv = new UserValidator();
uv.validate(user, errors);
if (errors.hasErrors()) {
return showForm(user.getUserId(), createNewPerson, user, model);
}
if (isNewUser(user)){
us.saveUser(user, password);
} else {
us.saveUser(user, null);
if (!password.equals("") && Context.hasPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS)) {
if (log.isDebugEnabled())
log.debug("calling changePassword for user " + user + " by user " + Context.getAuthenticatedUser());
us.changePassword(user, password);
}
}
if (StringUtils.hasLength(secretQuestion) && StringUtils.hasLength(secretAnswer)) {
us.changeQuestionAnswer(user, secretQuestion, secretAnswer);
}
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.saved");
}
return "redirect:user.list";
}
|
diff --git a/source/de/tuclausthal/submissioninterface/servlets/controller/SubmitSolution.java b/source/de/tuclausthal/submissioninterface/servlets/controller/SubmitSolution.java
index 6102886..e6a143d 100644
--- a/source/de/tuclausthal/submissioninterface/servlets/controller/SubmitSolution.java
+++ b/source/de/tuclausthal/submissioninterface/servlets/controller/SubmitSolution.java
@@ -1,473 +1,475 @@
/*
* Copyright 2009 - 2011 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.servlets.controller;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.DiskFileUpload;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUpload;
import org.apache.tomcat.util.http.fileupload.FileUploadBase;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import de.tuclausthal.submissioninterface.dupecheck.normalizers.NormalizerIf;
import de.tuclausthal.submissioninterface.dupecheck.normalizers.impl.StripCommentsNormalizer;
import de.tuclausthal.submissioninterface.persistence.dao.DAOFactory;
import de.tuclausthal.submissioninterface.persistence.dao.ParticipationDAOIf;
import de.tuclausthal.submissioninterface.persistence.dao.SubmissionDAOIf;
import de.tuclausthal.submissioninterface.persistence.dao.TaskDAOIf;
import de.tuclausthal.submissioninterface.persistence.dao.impl.LogDAO;
import de.tuclausthal.submissioninterface.persistence.datamodel.LogEntry.LogAction;
import de.tuclausthal.submissioninterface.persistence.datamodel.Participation;
import de.tuclausthal.submissioninterface.persistence.datamodel.ParticipationRole;
import de.tuclausthal.submissioninterface.persistence.datamodel.Submission;
import de.tuclausthal.submissioninterface.persistence.datamodel.Task;
import de.tuclausthal.submissioninterface.servlets.RequestAdapter;
import de.tuclausthal.submissioninterface.template.Template;
import de.tuclausthal.submissioninterface.template.TemplateFactory;
import de.tuclausthal.submissioninterface.util.ContextAdapter;
import de.tuclausthal.submissioninterface.util.Util;
/**
* Controller-Servlet for the submission of files
* @author Sven Strickroth
*/
public class SubmitSolution extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
Session session = RequestAdapter.getSession(request);
TaskDAOIf taskDAO = DAOFactory.TaskDAOIf(session);
Task task = taskDAO.getTask(Util.parseInteger(request.getParameter("taskid"), 0));
if (task == null) {
request.setAttribute("title", "Aufgabe nicht gefunden");
request.getRequestDispatcher("MessageView").forward(request, response);
return;
}
// check Lecture Participation
ParticipationDAOIf participationDAO = DAOFactory.ParticipationDAOIf(session);
Participation participation = participationDAO.getParticipation(RequestAdapter.getUser(request), task.getTaskGroup().getLecture());
if (participation == null) {
((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN, "insufficient rights");
return;
}
boolean canUploadForStudents = participation.getRoleType() == ParticipationRole.ADVISOR || (task.isTutorsCanUploadFiles() && participation.getRoleType() == ParticipationRole.TUTOR);
// if session-user is not a tutor (with rights to upload for students) or advisor: check dates
if (!canUploadForStudents) {
if (participation.getRoleType() == ParticipationRole.TUTOR) {
request.setAttribute("title", "Tutoren k�nnen keine eigenen L�sungen einsenden.");
request.getRequestDispatcher("MessageView").forward(request, response);
return;
}
if (task.getStart().after(Util.correctTimezone(new Date()))) {
request.setAttribute("title", "Abgabe nicht gefunden");
request.getRequestDispatcher("MessageView").forward(request, response);
return;
}
if (task.getDeadline().before(Util.correctTimezone(new Date()))) {
request.setAttribute("title", "Abgabe nicht mehr m�glich");
request.getRequestDispatcher("MessageView").forward(request, response);
return;
}
}
if (task.isShowTextArea() == false && "-".equals(task.getFilenameRegexp())) {
request.setAttribute("title", "Das Einsenden von L�sungen ist f�r diese Aufgabe deaktiviert.");
request.getRequestDispatcher("MessageView").forward(request, response);
return;
}
request.setAttribute("task", task);
if (canUploadForStudents) {
request.getRequestDispatcher("SubmitSolutionAdvisorFormView").forward(request, response);
} else {
request.setAttribute("participation", participation);
if (task.isShowTextArea()) {
String textsolution = "";
Submission submission = DAOFactory.SubmissionDAOIf(session).getSubmission(task, RequestAdapter.getUser(request));
if (submission != null) {
ContextAdapter contextAdapter = new ContextAdapter(getServletContext());
File textSolutionFile = new File(contextAdapter.getDataPath().getAbsolutePath() + System.getProperty("file.separator") + task.getTaskGroup().getLecture().getId() + System.getProperty("file.separator") + task.getTaskid() + System.getProperty("file.separator") + submission.getSubmissionid() + System.getProperty("file.separator") + "textloesung.txt");
if (textSolutionFile.exists()) {
BufferedReader bufferedReader = new BufferedReader(new FileReader(textSolutionFile));
StringBuffer sb = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
sb.append(System.getProperty("line.separator"));
}
textsolution = sb.toString();
bufferedReader.close();
}
}
request.setAttribute("textsolution", textsolution);
}
request.getRequestDispatcher("SubmitSolutionFormView").forward(request, response);
}
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
Session session = RequestAdapter.getSession(request);
Template template = TemplateFactory.getTemplate(request, response);
PrintWriter out = response.getWriter();
TaskDAOIf taskDAO = DAOFactory.TaskDAOIf(session);
Task task = taskDAO.getTask(Util.parseInteger(request.getParameter("taskid"), 0));
if (task == null) {
template.printTemplateHeader("Aufgabe nicht gefunden");
out.println("<div class=mid><a href=\"" + response.encodeURL("?") + "\">zur �bersicht</a></div>");
template.printTemplateFooter();
return;
}
// check Lecture Participation
ParticipationDAOIf participationDAO = DAOFactory.ParticipationDAOIf(session);
Participation studentParticipation = participationDAO.getParticipation(RequestAdapter.getUser(request), task.getTaskGroup().getLecture());
if (studentParticipation == null) {
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("<div class=mid>Sie sind kein Teilnehmer dieser Veranstaltung.</div>");
out.println("<div class=mid><a href=\"" + response.encodeURL("Overview") + "\">zur �bersicht</a></div>");
template.printTemplateFooter();
return;
}
//http://commons.apache.org/fileupload/using.html
// Check that we have a file upload request
boolean isMultipart = FileUpload.isMultipartContent(request);
List<Integer> partnerIDs = new LinkedList<Integer>();
int uploadFor = 0;
List<FileItem> items = null;
if (!isMultipart) {
- for (String partnerIdParameter : request.getParameterValues("partnerid")) {
- int partnerID = Util.parseInteger(partnerIdParameter, 0);
- if (partnerID > 0) {
- partnerIDs.add(partnerID);
+ if (request.getParameterValues("partnerid") != null) {
+ for (String partnerIdParameter : request.getParameterValues("partnerid")) {
+ int partnerID = Util.parseInteger(partnerIdParameter, 0);
+ if (partnerID > 0) {
+ partnerIDs.add(partnerID);
+ }
}
}
} else {
// Create a new file upload handler
FileUploadBase upload = new DiskFileUpload();
// Parse the request
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
return;
}
// Process the uploaded items
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
if (item.isFormField() && "partnerid".equals(item.getFieldName())) {
int partnerID = Util.parseInteger(item.getString(), 0);
if (partnerID > 0) {
partnerIDs.add(partnerID);
}
} else if (item.isFormField() && "uploadFor".equals(item.getFieldName())) {
uploadFor = Util.parseInteger(item.getString(), 0);
}
}
}
if (uploadFor > 0) {
// Uploader ist wahrscheinlich Betreuer -> keine zeitlichen Pr�fungen
// check if uploader is allowed to upload for students
if (!(studentParticipation.getRoleType() == ParticipationRole.ADVISOR || (task.isTutorsCanUploadFiles() && studentParticipation.getRoleType() == ParticipationRole.TUTOR))) {
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("<div class=mid>Sie sind nicht berechtigt bei dieser Veranstaltung Dateien f�r Studenten hochzuladen.</div>");
out.println("<div class=mid><a href=\"" + response.encodeURL("Overview") + "\">zur �bersicht</a></div>");
template.printTemplateFooter();
return;
}
studentParticipation = participationDAO.getParticipation(uploadFor);
if (studentParticipation == null || studentParticipation.getLecture().getId() != task.getTaskGroup().getLecture().getId()) {
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("<div class=mid>Der gew�hlte Student ist kein Teilnehmer dieser Veranstaltung.</div>");
out.println("<div class=mid><a href=\"" + response.encodeURL("Overview") + "\">zur �bersicht</a></div>");
template.printTemplateFooter();
return;
}
if (task.isShowTextArea() == false && "-".equals(task.getFilenameRegexp())) {
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("<div class=mid>Das Einsenden von L�sungen ist f�r diese Aufgabe deaktiviert.</div>");
template.printTemplateFooter();
return;
}
} else {
if (studentParticipation.getRoleType() == ParticipationRole.ADVISOR || studentParticipation.getRoleType() == ParticipationRole.TUTOR) {
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("<div class=mid>Betreuer und Tutoren k�nnen keine eigenen L�sungen einsenden.</div>");
template.printTemplateFooter();
return;
}
// Uploader is Student, -> hard date checks
if (task.getStart().after(Util.correctTimezone(new Date()))) {
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("<div class=mid>Abgabe nicht gefunden.</div>");
template.printTemplateFooter();
return;
}
if (task.getDeadline().before(Util.correctTimezone(new Date()))) {
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("<div class=mid>Abgabe nicht mehr m�glich.</div>");
template.printTemplateFooter();
return;
}
if (isMultipart && "-".equals(task.getFilenameRegexp())) {
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("<div class=mid>Dateiupload ist f�r diese Aufgabe deaktiviert.</div>");
template.printTemplateFooter();
return;
} else if (!isMultipart && !task.isShowTextArea()) {
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("<div class=mid>Textl�sungen sind f�r diese Aufgabe deaktiviert.</div>");
template.printTemplateFooter();
return;
}
}
SubmissionDAOIf submissionDAO = DAOFactory.SubmissionDAOIf(session);
Transaction tx = session.beginTransaction();
Submission submission = submissionDAO.createSubmission(task, studentParticipation);
for (int partnerID : partnerIDs) {
Participation partnerParticipation = participationDAO.getParticipation(partnerID);
if (submission.getSubmitters().size() < task.getMaxSubmitters() && partnerParticipation != null && partnerParticipation.getLecture().getId() == task.getTaskGroup().getLecture().getId() && submissionDAO.getSubmissionLocked(task, partnerParticipation.getUser()) == null) {
submission.getSubmitters().add(partnerParticipation);
session.update(submission);
} else {
tx.rollback();
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("<div class=mid>Ein ausgew�hlter Partner hat bereits eine eigene Abgabe initiiert oder Sie haben bereits die maximale Anzahl von Partnern ausgew�hlt.</div>");
template.printTemplateFooter();
return;
}
}
ContextAdapter contextAdapter = new ContextAdapter(getServletContext());
File path = new File(contextAdapter.getDataPath().getAbsolutePath() + System.getProperty("file.separator") + task.getTaskGroup().getLecture().getId() + System.getProperty("file.separator") + task.getTaskid() + System.getProperty("file.separator") + submission.getSubmissionid() + System.getProperty("file.separator"));
if (path.exists() == false) {
path.mkdirs();
}
if (isMultipart) {
// Process the uploaded items
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
// Process a file upload
if (!item.isFormField()) {
Pattern pattern;
if (task.getFilenameRegexp() == null || task.getFilenameRegexp().isEmpty() || uploadFor > 0) {
pattern = Pattern.compile("^(?:.*?\\\\|/)?([a-zA-Z0-9_.-]+)$");
} else {
pattern = Pattern.compile("^(?:.*?\\\\|/)?(" + task.getFilenameRegexp() + ")$");
}
StringBuffer submittedFileName = new StringBuffer(item.getName());
if (submittedFileName.lastIndexOf(".") > 0) {
int lastDot = submittedFileName.lastIndexOf(".");
submittedFileName.replace(lastDot, submittedFileName.length(), submittedFileName.subSequence(lastDot, submittedFileName.length()).toString().toLowerCase());
}
Matcher m = pattern.matcher(submittedFileName);
if (!m.matches()) {
if (!submissionDAO.deleteIfNoFiles(submission, path)) {
submission.setLastModified(new Date());
submissionDAO.saveSubmission(submission);
}
System.out.println("SubmitSolutionProblem2: " + item.getName() + ";" + submittedFileName + ";" + pattern.pattern());
tx.commit();
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("Dateiname ung�ltig bzw. entspricht nicht der Vorgabe (ist ein Klassenname vorgegeben, so muss die Datei genauso hei�en).<br>Tipp: Nur A-Z, a-z, 0-9, ., - und _ sind erlaubt. Evtl. muss der Dateiname mit einem Gro�buchstaben beginnen und darf keine Leerzeichen enthalten.");
if (uploadFor > 0) {
out.println("<br>F�r Experten: Der Dateiname muss dem folgenden regul�ren Ausdruck gen�gen: " + Util.escapeHTML(pattern.pattern()));
}
template.printTemplateFooter();
return;
}
String fileName = m.group(1);
if (!"-".equals(task.getArchiveFilenameRegexp()) && (fileName.endsWith(".zip") || fileName.endsWith(".jar"))) {
ZipInputStream zipFile;
Pattern archivePattern;
if (task.getArchiveFilenameRegexp() == null || task.getArchiveFilenameRegexp().isEmpty()) {
archivePattern = Pattern.compile("^([\\/a-zA-Z0-9_ .-]*([a-zA-Z0-9_ .-]+))$");
} else if (task.getArchiveFilenameRegexp().startsWith("^")) {
archivePattern = Pattern.compile("^(" + task.getArchiveFilenameRegexp().substring(1) + ")$");
} else {
archivePattern = Pattern.compile("^([\\/a-zA-Z0-9_ .-]*(" + task.getArchiveFilenameRegexp() + "))$");
}
try {
zipFile = new ZipInputStream(item.getInputStream());
ZipEntry entry = null;
while ((entry = zipFile.getNextEntry()) != null) {
if (entry.getName().contains("..")) {
continue;
}
StringBuffer archivedFileName = new StringBuffer(entry.getName());
if (!archivePattern.matcher(archivedFileName).matches()) {
System.out.println("Ignored entry: " + archivedFileName);
continue;
}
if (entry.isDirectory() == false && !entry.getName().toLowerCase().endsWith(".class")) {
if (archivedFileName.lastIndexOf(".") > 0) {
int lastDot = archivedFileName.lastIndexOf(".");
archivedFileName.replace(lastDot, archivedFileName.length(), archivedFileName.subSequence(lastDot, archivedFileName.length()).toString().toLowerCase());
}
// TODO: relocate java-files from jar/zip archives?
File fileToCreate = new File(path, archivedFileName.toString());
if (!fileToCreate.getParentFile().exists()) {
fileToCreate.getParentFile().mkdirs();
}
copyInputStream(zipFile, new BufferedOutputStream(new FileOutputStream(fileToCreate)));
}
}
zipFile.close();
} catch (IOException e) {
if (!submissionDAO.deleteIfNoFiles(submission, path)) {
submission.setLastModified(new Date());
submissionDAO.saveSubmission(submission);
}
System.out.println("SubmitSolutionProblem1");
tx.commit();
System.out.println(e.getMessage());
e.printStackTrace();
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("Problem beim Entpacken des Archives.");
template.printTemplateFooter();
return;
}
} else {
File uploadedFile = new File(path, fileName);
// handle .java-files differently in order to extract package and move it to the correct folder
if (fileName.toLowerCase().endsWith(".java")) {
uploadedFile = File.createTempFile("upload", null, path);
}
try {
item.write(uploadedFile);
} catch (Exception e) {
e.printStackTrace();
}
// extract defined package in java-files
if (fileName.toLowerCase().endsWith(".java")) {
NormalizerIf stripComments = new StripCommentsNormalizer();
StringBuffer javaFileContents = stripComments.normalize(Util.loadFile(uploadedFile));
Pattern packagePattern = Pattern.compile(".*package\\s+([a-zA-Z$]([a-zA-Z0-9_$]|\\.[a-zA-Z0-9_$])*)\\s*;.*", Pattern.DOTALL);
Matcher packageMatcher = packagePattern.matcher(javaFileContents);
File destFile = new File(path, fileName);
if (packageMatcher.matches()) {
String packageName = packageMatcher.group(1).replace(".", System.getProperty("file.separator"));
File packageDirectory = new File(path, packageName);
packageDirectory.mkdirs();
destFile = new File(packageDirectory, fileName);
}
if (destFile.exists() && destFile.isFile()) {
destFile.delete();
}
uploadedFile.renameTo(destFile);
}
}
if (!submissionDAO.deleteIfNoFiles(submission, path)) {
submission.setLastModified(new Date());
submissionDAO.saveSubmission(submission);
}
tx.commit();
new LogDAO(session).createLogEntry(studentParticipation.getUser(), null, task, LogAction.UPLOAD, null, null);
response.sendRedirect(response.encodeRedirectURL("ShowTask?taskid=" + task.getTaskid()));
return;
}
}
if (!submissionDAO.deleteIfNoFiles(submission, path)) {
submission.setLastModified(new Date());
submissionDAO.saveSubmission(submission);
}
System.out.println("SubmitSolutionProblem3");
System.out.println("Problem: Keine Abgabedaten gefunden.");
tx.commit();
out.println("Problem: Keine Abgabedaten gefunden.");
} else if (request.getParameter("textsolution") != null) {
File uploadedFile = new File(path, "textloesung.txt");
FileWriter fileWriter = new FileWriter(uploadedFile);
fileWriter.write(request.getParameter("textsolution"));
fileWriter.flush();
fileWriter.close();
submission.setLastModified(new Date());
submissionDAO.saveSubmission(submission);
tx.commit();
response.sendRedirect(response.encodeRedirectURL("ShowTask?taskid=" + task.getTaskid()));
} else {
if (!submissionDAO.deleteIfNoFiles(submission, path)) {
submission.setLastModified(new Date());
submissionDAO.saveSubmission(submission);
}
System.out.println("SubmitSolutionProblem4");
tx.commit();
out.println("Problem: Keine Abgabedaten gefunden.");
}
}
public static final void copyInputStream(ZipInputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) >= 0) {
out.write(buffer, 0, len);
}
in.closeEntry();
out.close();
}
}
| true | true | public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
Session session = RequestAdapter.getSession(request);
Template template = TemplateFactory.getTemplate(request, response);
PrintWriter out = response.getWriter();
TaskDAOIf taskDAO = DAOFactory.TaskDAOIf(session);
Task task = taskDAO.getTask(Util.parseInteger(request.getParameter("taskid"), 0));
if (task == null) {
template.printTemplateHeader("Aufgabe nicht gefunden");
out.println("<div class=mid><a href=\"" + response.encodeURL("?") + "\">zur �bersicht</a></div>");
template.printTemplateFooter();
return;
}
// check Lecture Participation
ParticipationDAOIf participationDAO = DAOFactory.ParticipationDAOIf(session);
Participation studentParticipation = participationDAO.getParticipation(RequestAdapter.getUser(request), task.getTaskGroup().getLecture());
if (studentParticipation == null) {
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("<div class=mid>Sie sind kein Teilnehmer dieser Veranstaltung.</div>");
out.println("<div class=mid><a href=\"" + response.encodeURL("Overview") + "\">zur �bersicht</a></div>");
template.printTemplateFooter();
return;
}
//http://commons.apache.org/fileupload/using.html
// Check that we have a file upload request
boolean isMultipart = FileUpload.isMultipartContent(request);
List<Integer> partnerIDs = new LinkedList<Integer>();
int uploadFor = 0;
List<FileItem> items = null;
if (!isMultipart) {
for (String partnerIdParameter : request.getParameterValues("partnerid")) {
int partnerID = Util.parseInteger(partnerIdParameter, 0);
if (partnerID > 0) {
partnerIDs.add(partnerID);
}
}
} else {
// Create a new file upload handler
FileUploadBase upload = new DiskFileUpload();
// Parse the request
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
return;
}
// Process the uploaded items
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
if (item.isFormField() && "partnerid".equals(item.getFieldName())) {
int partnerID = Util.parseInteger(item.getString(), 0);
if (partnerID > 0) {
partnerIDs.add(partnerID);
}
} else if (item.isFormField() && "uploadFor".equals(item.getFieldName())) {
uploadFor = Util.parseInteger(item.getString(), 0);
}
}
}
if (uploadFor > 0) {
// Uploader ist wahrscheinlich Betreuer -> keine zeitlichen Pr�fungen
// check if uploader is allowed to upload for students
if (!(studentParticipation.getRoleType() == ParticipationRole.ADVISOR || (task.isTutorsCanUploadFiles() && studentParticipation.getRoleType() == ParticipationRole.TUTOR))) {
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("<div class=mid>Sie sind nicht berechtigt bei dieser Veranstaltung Dateien f�r Studenten hochzuladen.</div>");
out.println("<div class=mid><a href=\"" + response.encodeURL("Overview") + "\">zur �bersicht</a></div>");
template.printTemplateFooter();
return;
}
studentParticipation = participationDAO.getParticipation(uploadFor);
if (studentParticipation == null || studentParticipation.getLecture().getId() != task.getTaskGroup().getLecture().getId()) {
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("<div class=mid>Der gew�hlte Student ist kein Teilnehmer dieser Veranstaltung.</div>");
out.println("<div class=mid><a href=\"" + response.encodeURL("Overview") + "\">zur �bersicht</a></div>");
template.printTemplateFooter();
return;
}
if (task.isShowTextArea() == false && "-".equals(task.getFilenameRegexp())) {
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("<div class=mid>Das Einsenden von L�sungen ist f�r diese Aufgabe deaktiviert.</div>");
template.printTemplateFooter();
return;
}
} else {
if (studentParticipation.getRoleType() == ParticipationRole.ADVISOR || studentParticipation.getRoleType() == ParticipationRole.TUTOR) {
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("<div class=mid>Betreuer und Tutoren k�nnen keine eigenen L�sungen einsenden.</div>");
template.printTemplateFooter();
return;
}
// Uploader is Student, -> hard date checks
if (task.getStart().after(Util.correctTimezone(new Date()))) {
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("<div class=mid>Abgabe nicht gefunden.</div>");
template.printTemplateFooter();
return;
}
if (task.getDeadline().before(Util.correctTimezone(new Date()))) {
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("<div class=mid>Abgabe nicht mehr m�glich.</div>");
template.printTemplateFooter();
return;
}
if (isMultipart && "-".equals(task.getFilenameRegexp())) {
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("<div class=mid>Dateiupload ist f�r diese Aufgabe deaktiviert.</div>");
template.printTemplateFooter();
return;
} else if (!isMultipart && !task.isShowTextArea()) {
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("<div class=mid>Textl�sungen sind f�r diese Aufgabe deaktiviert.</div>");
template.printTemplateFooter();
return;
}
}
SubmissionDAOIf submissionDAO = DAOFactory.SubmissionDAOIf(session);
Transaction tx = session.beginTransaction();
Submission submission = submissionDAO.createSubmission(task, studentParticipation);
for (int partnerID : partnerIDs) {
Participation partnerParticipation = participationDAO.getParticipation(partnerID);
if (submission.getSubmitters().size() < task.getMaxSubmitters() && partnerParticipation != null && partnerParticipation.getLecture().getId() == task.getTaskGroup().getLecture().getId() && submissionDAO.getSubmissionLocked(task, partnerParticipation.getUser()) == null) {
submission.getSubmitters().add(partnerParticipation);
session.update(submission);
} else {
tx.rollback();
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("<div class=mid>Ein ausgew�hlter Partner hat bereits eine eigene Abgabe initiiert oder Sie haben bereits die maximale Anzahl von Partnern ausgew�hlt.</div>");
template.printTemplateFooter();
return;
}
}
ContextAdapter contextAdapter = new ContextAdapter(getServletContext());
File path = new File(contextAdapter.getDataPath().getAbsolutePath() + System.getProperty("file.separator") + task.getTaskGroup().getLecture().getId() + System.getProperty("file.separator") + task.getTaskid() + System.getProperty("file.separator") + submission.getSubmissionid() + System.getProperty("file.separator"));
if (path.exists() == false) {
path.mkdirs();
}
if (isMultipart) {
// Process the uploaded items
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
// Process a file upload
if (!item.isFormField()) {
Pattern pattern;
if (task.getFilenameRegexp() == null || task.getFilenameRegexp().isEmpty() || uploadFor > 0) {
pattern = Pattern.compile("^(?:.*?\\\\|/)?([a-zA-Z0-9_.-]+)$");
} else {
pattern = Pattern.compile("^(?:.*?\\\\|/)?(" + task.getFilenameRegexp() + ")$");
}
StringBuffer submittedFileName = new StringBuffer(item.getName());
if (submittedFileName.lastIndexOf(".") > 0) {
int lastDot = submittedFileName.lastIndexOf(".");
submittedFileName.replace(lastDot, submittedFileName.length(), submittedFileName.subSequence(lastDot, submittedFileName.length()).toString().toLowerCase());
}
Matcher m = pattern.matcher(submittedFileName);
if (!m.matches()) {
if (!submissionDAO.deleteIfNoFiles(submission, path)) {
submission.setLastModified(new Date());
submissionDAO.saveSubmission(submission);
}
System.out.println("SubmitSolutionProblem2: " + item.getName() + ";" + submittedFileName + ";" + pattern.pattern());
tx.commit();
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("Dateiname ung�ltig bzw. entspricht nicht der Vorgabe (ist ein Klassenname vorgegeben, so muss die Datei genauso hei�en).<br>Tipp: Nur A-Z, a-z, 0-9, ., - und _ sind erlaubt. Evtl. muss der Dateiname mit einem Gro�buchstaben beginnen und darf keine Leerzeichen enthalten.");
if (uploadFor > 0) {
out.println("<br>F�r Experten: Der Dateiname muss dem folgenden regul�ren Ausdruck gen�gen: " + Util.escapeHTML(pattern.pattern()));
}
template.printTemplateFooter();
return;
}
String fileName = m.group(1);
if (!"-".equals(task.getArchiveFilenameRegexp()) && (fileName.endsWith(".zip") || fileName.endsWith(".jar"))) {
ZipInputStream zipFile;
Pattern archivePattern;
if (task.getArchiveFilenameRegexp() == null || task.getArchiveFilenameRegexp().isEmpty()) {
archivePattern = Pattern.compile("^([\\/a-zA-Z0-9_ .-]*([a-zA-Z0-9_ .-]+))$");
} else if (task.getArchiveFilenameRegexp().startsWith("^")) {
archivePattern = Pattern.compile("^(" + task.getArchiveFilenameRegexp().substring(1) + ")$");
} else {
archivePattern = Pattern.compile("^([\\/a-zA-Z0-9_ .-]*(" + task.getArchiveFilenameRegexp() + "))$");
}
try {
zipFile = new ZipInputStream(item.getInputStream());
ZipEntry entry = null;
while ((entry = zipFile.getNextEntry()) != null) {
if (entry.getName().contains("..")) {
continue;
}
StringBuffer archivedFileName = new StringBuffer(entry.getName());
if (!archivePattern.matcher(archivedFileName).matches()) {
System.out.println("Ignored entry: " + archivedFileName);
continue;
}
if (entry.isDirectory() == false && !entry.getName().toLowerCase().endsWith(".class")) {
if (archivedFileName.lastIndexOf(".") > 0) {
int lastDot = archivedFileName.lastIndexOf(".");
archivedFileName.replace(lastDot, archivedFileName.length(), archivedFileName.subSequence(lastDot, archivedFileName.length()).toString().toLowerCase());
}
// TODO: relocate java-files from jar/zip archives?
File fileToCreate = new File(path, archivedFileName.toString());
if (!fileToCreate.getParentFile().exists()) {
fileToCreate.getParentFile().mkdirs();
}
copyInputStream(zipFile, new BufferedOutputStream(new FileOutputStream(fileToCreate)));
}
}
zipFile.close();
} catch (IOException e) {
if (!submissionDAO.deleteIfNoFiles(submission, path)) {
submission.setLastModified(new Date());
submissionDAO.saveSubmission(submission);
}
System.out.println("SubmitSolutionProblem1");
tx.commit();
System.out.println(e.getMessage());
e.printStackTrace();
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("Problem beim Entpacken des Archives.");
template.printTemplateFooter();
return;
}
} else {
File uploadedFile = new File(path, fileName);
// handle .java-files differently in order to extract package and move it to the correct folder
if (fileName.toLowerCase().endsWith(".java")) {
uploadedFile = File.createTempFile("upload", null, path);
}
try {
item.write(uploadedFile);
} catch (Exception e) {
e.printStackTrace();
}
// extract defined package in java-files
if (fileName.toLowerCase().endsWith(".java")) {
NormalizerIf stripComments = new StripCommentsNormalizer();
StringBuffer javaFileContents = stripComments.normalize(Util.loadFile(uploadedFile));
Pattern packagePattern = Pattern.compile(".*package\\s+([a-zA-Z$]([a-zA-Z0-9_$]|\\.[a-zA-Z0-9_$])*)\\s*;.*", Pattern.DOTALL);
Matcher packageMatcher = packagePattern.matcher(javaFileContents);
File destFile = new File(path, fileName);
if (packageMatcher.matches()) {
String packageName = packageMatcher.group(1).replace(".", System.getProperty("file.separator"));
File packageDirectory = new File(path, packageName);
packageDirectory.mkdirs();
destFile = new File(packageDirectory, fileName);
}
if (destFile.exists() && destFile.isFile()) {
destFile.delete();
}
uploadedFile.renameTo(destFile);
}
}
if (!submissionDAO.deleteIfNoFiles(submission, path)) {
submission.setLastModified(new Date());
submissionDAO.saveSubmission(submission);
}
tx.commit();
new LogDAO(session).createLogEntry(studentParticipation.getUser(), null, task, LogAction.UPLOAD, null, null);
response.sendRedirect(response.encodeRedirectURL("ShowTask?taskid=" + task.getTaskid()));
return;
}
}
if (!submissionDAO.deleteIfNoFiles(submission, path)) {
submission.setLastModified(new Date());
submissionDAO.saveSubmission(submission);
}
System.out.println("SubmitSolutionProblem3");
System.out.println("Problem: Keine Abgabedaten gefunden.");
tx.commit();
out.println("Problem: Keine Abgabedaten gefunden.");
} else if (request.getParameter("textsolution") != null) {
File uploadedFile = new File(path, "textloesung.txt");
FileWriter fileWriter = new FileWriter(uploadedFile);
fileWriter.write(request.getParameter("textsolution"));
fileWriter.flush();
fileWriter.close();
submission.setLastModified(new Date());
submissionDAO.saveSubmission(submission);
tx.commit();
response.sendRedirect(response.encodeRedirectURL("ShowTask?taskid=" + task.getTaskid()));
} else {
if (!submissionDAO.deleteIfNoFiles(submission, path)) {
submission.setLastModified(new Date());
submissionDAO.saveSubmission(submission);
}
System.out.println("SubmitSolutionProblem4");
tx.commit();
out.println("Problem: Keine Abgabedaten gefunden.");
}
}
| public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
Session session = RequestAdapter.getSession(request);
Template template = TemplateFactory.getTemplate(request, response);
PrintWriter out = response.getWriter();
TaskDAOIf taskDAO = DAOFactory.TaskDAOIf(session);
Task task = taskDAO.getTask(Util.parseInteger(request.getParameter("taskid"), 0));
if (task == null) {
template.printTemplateHeader("Aufgabe nicht gefunden");
out.println("<div class=mid><a href=\"" + response.encodeURL("?") + "\">zur �bersicht</a></div>");
template.printTemplateFooter();
return;
}
// check Lecture Participation
ParticipationDAOIf participationDAO = DAOFactory.ParticipationDAOIf(session);
Participation studentParticipation = participationDAO.getParticipation(RequestAdapter.getUser(request), task.getTaskGroup().getLecture());
if (studentParticipation == null) {
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("<div class=mid>Sie sind kein Teilnehmer dieser Veranstaltung.</div>");
out.println("<div class=mid><a href=\"" + response.encodeURL("Overview") + "\">zur �bersicht</a></div>");
template.printTemplateFooter();
return;
}
//http://commons.apache.org/fileupload/using.html
// Check that we have a file upload request
boolean isMultipart = FileUpload.isMultipartContent(request);
List<Integer> partnerIDs = new LinkedList<Integer>();
int uploadFor = 0;
List<FileItem> items = null;
if (!isMultipart) {
if (request.getParameterValues("partnerid") != null) {
for (String partnerIdParameter : request.getParameterValues("partnerid")) {
int partnerID = Util.parseInteger(partnerIdParameter, 0);
if (partnerID > 0) {
partnerIDs.add(partnerID);
}
}
}
} else {
// Create a new file upload handler
FileUploadBase upload = new DiskFileUpload();
// Parse the request
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
return;
}
// Process the uploaded items
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
if (item.isFormField() && "partnerid".equals(item.getFieldName())) {
int partnerID = Util.parseInteger(item.getString(), 0);
if (partnerID > 0) {
partnerIDs.add(partnerID);
}
} else if (item.isFormField() && "uploadFor".equals(item.getFieldName())) {
uploadFor = Util.parseInteger(item.getString(), 0);
}
}
}
if (uploadFor > 0) {
// Uploader ist wahrscheinlich Betreuer -> keine zeitlichen Pr�fungen
// check if uploader is allowed to upload for students
if (!(studentParticipation.getRoleType() == ParticipationRole.ADVISOR || (task.isTutorsCanUploadFiles() && studentParticipation.getRoleType() == ParticipationRole.TUTOR))) {
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("<div class=mid>Sie sind nicht berechtigt bei dieser Veranstaltung Dateien f�r Studenten hochzuladen.</div>");
out.println("<div class=mid><a href=\"" + response.encodeURL("Overview") + "\">zur �bersicht</a></div>");
template.printTemplateFooter();
return;
}
studentParticipation = participationDAO.getParticipation(uploadFor);
if (studentParticipation == null || studentParticipation.getLecture().getId() != task.getTaskGroup().getLecture().getId()) {
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("<div class=mid>Der gew�hlte Student ist kein Teilnehmer dieser Veranstaltung.</div>");
out.println("<div class=mid><a href=\"" + response.encodeURL("Overview") + "\">zur �bersicht</a></div>");
template.printTemplateFooter();
return;
}
if (task.isShowTextArea() == false && "-".equals(task.getFilenameRegexp())) {
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("<div class=mid>Das Einsenden von L�sungen ist f�r diese Aufgabe deaktiviert.</div>");
template.printTemplateFooter();
return;
}
} else {
if (studentParticipation.getRoleType() == ParticipationRole.ADVISOR || studentParticipation.getRoleType() == ParticipationRole.TUTOR) {
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("<div class=mid>Betreuer und Tutoren k�nnen keine eigenen L�sungen einsenden.</div>");
template.printTemplateFooter();
return;
}
// Uploader is Student, -> hard date checks
if (task.getStart().after(Util.correctTimezone(new Date()))) {
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("<div class=mid>Abgabe nicht gefunden.</div>");
template.printTemplateFooter();
return;
}
if (task.getDeadline().before(Util.correctTimezone(new Date()))) {
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("<div class=mid>Abgabe nicht mehr m�glich.</div>");
template.printTemplateFooter();
return;
}
if (isMultipart && "-".equals(task.getFilenameRegexp())) {
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("<div class=mid>Dateiupload ist f�r diese Aufgabe deaktiviert.</div>");
template.printTemplateFooter();
return;
} else if (!isMultipart && !task.isShowTextArea()) {
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("<div class=mid>Textl�sungen sind f�r diese Aufgabe deaktiviert.</div>");
template.printTemplateFooter();
return;
}
}
SubmissionDAOIf submissionDAO = DAOFactory.SubmissionDAOIf(session);
Transaction tx = session.beginTransaction();
Submission submission = submissionDAO.createSubmission(task, studentParticipation);
for (int partnerID : partnerIDs) {
Participation partnerParticipation = participationDAO.getParticipation(partnerID);
if (submission.getSubmitters().size() < task.getMaxSubmitters() && partnerParticipation != null && partnerParticipation.getLecture().getId() == task.getTaskGroup().getLecture().getId() && submissionDAO.getSubmissionLocked(task, partnerParticipation.getUser()) == null) {
submission.getSubmitters().add(partnerParticipation);
session.update(submission);
} else {
tx.rollback();
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("<div class=mid>Ein ausgew�hlter Partner hat bereits eine eigene Abgabe initiiert oder Sie haben bereits die maximale Anzahl von Partnern ausgew�hlt.</div>");
template.printTemplateFooter();
return;
}
}
ContextAdapter contextAdapter = new ContextAdapter(getServletContext());
File path = new File(contextAdapter.getDataPath().getAbsolutePath() + System.getProperty("file.separator") + task.getTaskGroup().getLecture().getId() + System.getProperty("file.separator") + task.getTaskid() + System.getProperty("file.separator") + submission.getSubmissionid() + System.getProperty("file.separator"));
if (path.exists() == false) {
path.mkdirs();
}
if (isMultipart) {
// Process the uploaded items
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
// Process a file upload
if (!item.isFormField()) {
Pattern pattern;
if (task.getFilenameRegexp() == null || task.getFilenameRegexp().isEmpty() || uploadFor > 0) {
pattern = Pattern.compile("^(?:.*?\\\\|/)?([a-zA-Z0-9_.-]+)$");
} else {
pattern = Pattern.compile("^(?:.*?\\\\|/)?(" + task.getFilenameRegexp() + ")$");
}
StringBuffer submittedFileName = new StringBuffer(item.getName());
if (submittedFileName.lastIndexOf(".") > 0) {
int lastDot = submittedFileName.lastIndexOf(".");
submittedFileName.replace(lastDot, submittedFileName.length(), submittedFileName.subSequence(lastDot, submittedFileName.length()).toString().toLowerCase());
}
Matcher m = pattern.matcher(submittedFileName);
if (!m.matches()) {
if (!submissionDAO.deleteIfNoFiles(submission, path)) {
submission.setLastModified(new Date());
submissionDAO.saveSubmission(submission);
}
System.out.println("SubmitSolutionProblem2: " + item.getName() + ";" + submittedFileName + ";" + pattern.pattern());
tx.commit();
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("Dateiname ung�ltig bzw. entspricht nicht der Vorgabe (ist ein Klassenname vorgegeben, so muss die Datei genauso hei�en).<br>Tipp: Nur A-Z, a-z, 0-9, ., - und _ sind erlaubt. Evtl. muss der Dateiname mit einem Gro�buchstaben beginnen und darf keine Leerzeichen enthalten.");
if (uploadFor > 0) {
out.println("<br>F�r Experten: Der Dateiname muss dem folgenden regul�ren Ausdruck gen�gen: " + Util.escapeHTML(pattern.pattern()));
}
template.printTemplateFooter();
return;
}
String fileName = m.group(1);
if (!"-".equals(task.getArchiveFilenameRegexp()) && (fileName.endsWith(".zip") || fileName.endsWith(".jar"))) {
ZipInputStream zipFile;
Pattern archivePattern;
if (task.getArchiveFilenameRegexp() == null || task.getArchiveFilenameRegexp().isEmpty()) {
archivePattern = Pattern.compile("^([\\/a-zA-Z0-9_ .-]*([a-zA-Z0-9_ .-]+))$");
} else if (task.getArchiveFilenameRegexp().startsWith("^")) {
archivePattern = Pattern.compile("^(" + task.getArchiveFilenameRegexp().substring(1) + ")$");
} else {
archivePattern = Pattern.compile("^([\\/a-zA-Z0-9_ .-]*(" + task.getArchiveFilenameRegexp() + "))$");
}
try {
zipFile = new ZipInputStream(item.getInputStream());
ZipEntry entry = null;
while ((entry = zipFile.getNextEntry()) != null) {
if (entry.getName().contains("..")) {
continue;
}
StringBuffer archivedFileName = new StringBuffer(entry.getName());
if (!archivePattern.matcher(archivedFileName).matches()) {
System.out.println("Ignored entry: " + archivedFileName);
continue;
}
if (entry.isDirectory() == false && !entry.getName().toLowerCase().endsWith(".class")) {
if (archivedFileName.lastIndexOf(".") > 0) {
int lastDot = archivedFileName.lastIndexOf(".");
archivedFileName.replace(lastDot, archivedFileName.length(), archivedFileName.subSequence(lastDot, archivedFileName.length()).toString().toLowerCase());
}
// TODO: relocate java-files from jar/zip archives?
File fileToCreate = new File(path, archivedFileName.toString());
if (!fileToCreate.getParentFile().exists()) {
fileToCreate.getParentFile().mkdirs();
}
copyInputStream(zipFile, new BufferedOutputStream(new FileOutputStream(fileToCreate)));
}
}
zipFile.close();
} catch (IOException e) {
if (!submissionDAO.deleteIfNoFiles(submission, path)) {
submission.setLastModified(new Date());
submissionDAO.saveSubmission(submission);
}
System.out.println("SubmitSolutionProblem1");
tx.commit();
System.out.println(e.getMessage());
e.printStackTrace();
template.printTemplateHeader("Ung�ltige Anfrage");
out.println("Problem beim Entpacken des Archives.");
template.printTemplateFooter();
return;
}
} else {
File uploadedFile = new File(path, fileName);
// handle .java-files differently in order to extract package and move it to the correct folder
if (fileName.toLowerCase().endsWith(".java")) {
uploadedFile = File.createTempFile("upload", null, path);
}
try {
item.write(uploadedFile);
} catch (Exception e) {
e.printStackTrace();
}
// extract defined package in java-files
if (fileName.toLowerCase().endsWith(".java")) {
NormalizerIf stripComments = new StripCommentsNormalizer();
StringBuffer javaFileContents = stripComments.normalize(Util.loadFile(uploadedFile));
Pattern packagePattern = Pattern.compile(".*package\\s+([a-zA-Z$]([a-zA-Z0-9_$]|\\.[a-zA-Z0-9_$])*)\\s*;.*", Pattern.DOTALL);
Matcher packageMatcher = packagePattern.matcher(javaFileContents);
File destFile = new File(path, fileName);
if (packageMatcher.matches()) {
String packageName = packageMatcher.group(1).replace(".", System.getProperty("file.separator"));
File packageDirectory = new File(path, packageName);
packageDirectory.mkdirs();
destFile = new File(packageDirectory, fileName);
}
if (destFile.exists() && destFile.isFile()) {
destFile.delete();
}
uploadedFile.renameTo(destFile);
}
}
if (!submissionDAO.deleteIfNoFiles(submission, path)) {
submission.setLastModified(new Date());
submissionDAO.saveSubmission(submission);
}
tx.commit();
new LogDAO(session).createLogEntry(studentParticipation.getUser(), null, task, LogAction.UPLOAD, null, null);
response.sendRedirect(response.encodeRedirectURL("ShowTask?taskid=" + task.getTaskid()));
return;
}
}
if (!submissionDAO.deleteIfNoFiles(submission, path)) {
submission.setLastModified(new Date());
submissionDAO.saveSubmission(submission);
}
System.out.println("SubmitSolutionProblem3");
System.out.println("Problem: Keine Abgabedaten gefunden.");
tx.commit();
out.println("Problem: Keine Abgabedaten gefunden.");
} else if (request.getParameter("textsolution") != null) {
File uploadedFile = new File(path, "textloesung.txt");
FileWriter fileWriter = new FileWriter(uploadedFile);
fileWriter.write(request.getParameter("textsolution"));
fileWriter.flush();
fileWriter.close();
submission.setLastModified(new Date());
submissionDAO.saveSubmission(submission);
tx.commit();
response.sendRedirect(response.encodeRedirectURL("ShowTask?taskid=" + task.getTaskid()));
} else {
if (!submissionDAO.deleteIfNoFiles(submission, path)) {
submission.setLastModified(new Date());
submissionDAO.saveSubmission(submission);
}
System.out.println("SubmitSolutionProblem4");
tx.commit();
out.println("Problem: Keine Abgabedaten gefunden.");
}
}
|
diff --git a/components/bio-formats/src/loci/formats/out/JPEGWriter.java b/components/bio-formats/src/loci/formats/out/JPEGWriter.java
index 169696f84..0fe6ce650 100644
--- a/components/bio-formats/src/loci/formats/out/JPEGWriter.java
+++ b/components/bio-formats/src/loci/formats/out/JPEGWriter.java
@@ -1,71 +1,72 @@
//
// JPEGWriter.java
//
/*
OME Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc.
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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats.out;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import loci.common.*;
import loci.formats.*;
/**
* JPEGWriter is the file format writer for JPEG files.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/out/JPEGWriter.java">Trac</a>,
* <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/out/JPEGWriter.java">SVN</a></dd></dl>
*/
public class JPEGWriter extends ImageIOWriter {
// -- Constructor --
public JPEGWriter() {
super("Joint Photographic Experts Group",
new String[] {"jpg", "jpeg", "jpe"}, "jpeg");
}
// -- IFormatWriter API methods --
/* @see loci.formats.IFormatWriter#save(Image, int, boolean, boolean) */
public void saveImage(Image image, int series, boolean lastInSeries,
boolean last) throws FormatException, IOException
{
BufferedImage img = AWTImageTools.makeBuffered(image, cm);
int type = AWTImageTools.getPixelType(img);
int[] types = getPixelTypes();
for (int i=0; i<types.length; i++) {
if (types[i] == type) {
super.saveImage(image, series, lastInSeries, last);
return;
}
}
- throw new FormatException("Unsupported data type");
+ throw new FormatException("Unsupported data type - > 8 bit images " +
+ "cannot be saved.");
}
/* @see loci.formats.IFormatWriter#getPixelTypes(String) */
public int[] getPixelTypes() {
return new int[] {FormatTools.UINT8};
}
}
| true | true | public JPEGWriter() {
super("Joint Photographic Experts Group",
new String[] {"jpg", "jpeg", "jpe"}, "jpeg");
}
// -- IFormatWriter API methods --
/* @see loci.formats.IFormatWriter#save(Image, int, boolean, boolean) */
public void saveImage(Image image, int series, boolean lastInSeries,
boolean last) throws FormatException, IOException
{
BufferedImage img = AWTImageTools.makeBuffered(image, cm);
int type = AWTImageTools.getPixelType(img);
int[] types = getPixelTypes();
for (int i=0; i<types.length; i++) {
if (types[i] == type) {
super.saveImage(image, series, lastInSeries, last);
return;
}
}
throw new FormatException("Unsupported data type");
}
/* @see loci.formats.IFormatWriter#getPixelTypes(String) */
public int[] getPixelTypes() {
return new int[] {FormatTools.UINT8};
}
}
| public JPEGWriter() {
super("Joint Photographic Experts Group",
new String[] {"jpg", "jpeg", "jpe"}, "jpeg");
}
// -- IFormatWriter API methods --
/* @see loci.formats.IFormatWriter#save(Image, int, boolean, boolean) */
public void saveImage(Image image, int series, boolean lastInSeries,
boolean last) throws FormatException, IOException
{
BufferedImage img = AWTImageTools.makeBuffered(image, cm);
int type = AWTImageTools.getPixelType(img);
int[] types = getPixelTypes();
for (int i=0; i<types.length; i++) {
if (types[i] == type) {
super.saveImage(image, series, lastInSeries, last);
return;
}
}
throw new FormatException("Unsupported data type - > 8 bit images " +
"cannot be saved.");
}
/* @see loci.formats.IFormatWriter#getPixelTypes(String) */
public int[] getPixelTypes() {
return new int[] {FormatTools.UINT8};
}
}
|
diff --git a/fog/src/de/tuilmenau/ics/fog/transfer/forwardingNodes/Multiplexer.java b/fog/src/de/tuilmenau/ics/fog/transfer/forwardingNodes/Multiplexer.java
index cafbec63..0c06801f 100644
--- a/fog/src/de/tuilmenau/ics/fog/transfer/forwardingNodes/Multiplexer.java
+++ b/fog/src/de/tuilmenau/ics/fog/transfer/forwardingNodes/Multiplexer.java
@@ -1,332 +1,332 @@
/*******************************************************************************
* Forwarding on Gates Simulator/Emulator
* Copyright (C) 2012, Integrated Communication Systems Group, TU Ilmenau.
*
* This program and the accompanying materials are dual-licensed under either
* the terms of the Eclipse Public License v1.0 as published by the Eclipse
* Foundation
*
* or (per the licensee's choosing)
*
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
******************************************************************************/
package de.tuilmenau.ics.fog.transfer.forwardingNodes;
import de.tuilmenau.ics.fog.Config;
import de.tuilmenau.ics.fog.FoGEntity;
import de.tuilmenau.ics.fog.authentication.IdentityManagement;
import de.tuilmenau.ics.fog.facade.Description;
import de.tuilmenau.ics.fog.facade.Identity;
import de.tuilmenau.ics.fog.facade.Name;
import de.tuilmenau.ics.fog.packets.Invisible;
import de.tuilmenau.ics.fog.packets.Packet;
import de.tuilmenau.ics.fog.packets.Signalling;
import de.tuilmenau.ics.fog.transfer.ForwardingElement;
import de.tuilmenau.ics.fog.transfer.TransferPlaneObserver.NamingLevel;
import de.tuilmenau.ics.fog.transfer.gates.AbstractGate;
import de.tuilmenau.ics.fog.transfer.gates.GateID;
import de.tuilmenau.ics.fog.transfer.gates.TransparentGate;
import de.tuilmenau.ics.fog.transfer.manager.Controller;
import de.tuilmenau.ics.fog.ui.Logging;
import de.tuilmenau.ics.fog.ui.PacketLogger;
import de.tuilmenau.ics.fog.ui.Viewable;
/**
* Forwards a message to the next gate based on the gate
* list of the packet.
* It implements the "forwarding node" functionality by
* multiplexing between several registered gates.
*/
public class Multiplexer extends GateContainer
{
/**
* Forwarding node in a FoG network.
*
* @param node Node the FN is located on.
* @param errorHandling Controller doing error handling for this FN (if null, the controller of the node is used)
*/
public Multiplexer(FoGEntity node, Controller errorHandling)
{
super(node, null, NamingLevel.NONE);
mErrorGate = errorHandling;
if(mErrorGate == null) {
mErrorGate = node.getController();
}
// TODO where to close it?
mPacketLog = PacketLogger.createLogger(mEntity.getTimeBase(), this, node);
}
/**
* Forwarding node in a FoG network.
*
* @param node Node the FN is located on.
* @param name Name of the FN (just for GUI and debugging reasons)
* @param level Level of abstraction of name
* @param owner Identity of the FN (optional; null if not available)
* @param errorHandling Controller doing error handling for this FN (if null, the controller of the node is used)
*/
public Multiplexer(FoGEntity entity, Name name, NamingLevel level, boolean privateForTransfer, Identity owner, Controller errorHandling)
{
super(entity, name, level);
mIsPrivate = privateForTransfer;
mErrorGate = errorHandling;
if(mErrorGate == null) {
mErrorGate = entity.getController();
}
mOwner = owner;
// TODO where to close it?
mPacketLog = PacketLogger.createLogger(mEntity.getTimeBase(), this, entity);
}
/**
* Creates bi-directional connection between two multiplexer with
* help of TransparentGates
*
* @param pMux other multiplexer to connect to
* @return true if connection had been established; false on error
*/
public boolean connectMultiplexer(Multiplexer pMux)
{
TransparentGate toMux = new TransparentGate(getEntity(), pMux);
TransparentGate fromMux = new TransparentGate(getEntity(), this);
GateID toMuxGateNr = registerGate(toMux);
GateID fromMuxGateNr = pMux.registerGate(fromMux);
toMux.initialise();
fromMux.initialise();
if((toMuxGateNr == null) || (fromMuxGateNr == null)) {
mLogger.err(this, "connecting to " +pMux +" failed because of missing gate numbers.");
unregisterGate(toMux);
pMux.unregisterGate(fromMux);
return false;
} else {
toMux.setReverseGateID(fromMuxGateNr);
fromMux.setReverseGateID(toMuxGateNr);
return true;
}
}
final public void handlePacket(Packet packet, ForwardingElement lastHop)
{
if(Config.Connection.LOG_PACKET_STATIONS){
Logging.log(this, "Forwarding: " + packet);
}
if(packet.isTraceRouting()){
Logging.log(this, "TRACEROUTE-Processing packet: " + packet);
}
// log packet for statistic
mPacketLog.add(packet);
packet.forwarded(this);
// trace backward route
if((lastHop != null) && packet.traceBackwardRoute()) {
GateID tReturn = null;
if(lastHop instanceof AbstractGate) {
tReturn = ((AbstractGate) lastHop).getReverseGateID();
}
if(tReturn == null) {
tReturn = searchForGate(lastHop);
}
if(tReturn != null) {
// e.g. for UpGates attached to a multiplexer
packet.addReturnRoute(tReturn);
} else {
/*
* this is required in case a packet was emitted by a node
*/
if(!packet.getReturnRoute().isEmpty()) {
mLogger.warn(this, "Return route for " +packet +" broken at " +lastHop);
packet.returnRouteBroken();
}
}
}
// add signature
// if packet already authenticated and multiplexer has the possibility to add a signature
if(packet.pleaseAuthenticate() && (mOwner != null)) {
IdentityManagement authService = mEntity.getAuthenticationService();
// check, if the existing signatures are acceptable
if(authService.check(packet)) {
// create and add own signature
authService.sign(packet, mOwner);
} else {
mLogger.warn(this, "Signature not matching packet: " +packet);
}
}
// handle invisible packets
boolean tInvisible = packet.isInvisible();
if(tInvisible) {
((Invisible) packet.getData()).execute(this, packet);
}
// find next gate and delegate forwarding process to it
GateID tID = packet.fetchNextGateID();
if(tID == null) {
if(packet.isTraceRouting()){
Logging.log(this, "TRACEROUTE-Forwarding to this FN, route=" + packet.getRoute() + ", the packet: " + packet);
}
mLogger.log(this, "Route of packet is : " + packet.getRoute());
if(packet.getRoute().isEmpty()) {
// end of gate list reached
// => packet is for this node
mLogger.log(this, "Packet is directed to this FN");
handlePacket(packet);
} else {
// route not empty but no gate ID
// => check for incomplete route
// even do so for invisible packets,
// in order to deliver them to the
// final goal
mErrorGate.incompleteRoute(packet, this);
}
} else {
// determine next gate
// => search gate and forward packet
AbstractGate tNext = getGate(tID);
if(packet.isTraceRouting()){
- Logging.log(this, "TRACEROUTE-Forwarding to next gate: " + tNext + ",readyToReceive=" + tNext.isReadyToReceive() + ", the packet: " + packet);
+ Logging.log(this, "TRACEROUTE-Forwarding to next gate: " + tNext + (tNext != null ? ",readyToReceive=" + tNext.isReadyToReceive() : "") + ", the packet: " + packet);
}
// was ID valid?
if(tNext != null) {
// Call the handle method from the FN; so we do not have to
// do that in each gate implementation. Furthermore, we do
// not care about the state of the gate in order to mark the
// last (error) gate on the path.
if(tInvisible) {
((Invisible) packet.getData()).execute(tNext, packet);
}
// is gate in correct state?
if(tNext.isReadyToReceive()) {
if (getEntity().getCentralFN() == this) {
packet.addToDownRoute(tNext.getGateID());
}
packet.forwarded(tNext);
if(packet.isTraceRouting()){
Logging.log(this, "TRACEROUTE-Forwarding to next FN the packet: " + packet);
}
tNext.handlePacket(packet, this);
} else {
if(packet.isTraceRouting()){
Logging.log(this, "TRACEROUTE-Invalid state for next gate: " + tNext + ", readyToReceive=" + tNext.isReadyToReceive() + ", the packet: " + packet);
}
if(!tInvisible) {
mErrorGate.invalidGateState(tNext, packet, this);
}
// else: suppress error handling
}
} else {
if(!tInvisible) {
mErrorGate.invalidGate(tID, packet, this);
}
// else: suppress error handling
}
}
}
/**
* Method for handling packets, which are for the forwarding node itself.
*/
protected void handlePacket(Packet packet)
{
if(packet.isTraceRouting()){
Logging.log(this, "TRACEROUTE-Forwarding upwards the packet: " + packet);
}
packet.logStats(getEntity().getNode().getAS().getSimulation());
if(packet.getData() instanceof Signalling) {
Signalling tSig = (Signalling) packet.getData();
mLogger.debug(this, "Executing signalling packet " +packet);
boolean tRes = tSig.execute(this, packet);
mLogger.trace(this, "Signalling packet " +packet +" execution result = " +tRes);
}
else if(packet.getData() instanceof Invisible) {
// ignore it; had been handled before
mLogger.trace(this, "Received invisible " + packet +" and ignoring it.");
}
else {
handleDataPacket(packet);
}
}
/**
* Called if a FN received data packets, which have to be forwarded to higher layer entities.
* The implementation of this class just outputs an error.
*/
protected void handleDataPacket(Packet packet)
{
mLogger.warn(this, "Skip packet " +packet +" because socket towards app. " + getName().toString() + " is not valid (no signaling packet)");
}
/**
* @return Description of the server requirements for all communications
*/
public Description getDescription()
{
return getEntity().getNode().getCapabilities();
}
@Override
public String toString()
{
if (mName != null){
return getClass().getSimpleName() + "(" + mName + ")@" + mEntity;
}else{
return getClass().getSimpleName() + "@" + mEntity;
}
}
@Override
public boolean isPrivateToTransfer()
{
return mIsPrivate;
}
@Override
public Identity getOwner()
{
if(mOwner != null) {
return mOwner;
} else {
return mEntity.getIdentity();
}
}
private Controller mErrorGate = null;
private PacketLogger mPacketLog = null;
private boolean mIsPrivate = true;
@Viewable("Owner")
private Identity mOwner = null;
}
| true | true | final public void handlePacket(Packet packet, ForwardingElement lastHop)
{
if(Config.Connection.LOG_PACKET_STATIONS){
Logging.log(this, "Forwarding: " + packet);
}
if(packet.isTraceRouting()){
Logging.log(this, "TRACEROUTE-Processing packet: " + packet);
}
// log packet for statistic
mPacketLog.add(packet);
packet.forwarded(this);
// trace backward route
if((lastHop != null) && packet.traceBackwardRoute()) {
GateID tReturn = null;
if(lastHop instanceof AbstractGate) {
tReturn = ((AbstractGate) lastHop).getReverseGateID();
}
if(tReturn == null) {
tReturn = searchForGate(lastHop);
}
if(tReturn != null) {
// e.g. for UpGates attached to a multiplexer
packet.addReturnRoute(tReturn);
} else {
/*
* this is required in case a packet was emitted by a node
*/
if(!packet.getReturnRoute().isEmpty()) {
mLogger.warn(this, "Return route for " +packet +" broken at " +lastHop);
packet.returnRouteBroken();
}
}
}
// add signature
// if packet already authenticated and multiplexer has the possibility to add a signature
if(packet.pleaseAuthenticate() && (mOwner != null)) {
IdentityManagement authService = mEntity.getAuthenticationService();
// check, if the existing signatures are acceptable
if(authService.check(packet)) {
// create and add own signature
authService.sign(packet, mOwner);
} else {
mLogger.warn(this, "Signature not matching packet: " +packet);
}
}
// handle invisible packets
boolean tInvisible = packet.isInvisible();
if(tInvisible) {
((Invisible) packet.getData()).execute(this, packet);
}
// find next gate and delegate forwarding process to it
GateID tID = packet.fetchNextGateID();
if(tID == null) {
if(packet.isTraceRouting()){
Logging.log(this, "TRACEROUTE-Forwarding to this FN, route=" + packet.getRoute() + ", the packet: " + packet);
}
mLogger.log(this, "Route of packet is : " + packet.getRoute());
if(packet.getRoute().isEmpty()) {
// end of gate list reached
// => packet is for this node
mLogger.log(this, "Packet is directed to this FN");
handlePacket(packet);
} else {
// route not empty but no gate ID
// => check for incomplete route
// even do so for invisible packets,
// in order to deliver them to the
// final goal
mErrorGate.incompleteRoute(packet, this);
}
} else {
// determine next gate
// => search gate and forward packet
AbstractGate tNext = getGate(tID);
if(packet.isTraceRouting()){
Logging.log(this, "TRACEROUTE-Forwarding to next gate: " + tNext + ",readyToReceive=" + tNext.isReadyToReceive() + ", the packet: " + packet);
}
// was ID valid?
if(tNext != null) {
// Call the handle method from the FN; so we do not have to
// do that in each gate implementation. Furthermore, we do
// not care about the state of the gate in order to mark the
// last (error) gate on the path.
if(tInvisible) {
((Invisible) packet.getData()).execute(tNext, packet);
}
// is gate in correct state?
if(tNext.isReadyToReceive()) {
if (getEntity().getCentralFN() == this) {
packet.addToDownRoute(tNext.getGateID());
}
packet.forwarded(tNext);
if(packet.isTraceRouting()){
Logging.log(this, "TRACEROUTE-Forwarding to next FN the packet: " + packet);
}
tNext.handlePacket(packet, this);
} else {
if(packet.isTraceRouting()){
Logging.log(this, "TRACEROUTE-Invalid state for next gate: " + tNext + ", readyToReceive=" + tNext.isReadyToReceive() + ", the packet: " + packet);
}
if(!tInvisible) {
mErrorGate.invalidGateState(tNext, packet, this);
}
// else: suppress error handling
}
} else {
if(!tInvisible) {
mErrorGate.invalidGate(tID, packet, this);
}
// else: suppress error handling
}
}
}
| final public void handlePacket(Packet packet, ForwardingElement lastHop)
{
if(Config.Connection.LOG_PACKET_STATIONS){
Logging.log(this, "Forwarding: " + packet);
}
if(packet.isTraceRouting()){
Logging.log(this, "TRACEROUTE-Processing packet: " + packet);
}
// log packet for statistic
mPacketLog.add(packet);
packet.forwarded(this);
// trace backward route
if((lastHop != null) && packet.traceBackwardRoute()) {
GateID tReturn = null;
if(lastHop instanceof AbstractGate) {
tReturn = ((AbstractGate) lastHop).getReverseGateID();
}
if(tReturn == null) {
tReturn = searchForGate(lastHop);
}
if(tReturn != null) {
// e.g. for UpGates attached to a multiplexer
packet.addReturnRoute(tReturn);
} else {
/*
* this is required in case a packet was emitted by a node
*/
if(!packet.getReturnRoute().isEmpty()) {
mLogger.warn(this, "Return route for " +packet +" broken at " +lastHop);
packet.returnRouteBroken();
}
}
}
// add signature
// if packet already authenticated and multiplexer has the possibility to add a signature
if(packet.pleaseAuthenticate() && (mOwner != null)) {
IdentityManagement authService = mEntity.getAuthenticationService();
// check, if the existing signatures are acceptable
if(authService.check(packet)) {
// create and add own signature
authService.sign(packet, mOwner);
} else {
mLogger.warn(this, "Signature not matching packet: " +packet);
}
}
// handle invisible packets
boolean tInvisible = packet.isInvisible();
if(tInvisible) {
((Invisible) packet.getData()).execute(this, packet);
}
// find next gate and delegate forwarding process to it
GateID tID = packet.fetchNextGateID();
if(tID == null) {
if(packet.isTraceRouting()){
Logging.log(this, "TRACEROUTE-Forwarding to this FN, route=" + packet.getRoute() + ", the packet: " + packet);
}
mLogger.log(this, "Route of packet is : " + packet.getRoute());
if(packet.getRoute().isEmpty()) {
// end of gate list reached
// => packet is for this node
mLogger.log(this, "Packet is directed to this FN");
handlePacket(packet);
} else {
// route not empty but no gate ID
// => check for incomplete route
// even do so for invisible packets,
// in order to deliver them to the
// final goal
mErrorGate.incompleteRoute(packet, this);
}
} else {
// determine next gate
// => search gate and forward packet
AbstractGate tNext = getGate(tID);
if(packet.isTraceRouting()){
Logging.log(this, "TRACEROUTE-Forwarding to next gate: " + tNext + (tNext != null ? ",readyToReceive=" + tNext.isReadyToReceive() : "") + ", the packet: " + packet);
}
// was ID valid?
if(tNext != null) {
// Call the handle method from the FN; so we do not have to
// do that in each gate implementation. Furthermore, we do
// not care about the state of the gate in order to mark the
// last (error) gate on the path.
if(tInvisible) {
((Invisible) packet.getData()).execute(tNext, packet);
}
// is gate in correct state?
if(tNext.isReadyToReceive()) {
if (getEntity().getCentralFN() == this) {
packet.addToDownRoute(tNext.getGateID());
}
packet.forwarded(tNext);
if(packet.isTraceRouting()){
Logging.log(this, "TRACEROUTE-Forwarding to next FN the packet: " + packet);
}
tNext.handlePacket(packet, this);
} else {
if(packet.isTraceRouting()){
Logging.log(this, "TRACEROUTE-Invalid state for next gate: " + tNext + ", readyToReceive=" + tNext.isReadyToReceive() + ", the packet: " + packet);
}
if(!tInvisible) {
mErrorGate.invalidGateState(tNext, packet, this);
}
// else: suppress error handling
}
} else {
if(!tInvisible) {
mErrorGate.invalidGate(tID, packet, this);
}
// else: suppress error handling
}
}
}
|
diff --git a/core/src/main/java/com/nuodb/migrator/jdbc/metadata/inspector/NuoDBTableInspector.java b/core/src/main/java/com/nuodb/migrator/jdbc/metadata/inspector/NuoDBTableInspector.java
index e75138c9..92add770 100644
--- a/core/src/main/java/com/nuodb/migrator/jdbc/metadata/inspector/NuoDBTableInspector.java
+++ b/core/src/main/java/com/nuodb/migrator/jdbc/metadata/inspector/NuoDBTableInspector.java
@@ -1,154 +1,155 @@
/**
* Copyright (c) 2012, NuoDB, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * 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 NuoDB, Inc. 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 NUODB, INC. BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.nuodb.migrator.jdbc.metadata.inspector;
import com.nuodb.migrator.jdbc.metadata.Schema;
import com.nuodb.migrator.jdbc.metadata.Table;
import com.nuodb.migrator.jdbc.query.StatementCallback;
import com.nuodb.migrator.jdbc.query.StatementFactory;
import com.nuodb.migrator.jdbc.query.StatementTemplate;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Iterator;
import static com.google.common.collect.Lists.newArrayList;
import static com.nuodb.migrator.jdbc.metadata.MetaDataType.SCHEMA;
import static com.nuodb.migrator.jdbc.metadata.MetaDataType.TABLE;
import static com.nuodb.migrator.jdbc.metadata.inspector.InspectionResultsUtils.addTable;
import static com.nuodb.migrator.jdbc.metadata.inspector.NuoDBInspectorUtils.validateInspectionScope;
import static com.nuodb.migrator.jdbc.query.QueryUtils.where;
import static java.sql.ResultSet.CONCUR_READ_ONLY;
import static java.sql.ResultSet.TYPE_FORWARD_ONLY;
import static org.apache.commons.lang3.StringUtils.containsAny;
/**
* @author Sergey Bushik
*/
public class NuoDBTableInspector extends InspectorBase<Schema, TableInspectionScope> {
private static final String QUERY = "SELECT * FROM SYSTEM.TABLES";
public NuoDBTableInspector() {
super(TABLE, SCHEMA, TableInspectionScope.class);
}
@Override
public void inspectScope(final InspectionContext inspectionContext, final TableInspectionScope inspectionScope) throws SQLException {
validateInspectionScope(inspectionScope);
final Collection<String> filters = newArrayList();
final Collection<String> parameters = newArrayList();
String schemaName = inspectionScope.getSchema();
if (schemaName != null) {
filters.add(containsAny(schemaName, "%_") ? "SCHEMA LIKE ?" : "SCHEMA=?");
parameters.add(schemaName);
}
String tableName = inspectionScope.getTable();
if (tableName != null) {
filters.add(containsAny(tableName, "%_") ? "TABLENAME LIKE ?" : "TABLENAME=?");
parameters.add(tableName);
}
String[] tableTypes = inspectionScope.getTableTypes();
if (tableTypes != null && tableTypes.length > 0) {
StringBuilder filter = new StringBuilder("TYPE IN");
filter.append(' ');
+ filter.append('(');
for (int i = 0, length = tableTypes.length; i < length; i++) {
String tableType = tableTypes[i];
filter.append('?');
if ((i + 1) != length) {
filter.append(", ");
}
parameters.add(tableType);
}
filter.append(')');
filters.add(filter.toString());
}
final String query = where(QUERY, filters, "AND");
final StatementTemplate template = new StatementTemplate(inspectionContext.getConnection());
template.execute(
new StatementFactory<PreparedStatement>() {
@Override
public PreparedStatement create(Connection connection) throws SQLException {
return connection.prepareStatement(query,
TYPE_FORWARD_ONLY, CONCUR_READ_ONLY);
}
},
new StatementCallback<PreparedStatement>() {
@Override
public void execute(PreparedStatement statement) throws SQLException {
int parameter = 1;
for (Iterator<String> iterator = parameters.iterator(); iterator.hasNext(); ) {
statement.setString(parameter++, iterator.next());
}
inspect(inspectionContext, statement.executeQuery());
}
}
);
}
@Override
public void inspectObjects(final InspectionContext inspectionContext,
final Collection<? extends Schema> schemas) throws SQLException {
final String query = where(QUERY, newArrayList("SCHEMA=?"), "AND");
final StatementTemplate template = new StatementTemplate(inspectionContext.getConnection());
template.execute(
new StatementFactory<PreparedStatement>() {
@Override
public PreparedStatement create(Connection connection) throws SQLException {
return connection.prepareStatement(query,
TYPE_FORWARD_ONLY, CONCUR_READ_ONLY);
}
},
new StatementCallback<PreparedStatement>() {
@Override
public void execute(PreparedStatement statement) throws SQLException {
for (Schema schema : schemas) {
statement.setString(1, schema.getName());
inspect(inspectionContext, statement.executeQuery());
}
}
}
);
}
private void inspect(InspectionContext inspectionContext, ResultSet tables) throws SQLException {
InspectionResults inspectionResults = inspectionContext.getInspectionResults();
while (tables.next()) {
Table table = addTable(inspectionResults, null, tables.getString("SCHEMA"), tables.getString("TABLENAME"));
table.setType(tables.getString("TYPE"));
table.setComment(tables.getString("REMARKS"));
}
}
}
| true | true | public void inspectScope(final InspectionContext inspectionContext, final TableInspectionScope inspectionScope) throws SQLException {
validateInspectionScope(inspectionScope);
final Collection<String> filters = newArrayList();
final Collection<String> parameters = newArrayList();
String schemaName = inspectionScope.getSchema();
if (schemaName != null) {
filters.add(containsAny(schemaName, "%_") ? "SCHEMA LIKE ?" : "SCHEMA=?");
parameters.add(schemaName);
}
String tableName = inspectionScope.getTable();
if (tableName != null) {
filters.add(containsAny(tableName, "%_") ? "TABLENAME LIKE ?" : "TABLENAME=?");
parameters.add(tableName);
}
String[] tableTypes = inspectionScope.getTableTypes();
if (tableTypes != null && tableTypes.length > 0) {
StringBuilder filter = new StringBuilder("TYPE IN");
filter.append(' ');
for (int i = 0, length = tableTypes.length; i < length; i++) {
String tableType = tableTypes[i];
filter.append('?');
if ((i + 1) != length) {
filter.append(", ");
}
parameters.add(tableType);
}
filter.append(')');
filters.add(filter.toString());
}
final String query = where(QUERY, filters, "AND");
final StatementTemplate template = new StatementTemplate(inspectionContext.getConnection());
template.execute(
new StatementFactory<PreparedStatement>() {
@Override
public PreparedStatement create(Connection connection) throws SQLException {
return connection.prepareStatement(query,
TYPE_FORWARD_ONLY, CONCUR_READ_ONLY);
}
},
new StatementCallback<PreparedStatement>() {
@Override
public void execute(PreparedStatement statement) throws SQLException {
int parameter = 1;
for (Iterator<String> iterator = parameters.iterator(); iterator.hasNext(); ) {
statement.setString(parameter++, iterator.next());
}
inspect(inspectionContext, statement.executeQuery());
}
}
);
}
| public void inspectScope(final InspectionContext inspectionContext, final TableInspectionScope inspectionScope) throws SQLException {
validateInspectionScope(inspectionScope);
final Collection<String> filters = newArrayList();
final Collection<String> parameters = newArrayList();
String schemaName = inspectionScope.getSchema();
if (schemaName != null) {
filters.add(containsAny(schemaName, "%_") ? "SCHEMA LIKE ?" : "SCHEMA=?");
parameters.add(schemaName);
}
String tableName = inspectionScope.getTable();
if (tableName != null) {
filters.add(containsAny(tableName, "%_") ? "TABLENAME LIKE ?" : "TABLENAME=?");
parameters.add(tableName);
}
String[] tableTypes = inspectionScope.getTableTypes();
if (tableTypes != null && tableTypes.length > 0) {
StringBuilder filter = new StringBuilder("TYPE IN");
filter.append(' ');
filter.append('(');
for (int i = 0, length = tableTypes.length; i < length; i++) {
String tableType = tableTypes[i];
filter.append('?');
if ((i + 1) != length) {
filter.append(", ");
}
parameters.add(tableType);
}
filter.append(')');
filters.add(filter.toString());
}
final String query = where(QUERY, filters, "AND");
final StatementTemplate template = new StatementTemplate(inspectionContext.getConnection());
template.execute(
new StatementFactory<PreparedStatement>() {
@Override
public PreparedStatement create(Connection connection) throws SQLException {
return connection.prepareStatement(query,
TYPE_FORWARD_ONLY, CONCUR_READ_ONLY);
}
},
new StatementCallback<PreparedStatement>() {
@Override
public void execute(PreparedStatement statement) throws SQLException {
int parameter = 1;
for (Iterator<String> iterator = parameters.iterator(); iterator.hasNext(); ) {
statement.setString(parameter++, iterator.next());
}
inspect(inspectionContext, statement.executeQuery());
}
}
);
}
|
diff --git a/Zed-Eclipse/src/zed/Zed.java b/Zed-Eclipse/src/zed/Zed.java
index f680575..542b9ad 100644
--- a/Zed-Eclipse/src/zed/Zed.java
+++ b/Zed-Eclipse/src/zed/Zed.java
@@ -1,130 +1,130 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package zed;
// Java for exception handling
import java.util.logging.Level;
import java.util.logging.Logger;
// Slick for creating game
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Music;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
// Slick for exception handling
import org.newdawn.slick.SlickException;
/**
* @author Richard Barella Jr.
* @author Adam Bennett
* @author Ryan Slyter
*/
public class Zed {
// Main function
public static void main(String[] args) throws SlickException {
// create game
org.newdawn.slick.BasicGame game = new org.newdawn.slick.BasicGame("zed") {
// Test-level
Level_Manager test;
// Sounds
Music music = new Music("soundtrack/kawfy/braintwoquart.wav");
// Game Initialization
@Override
public void init(GameContainer gc) throws SlickException {
/*
// Initialize test-images
link_down_bot = new Image("images/link-down-bot.png",
false, Image.FILTER_NEAREST);
link_down_top = new Image("images/link-down-top.png",
false, Image.FILTER_NEAREST);
*/
// Initialize test-level
test = new Level_Manager();
music.loop();
}
// Game Updates
@Override
public void update(GameContainer gc, int delta) throws SlickException {
boolean left = false; //these arent currently being used be needed
boolean right = false;
boolean up = false;
boolean down = false;
gc.setVSync(true); // makes it so computer doesn't heat up
//gc.setTargetFrameRate(120);
- Input input = gc.getInput(); // get the current input
+ Input input = gc.getInput(); // get the current input
if (input.isKeyDown(Input.KEY_UP) || input.isKeyDown(Input.KEY_W))
{
up = true;
//y_pos-=.05;
}
if (input.isKeyDown(Input.KEY_LEFT) || input.isKeyDown(Input.KEY_A))
{
left = true;
//x_pos-=.05;
}
if (input.isKeyDown(Input.KEY_DOWN) || input.isKeyDown(Input.KEY_S))
{
down = true;
//y_pos+=.05;
}
if (input.isKeyDown(Input.KEY_RIGHT) || input.isKeyDown(Input.KEY_D))
{
right = true;
//x_pos+=.05;
}
if (input.isKeyDown(Input.KEY_SPACE))
{
test.player.Start_Sword_Attack();
}
else
{
test.player.End_Sword_Attack();
}
// change the player's movement value
test.move_player((right? 1:0) - (left? 1:0),
(down? 1:0) - (up? 1:0));
test.update();
}
// Game Rendering
@Override
public void render(GameContainer gc, Graphics g) throws SlickException {
test.display(gc, g);
/*
g.drawImage(link_down_bot, x_pos, y_pos);
g.drawImage(link_down_top, x_pos, y_pos-16);
*/
// TODO: code render
}
};
AppGameContainer container;
try {
container = new AppGameContainer(game); // create game instance
container.start(); // start game instance
} catch (SlickException ex) { // catch exceptions
ex.printStackTrace();
Logger.getLogger(Zed.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| true | true | public static void main(String[] args) throws SlickException {
// create game
org.newdawn.slick.BasicGame game = new org.newdawn.slick.BasicGame("zed") {
// Test-level
Level_Manager test;
// Sounds
Music music = new Music("soundtrack/kawfy/braintwoquart.wav");
// Game Initialization
@Override
public void init(GameContainer gc) throws SlickException {
/*
// Initialize test-images
link_down_bot = new Image("images/link-down-bot.png",
false, Image.FILTER_NEAREST);
link_down_top = new Image("images/link-down-top.png",
false, Image.FILTER_NEAREST);
*/
// Initialize test-level
test = new Level_Manager();
music.loop();
}
// Game Updates
@Override
public void update(GameContainer gc, int delta) throws SlickException {
boolean left = false; //these arent currently being used be needed
boolean right = false;
boolean up = false;
boolean down = false;
gc.setVSync(true); // makes it so computer doesn't heat up
//gc.setTargetFrameRate(120);
Input input = gc.getInput(); // get the current input
if (input.isKeyDown(Input.KEY_UP) || input.isKeyDown(Input.KEY_W))
{
up = true;
//y_pos-=.05;
}
if (input.isKeyDown(Input.KEY_LEFT) || input.isKeyDown(Input.KEY_A))
{
left = true;
//x_pos-=.05;
}
if (input.isKeyDown(Input.KEY_DOWN) || input.isKeyDown(Input.KEY_S))
{
down = true;
//y_pos+=.05;
}
if (input.isKeyDown(Input.KEY_RIGHT) || input.isKeyDown(Input.KEY_D))
{
right = true;
//x_pos+=.05;
}
if (input.isKeyDown(Input.KEY_SPACE))
{
test.player.Start_Sword_Attack();
}
else
{
test.player.End_Sword_Attack();
}
// change the player's movement value
test.move_player((right? 1:0) - (left? 1:0),
(down? 1:0) - (up? 1:0));
test.update();
}
// Game Rendering
@Override
public void render(GameContainer gc, Graphics g) throws SlickException {
test.display(gc, g);
/*
g.drawImage(link_down_bot, x_pos, y_pos);
g.drawImage(link_down_top, x_pos, y_pos-16);
*/
// TODO: code render
}
};
AppGameContainer container;
try {
container = new AppGameContainer(game); // create game instance
container.start(); // start game instance
} catch (SlickException ex) { // catch exceptions
ex.printStackTrace();
Logger.getLogger(Zed.class.getName()).log(Level.SEVERE, null, ex);
}
}
| public static void main(String[] args) throws SlickException {
// create game
org.newdawn.slick.BasicGame game = new org.newdawn.slick.BasicGame("zed") {
// Test-level
Level_Manager test;
// Sounds
Music music = new Music("soundtrack/kawfy/braintwoquart.wav");
// Game Initialization
@Override
public void init(GameContainer gc) throws SlickException {
/*
// Initialize test-images
link_down_bot = new Image("images/link-down-bot.png",
false, Image.FILTER_NEAREST);
link_down_top = new Image("images/link-down-top.png",
false, Image.FILTER_NEAREST);
*/
// Initialize test-level
test = new Level_Manager();
music.loop();
}
// Game Updates
@Override
public void update(GameContainer gc, int delta) throws SlickException {
boolean left = false; //these arent currently being used be needed
boolean right = false;
boolean up = false;
boolean down = false;
gc.setVSync(true); // makes it so computer doesn't heat up
//gc.setTargetFrameRate(120);
Input input = gc.getInput(); // get the current input
if (input.isKeyDown(Input.KEY_UP) || input.isKeyDown(Input.KEY_W))
{
up = true;
//y_pos-=.05;
}
if (input.isKeyDown(Input.KEY_LEFT) || input.isKeyDown(Input.KEY_A))
{
left = true;
//x_pos-=.05;
}
if (input.isKeyDown(Input.KEY_DOWN) || input.isKeyDown(Input.KEY_S))
{
down = true;
//y_pos+=.05;
}
if (input.isKeyDown(Input.KEY_RIGHT) || input.isKeyDown(Input.KEY_D))
{
right = true;
//x_pos+=.05;
}
if (input.isKeyDown(Input.KEY_SPACE))
{
test.player.Start_Sword_Attack();
}
else
{
test.player.End_Sword_Attack();
}
// change the player's movement value
test.move_player((right? 1:0) - (left? 1:0),
(down? 1:0) - (up? 1:0));
test.update();
}
// Game Rendering
@Override
public void render(GameContainer gc, Graphics g) throws SlickException {
test.display(gc, g);
/*
g.drawImage(link_down_bot, x_pos, y_pos);
g.drawImage(link_down_top, x_pos, y_pos-16);
*/
// TODO: code render
}
};
AppGameContainer container;
try {
container = new AppGameContainer(game); // create game instance
container.start(); // start game instance
} catch (SlickException ex) { // catch exceptions
ex.printStackTrace();
Logger.getLogger(Zed.class.getName()).log(Level.SEVERE, null, ex);
}
}
|
diff --git a/frontend/src/main/java/cl/own/usi/gateway/netty/controller/AnswerController.java b/frontend/src/main/java/cl/own/usi/gateway/netty/controller/AnswerController.java
index 731311e..baa70da 100644
--- a/frontend/src/main/java/cl/own/usi/gateway/netty/controller/AnswerController.java
+++ b/frontend/src/main/java/cl/own/usi/gateway/netty/controller/AnswerController.java
@@ -1,124 +1,124 @@
package cl.own.usi.gateway.netty.controller;
import static cl.own.usi.gateway.netty.ResponseHelper.writeResponse;
import static cl.own.usi.gateway.netty.ResponseHelper.writeStringToReponse;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.CREATED;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.UNAUTHORIZED;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.util.CharsetUtil;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import cl.own.usi.gateway.client.WorkerClient;
import cl.own.usi.gateway.client.WorkerClient.UserAndScoreAndAnswer;
import cl.own.usi.model.Question;
import cl.own.usi.service.GameService;
/**
* Controller that validate and call for storing the answer.
*
* @author bperroud
* @author nicolas
*
*/
@Component
public class AnswerController extends AbstractController {
public static final String URI_ANSWER = "/answer/";
protected static final int URI_ANSWER_LENGTH = URI_ANSWER.length();
@Autowired
private GameService gameService;
@Autowired
private WorkerClient workerClient;
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
throws Exception {
HttpRequest request = (HttpRequest) e.getMessage();
String uri = request.getUri();
uri = uri.substring(URI_API_LENGTH);
String userId = getCookie(request, COOKIE_AUTH_NAME);
if (userId == null) {
writeResponse(e, UNAUTHORIZED);
getLogger().info("User not authorized");
} else {
try {
int questionNumber = Integer.parseInt(uri
.substring(URI_ANSWER_LENGTH));
if (!gameService
.validateQuestionToAnswer(questionNumber)) {
writeResponse(e, BAD_REQUEST);
getLogger().info("Invalid question number"
+ questionNumber);
} else {
getLogger().debug("Answer Question " + questionNumber
+ " for user " + userId);
gameService.userAnswer(questionNumber);
JSONObject object = (JSONObject) JSONValue
.parse(request.getContent().toString(
CharsetUtil.UTF_8));
Question question = gameService
.getQuestion(questionNumber);
Long answerLong = ((Long) object.get("answer"));
Integer answer = null;
if (answerLong != null) {
answer = answerLong.intValue();
}
// answer =
// gameService.validateAnswer(questionNumber,
// answer);
// boolean answerCorrect =
// gameService.isAnswerCorrect(questionNumber,
// answer);
UserAndScoreAndAnswer userAndScoreAndAnswer = workerClient
.validateUserAndInsertQuestionResponseAndUpdateScore(
userId, questionNumber, answer);
if (userAndScoreAndAnswer.userId == null) {
writeResponse(e, BAD_REQUEST);
getLogger().info("Invalid userId " + userId);
} else {
StringBuilder sb = new StringBuilder(
"{ \"are_u_ok\" : ");
if (userAndScoreAndAnswer.answer) {
sb.append("true");
} else {
sb.append("false");
}
sb.append(", \"good_answer\" : \""
+ question.getChoices().get(
- question.getCorrectChoice())
+ question.getCorrectChoice() - 1)
+ "\", \"score\" : "
+ userAndScoreAndAnswer.score + "}");
writeStringToReponse(sb.toString(), e, CREATED);
}
}
} catch (NumberFormatException exception) {
writeResponse(e, BAD_REQUEST);
getLogger().warn("NumberFormatException", exception);
}
}
}
}
| true | true | public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
throws Exception {
HttpRequest request = (HttpRequest) e.getMessage();
String uri = request.getUri();
uri = uri.substring(URI_API_LENGTH);
String userId = getCookie(request, COOKIE_AUTH_NAME);
if (userId == null) {
writeResponse(e, UNAUTHORIZED);
getLogger().info("User not authorized");
} else {
try {
int questionNumber = Integer.parseInt(uri
.substring(URI_ANSWER_LENGTH));
if (!gameService
.validateQuestionToAnswer(questionNumber)) {
writeResponse(e, BAD_REQUEST);
getLogger().info("Invalid question number"
+ questionNumber);
} else {
getLogger().debug("Answer Question " + questionNumber
+ " for user " + userId);
gameService.userAnswer(questionNumber);
JSONObject object = (JSONObject) JSONValue
.parse(request.getContent().toString(
CharsetUtil.UTF_8));
Question question = gameService
.getQuestion(questionNumber);
Long answerLong = ((Long) object.get("answer"));
Integer answer = null;
if (answerLong != null) {
answer = answerLong.intValue();
}
// answer =
// gameService.validateAnswer(questionNumber,
// answer);
// boolean answerCorrect =
// gameService.isAnswerCorrect(questionNumber,
// answer);
UserAndScoreAndAnswer userAndScoreAndAnswer = workerClient
.validateUserAndInsertQuestionResponseAndUpdateScore(
userId, questionNumber, answer);
if (userAndScoreAndAnswer.userId == null) {
writeResponse(e, BAD_REQUEST);
getLogger().info("Invalid userId " + userId);
} else {
StringBuilder sb = new StringBuilder(
"{ \"are_u_ok\" : ");
if (userAndScoreAndAnswer.answer) {
sb.append("true");
} else {
sb.append("false");
}
sb.append(", \"good_answer\" : \""
+ question.getChoices().get(
question.getCorrectChoice())
+ "\", \"score\" : "
+ userAndScoreAndAnswer.score + "}");
writeStringToReponse(sb.toString(), e, CREATED);
}
}
} catch (NumberFormatException exception) {
writeResponse(e, BAD_REQUEST);
getLogger().warn("NumberFormatException", exception);
}
}
}
| public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
throws Exception {
HttpRequest request = (HttpRequest) e.getMessage();
String uri = request.getUri();
uri = uri.substring(URI_API_LENGTH);
String userId = getCookie(request, COOKIE_AUTH_NAME);
if (userId == null) {
writeResponse(e, UNAUTHORIZED);
getLogger().info("User not authorized");
} else {
try {
int questionNumber = Integer.parseInt(uri
.substring(URI_ANSWER_LENGTH));
if (!gameService
.validateQuestionToAnswer(questionNumber)) {
writeResponse(e, BAD_REQUEST);
getLogger().info("Invalid question number"
+ questionNumber);
} else {
getLogger().debug("Answer Question " + questionNumber
+ " for user " + userId);
gameService.userAnswer(questionNumber);
JSONObject object = (JSONObject) JSONValue
.parse(request.getContent().toString(
CharsetUtil.UTF_8));
Question question = gameService
.getQuestion(questionNumber);
Long answerLong = ((Long) object.get("answer"));
Integer answer = null;
if (answerLong != null) {
answer = answerLong.intValue();
}
// answer =
// gameService.validateAnswer(questionNumber,
// answer);
// boolean answerCorrect =
// gameService.isAnswerCorrect(questionNumber,
// answer);
UserAndScoreAndAnswer userAndScoreAndAnswer = workerClient
.validateUserAndInsertQuestionResponseAndUpdateScore(
userId, questionNumber, answer);
if (userAndScoreAndAnswer.userId == null) {
writeResponse(e, BAD_REQUEST);
getLogger().info("Invalid userId " + userId);
} else {
StringBuilder sb = new StringBuilder(
"{ \"are_u_ok\" : ");
if (userAndScoreAndAnswer.answer) {
sb.append("true");
} else {
sb.append("false");
}
sb.append(", \"good_answer\" : \""
+ question.getChoices().get(
question.getCorrectChoice() - 1)
+ "\", \"score\" : "
+ userAndScoreAndAnswer.score + "}");
writeStringToReponse(sb.toString(), e, CREATED);
}
}
} catch (NumberFormatException exception) {
writeResponse(e, BAD_REQUEST);
getLogger().warn("NumberFormatException", exception);
}
}
}
|
diff --git a/invoice/src/main/java/com/ning/billing/invoice/dao/InvoiceItemModelDao.java b/invoice/src/main/java/com/ning/billing/invoice/dao/InvoiceItemModelDao.java
index 0d96a177c..c0a6804d3 100644
--- a/invoice/src/main/java/com/ning/billing/invoice/dao/InvoiceItemModelDao.java
+++ b/invoice/src/main/java/com/ning/billing/invoice/dao/InvoiceItemModelDao.java
@@ -1,228 +1,228 @@
/*
* Copyright 2010-2012 Ning, Inc.
*
* Ning 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 com.ning.billing.invoice.dao;
import java.math.BigDecimal;
import java.util.UUID;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import com.ning.billing.catalog.api.Currency;
import com.ning.billing.invoice.api.InvoiceItem;
import com.ning.billing.invoice.api.InvoiceItemType;
import com.ning.billing.util.entity.EntityBase;
public class InvoiceItemModelDao extends EntityBase {
private final InvoiceItemType type;
private final UUID invoiceId;
private final UUID accountId;
private final UUID bundleId;
private final UUID subscriptionId;
private final String planName;
private final String phaseName;
private final LocalDate startDate;
private final LocalDate endDate;
private final BigDecimal amount;
private final BigDecimal rate;
private final Currency currency;
private final UUID linkedItemId;
public InvoiceItemModelDao(final UUID id, final DateTime createdDate, final InvoiceItemType type, final UUID invoiceId,
final UUID accountId, final UUID bundleId, final UUID subscriptionId, final String planName,
final String phaseName, final LocalDate startDate, final LocalDate endDate, final BigDecimal amount,
final BigDecimal rate, final Currency currency, final UUID linkedItemId) {
super(id, createdDate, createdDate);
this.type = type;
this.invoiceId = invoiceId;
this.accountId = accountId;
this.bundleId = bundleId;
this.subscriptionId = subscriptionId;
this.planName = planName;
this.phaseName = phaseName;
this.startDate = startDate;
this.endDate = endDate;
this.amount = amount;
this.rate = rate;
this.currency = currency;
this.linkedItemId = linkedItemId;
}
public InvoiceItemModelDao(final DateTime createdDate, final InvoiceItemType type, final UUID invoiceId, final UUID accountId,
final UUID bundleId, final UUID subscriptionId, final String planName,
final String phaseName, final LocalDate startDate, final LocalDate endDate, final BigDecimal amount,
final BigDecimal rate, final Currency currency, final UUID linkedItemId) {
this(UUID.randomUUID(), createdDate, type, invoiceId, accountId, bundleId, subscriptionId, planName, phaseName,
startDate, endDate, amount, rate, currency, linkedItemId);
}
public InvoiceItemModelDao(final InvoiceItem invoiceItem) {
this(invoiceItem.getId(), invoiceItem.getCreatedDate(), invoiceItem.getInvoiceItemType(), invoiceItem.getInvoiceId(), invoiceItem.getAccountId(), invoiceItem.getBundleId(),
invoiceItem.getSubscriptionId(), invoiceItem.getPlanName(), invoiceItem.getPhaseName(), invoiceItem.getStartDate(), invoiceItem.getEndDate(),
invoiceItem.getAmount(), invoiceItem.getRate(), invoiceItem.getCurrency(), invoiceItem.getLinkedItemId());
}
public InvoiceItemType getType() {
return type;
}
public UUID getInvoiceId() {
return invoiceId;
}
public UUID getAccountId() {
return accountId;
}
public UUID getBundleId() {
return bundleId;
}
public UUID getSubscriptionId() {
return subscriptionId;
}
public String getPlanName() {
return planName;
}
public String getPhaseName() {
return phaseName;
}
public LocalDate getStartDate() {
return startDate;
}
public LocalDate getEndDate() {
return endDate;
}
public BigDecimal getAmount() {
return amount;
}
public BigDecimal getRate() {
return rate;
}
public Currency getCurrency() {
return currency;
}
public UUID getLinkedItemId() {
return linkedItemId;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("InvoiceItemModelDao");
sb.append("{type=").append(type);
sb.append(", invoiceId=").append(invoiceId);
sb.append(", accountId=").append(accountId);
sb.append(", bundleId=").append(bundleId);
sb.append(", subscriptionId=").append(subscriptionId);
sb.append(", planName='").append(planName).append('\'');
sb.append(", phaseName='").append(phaseName).append('\'');
sb.append(", startDate=").append(startDate);
sb.append(", endDate=").append(endDate);
sb.append(", amount=").append(amount);
sb.append(", rate=").append(rate);
sb.append(", currency=").append(currency);
sb.append(", linkedItemId=").append(linkedItemId);
sb.append('}');
return sb.toString();
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
final InvoiceItemModelDao that = (InvoiceItemModelDao) o;
if (accountId != null ? !accountId.equals(that.accountId) : that.accountId != null) {
return false;
}
- if (amount != null ? !amount.equals(that.amount) : that.amount != null) {
+ if (amount != null ? amount.compareTo(that.amount) != 0 : that.amount != null) {
return false;
}
if (bundleId != null ? !bundleId.equals(that.bundleId) : that.bundleId != null) {
return false;
}
if (currency != that.currency) {
return false;
}
if (endDate != null ? !endDate.equals(that.endDate) : that.endDate != null) {
return false;
}
if (invoiceId != null ? !invoiceId.equals(that.invoiceId) : that.invoiceId != null) {
return false;
}
if (linkedItemId != null ? !linkedItemId.equals(that.linkedItemId) : that.linkedItemId != null) {
return false;
}
if (phaseName != null ? !phaseName.equals(that.phaseName) : that.phaseName != null) {
return false;
}
if (planName != null ? !planName.equals(that.planName) : that.planName != null) {
return false;
}
- if (rate != null ? !rate.equals(that.rate) : that.rate != null) {
+ if (rate != null ? rate.compareTo(that.rate) != 0 : that.rate != null) {
return false;
}
if (startDate != null ? !startDate.equals(that.startDate) : that.startDate != null) {
return false;
}
if (subscriptionId != null ? !subscriptionId.equals(that.subscriptionId) : that.subscriptionId != null) {
return false;
}
if (type != that.type) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (type != null ? type.hashCode() : 0);
result = 31 * result + (invoiceId != null ? invoiceId.hashCode() : 0);
result = 31 * result + (accountId != null ? accountId.hashCode() : 0);
result = 31 * result + (bundleId != null ? bundleId.hashCode() : 0);
result = 31 * result + (subscriptionId != null ? subscriptionId.hashCode() : 0);
result = 31 * result + (planName != null ? planName.hashCode() : 0);
result = 31 * result + (phaseName != null ? phaseName.hashCode() : 0);
result = 31 * result + (startDate != null ? startDate.hashCode() : 0);
result = 31 * result + (endDate != null ? endDate.hashCode() : 0);
result = 31 * result + (amount != null ? amount.hashCode() : 0);
result = 31 * result + (rate != null ? rate.hashCode() : 0);
result = 31 * result + (currency != null ? currency.hashCode() : 0);
result = 31 * result + (linkedItemId != null ? linkedItemId.hashCode() : 0);
return result;
}
}
| false | true | public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
final InvoiceItemModelDao that = (InvoiceItemModelDao) o;
if (accountId != null ? !accountId.equals(that.accountId) : that.accountId != null) {
return false;
}
if (amount != null ? !amount.equals(that.amount) : that.amount != null) {
return false;
}
if (bundleId != null ? !bundleId.equals(that.bundleId) : that.bundleId != null) {
return false;
}
if (currency != that.currency) {
return false;
}
if (endDate != null ? !endDate.equals(that.endDate) : that.endDate != null) {
return false;
}
if (invoiceId != null ? !invoiceId.equals(that.invoiceId) : that.invoiceId != null) {
return false;
}
if (linkedItemId != null ? !linkedItemId.equals(that.linkedItemId) : that.linkedItemId != null) {
return false;
}
if (phaseName != null ? !phaseName.equals(that.phaseName) : that.phaseName != null) {
return false;
}
if (planName != null ? !planName.equals(that.planName) : that.planName != null) {
return false;
}
if (rate != null ? !rate.equals(that.rate) : that.rate != null) {
return false;
}
if (startDate != null ? !startDate.equals(that.startDate) : that.startDate != null) {
return false;
}
if (subscriptionId != null ? !subscriptionId.equals(that.subscriptionId) : that.subscriptionId != null) {
return false;
}
if (type != that.type) {
return false;
}
return true;
}
| public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
final InvoiceItemModelDao that = (InvoiceItemModelDao) o;
if (accountId != null ? !accountId.equals(that.accountId) : that.accountId != null) {
return false;
}
if (amount != null ? amount.compareTo(that.amount) != 0 : that.amount != null) {
return false;
}
if (bundleId != null ? !bundleId.equals(that.bundleId) : that.bundleId != null) {
return false;
}
if (currency != that.currency) {
return false;
}
if (endDate != null ? !endDate.equals(that.endDate) : that.endDate != null) {
return false;
}
if (invoiceId != null ? !invoiceId.equals(that.invoiceId) : that.invoiceId != null) {
return false;
}
if (linkedItemId != null ? !linkedItemId.equals(that.linkedItemId) : that.linkedItemId != null) {
return false;
}
if (phaseName != null ? !phaseName.equals(that.phaseName) : that.phaseName != null) {
return false;
}
if (planName != null ? !planName.equals(that.planName) : that.planName != null) {
return false;
}
if (rate != null ? rate.compareTo(that.rate) != 0 : that.rate != null) {
return false;
}
if (startDate != null ? !startDate.equals(that.startDate) : that.startDate != null) {
return false;
}
if (subscriptionId != null ? !subscriptionId.equals(that.subscriptionId) : that.subscriptionId != null) {
return false;
}
if (type != that.type) {
return false;
}
return true;
}
|
diff --git a/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/xobject/PDJpeg.java b/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/xobject/PDJpeg.java
index 0b50a26..59874ea 100644
--- a/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/xobject/PDJpeg.java
+++ b/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/xobject/PDJpeg.java
@@ -1,531 +1,533 @@
/*
* 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.pdfbox.pdmodel.graphics.xobject;
import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.Transparency;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.ComponentColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
import javax.imageio.IIOException;
import javax.imageio.ImageReader;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageInputStream;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.common.PDStream;
import org.apache.pdfbox.pdmodel.common.function.PDFunction;
import org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace;
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceCMYK;
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceGray;
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceN;
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB;
import org.apache.pdfbox.pdmodel.graphics.color.PDICCBased;
import org.apache.pdfbox.pdmodel.graphics.color.PDSeparation;
import org.apache.pdfbox.util.ImageIOUtil;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* An image class for JPegs.
*
* @author mathiak
* @version $Revision: 1.5 $
*/
public class PDJpeg extends PDXObjectImage
{
private BufferedImage image = null;
private static final String JPG = "jpg";
private static final List<String> DCT_FILTERS = new ArrayList<String>();
private static final float DEFAULT_COMPRESSION_LEVEL = 0.75f;
static
{
DCT_FILTERS.add( COSName.DCT_DECODE.getName() );
DCT_FILTERS.add( COSName.DCT_DECODE_ABBREVIATION.getName() );
}
/**
* Standard constructor.
*
* @param jpeg The COSStream from which to extract the JPeg
*/
public PDJpeg(PDStream jpeg)
{
super(jpeg, JPG);
}
/**
* Construct from a stream.
*
* @param doc The document to create the image as part of.
* @param is The stream that contains the jpeg data.
* @throws IOException If there is an error reading the jpeg data.
*/
public PDJpeg( PDDocument doc, InputStream is ) throws IOException
{
super( new PDStream( doc, is, true ), JPG);
COSDictionary dic = getCOSStream();
dic.setItem( COSName.FILTER, COSName.DCT_DECODE );
dic.setItem( COSName.SUBTYPE, COSName.IMAGE);
dic.setItem( COSName.TYPE, COSName.XOBJECT );
getRGBImage();
if (image != null)
{
setBitsPerComponent( 8 );
setColorSpace( PDDeviceRGB.INSTANCE );
setHeight( image.getHeight() );
setWidth( image.getWidth() );
}
}
/**
* Construct from a buffered image.
* The default compression level of 0.75 will be used.
*
* @param doc The document to create the image as part of.
* @param bi The image to convert to a jpeg
* @throws IOException If there is an error processing the jpeg data.
*/
public PDJpeg( PDDocument doc, BufferedImage bi ) throws IOException
{
super( new PDStream( doc ) , JPG);
createImageStream(doc, bi, DEFAULT_COMPRESSION_LEVEL);
}
/**
* Construct from a buffered image.
*
* @param doc The document to create the image as part of.
* @param bi The image to convert to a jpeg
* @param compressionQuality The quality level which is used to compress the image
* @throws IOException If there is an error processing the jpeg data.
*/
public PDJpeg( PDDocument doc, BufferedImage bi, float compressionQuality ) throws IOException
{
super( new PDStream( doc ), JPG);
createImageStream(doc, bi, compressionQuality);
}
private void createImageStream(PDDocument doc, BufferedImage bi, float compressionQuality) throws IOException
{
BufferedImage alpha = null;
if (bi.getColorModel().hasAlpha())
{
// extract the alpha information
WritableRaster alphaRaster = bi.getAlphaRaster();
ColorModel cm = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_GRAY),
false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
alpha = new BufferedImage(cm, alphaRaster, false, null);
// create a RGB image without alpha
image = new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.setComposite(AlphaComposite.Src);
g.drawImage(bi, 0, 0, null);
bi = image;
}
java.io.OutputStream os = getCOSStream().createFilteredStream();
try
{
ImageIOUtil.writeImage(bi, JPG, os, ImageIOUtil.DEFAULT_SCREEN_RESOLUTION, compressionQuality);
COSDictionary dic = getCOSStream();
dic.setItem( COSName.FILTER, COSName.DCT_DECODE );
dic.setItem( COSName.SUBTYPE, COSName.IMAGE);
dic.setItem( COSName.TYPE, COSName.XOBJECT );
PDXObjectImage alphaPdImage = null;
if(alpha != null)
{
alphaPdImage = new PDJpeg(doc, alpha, compressionQuality);
dic.setItem(COSName.SMASK, alphaPdImage);
}
setBitsPerComponent( 8 );
if (bi.getColorModel().getNumComponents() == 3)
{
setColorSpace( PDDeviceRGB.INSTANCE );
}
else
{
if (bi.getColorModel().getNumComponents() == 1)
{
setColorSpace( new PDDeviceGray() );
}
else
{
throw new IllegalStateException();
}
}
setHeight( bi.getHeight() );
setWidth( bi.getWidth() );
}
finally
{
os.close();
}
}
/**
* Returns an image of the JPeg, or null if JPegs are not supported. (They should be. )
* {@inheritDoc}
*/
public BufferedImage getRGBImage() throws IOException
{
if (image != null)
{
+ // use the cached image
return image;
}
BufferedImage bi = null;
boolean readError = false;
ByteArrayOutputStream os = new ByteArrayOutputStream();
removeAllFiltersButDCT(os);
os.close();
byte[] img = os.toByteArray();
PDColorSpace cs = getColorSpace();
try
{
if (cs instanceof PDDeviceCMYK
|| (cs instanceof PDICCBased && cs.getNumberOfComponents() == 4))
{
// JPEGs may contain CMYK, YCbCr or YCCK decoded image data
int transform = getApp14AdobeTransform(img);
// create BufferedImage based on the converted color values
if (transform == 0)
{
bi = convertCMYK2RGB(readImage(img), cs);
}
else if (transform == 1)
{
// TODO YCbCr
}
else if (transform == 2)
{
bi = convertYCCK2RGB(readImage(img));
}
}
else if (cs instanceof PDSeparation)
{
// create BufferedImage based on the converted color values
bi = processTintTransformation(readImage(img),
((PDSeparation)cs).getTintTransform(), cs.getJavaColorSpace());
}
else if (cs instanceof PDDeviceN)
{
// create BufferedImage based on the converted color values
bi = processTintTransformation(readImage(img),
((PDDeviceN)cs).getTintTransform(), cs.getJavaColorSpace());
}
else
{
ByteArrayInputStream bai = new ByteArrayInputStream(img);
bi = ImageIO.read(bai);
}
}
catch(IIOException exception)
{
readError = true;
}
// 2. try to read jpeg again. some jpegs have some strange header containing
// "Adobe " at some place. so just replace the header with a valid jpeg header.
// TODO : not sure if it works for all cases
if (bi == null && readError)
{
byte[] newImage = replaceHeader(img);
ByteArrayInputStream bai = new ByteArrayInputStream(newImage);
bi = ImageIO.read(bai);
}
// If there is a 'soft mask' or 'mask' image then we use that as a transparency mask.
- return applyMasks(bi);
+ image = applyMasks(bi);
+ return image;
}
/**
* This writes the JPeg to out.
* {@inheritDoc}
*/
public void write2OutputStream(OutputStream out) throws IOException
{
getRGBImage();
if (image != null)
{
ImageIOUtil.writeImage(image, JPG, out);
}
}
private void removeAllFiltersButDCT(OutputStream out) throws IOException
{
InputStream data = getPDStream().getPartiallyFilteredStream( DCT_FILTERS );
byte[] buf = new byte[1024];
int amountRead = -1;
while( (amountRead = data.read( buf )) != -1 )
{
out.write( buf, 0, amountRead );
}
}
private int getHeaderEndPos(byte[] imageAsBytes)
{
for (int i = 0; i < imageAsBytes.length; i++)
{
byte b = imageAsBytes[i];
if (b == (byte) 0xDB)
{
// TODO : check for ff db
return i -2;
}
}
return 0;
}
private byte[] replaceHeader(byte[] imageAsBytes)
{
// get end position of wrong header respectively startposition of "real jpeg data"
int pos = getHeaderEndPos(imageAsBytes);
// simple correct header
byte[] header = new byte[]{(byte) 0xFF, (byte) 0xD8, (byte) 0xFF, (byte) 0xE0, (byte) 0x00,
(byte) 0x10, (byte) 0x4A, (byte) 0x46, (byte) 0x49, (byte) 0x46, (byte) 0x00, (byte) 0x01,
(byte) 0x01, (byte) 0x01, (byte) 0x00, (byte) 0x60, (byte) 0x00, (byte) 0x60, (byte) 0x00, (byte) 0x00};
// concat
byte[] newImage = new byte[imageAsBytes.length - pos + header.length - 1];
System.arraycopy(header, 0, newImage, 0, header.length);
System.arraycopy(imageAsBytes, pos + 1, newImage, header.length, imageAsBytes.length - pos - 1);
return newImage;
}
private int getApp14AdobeTransform(byte[] bytes)
{
int transformType = 0;
ImageReader reader = null;
ImageInputStream input = null;
try
{
input = ImageIO.createImageInputStream(new ByteArrayInputStream(bytes));
Iterator<ImageReader> readers = ImageIO.getImageReaders(input);
if (readers == null || !readers.hasNext())
{
input.close();
throw new RuntimeException("No ImageReaders found");
}
reader = (ImageReader) readers.next();
reader.setInput(input);
IIOMetadata meta = reader.getImageMetadata(0);
if (meta != null)
{
Node tree = meta.getAsTree("javax_imageio_jpeg_image_1.0");
NodeList children = tree.getChildNodes();
for (int i=0;i<children.getLength();i++)
{
Node markerSequence = children.item(i);
if ("markerSequence".equals(markerSequence.getNodeName()))
{
NodeList markerSequenceChildren = markerSequence.getChildNodes();
for (int j=0;j<markerSequenceChildren.getLength();j++)
{
Node child = markerSequenceChildren.item(j);
if ("app14Adobe".equals(child.getNodeName()) && child.hasAttributes())
{
NamedNodeMap attribs = child.getAttributes();
Node transformNode = attribs.getNamedItem("transform");
transformType = Integer.parseInt(transformNode.getNodeValue());
break;
}
}
}
}
}
}
catch(IOException exception)
{
}
finally
{
if (reader != null)
{
reader.dispose();
}
}
return transformType;
}
private Raster readImage(byte[] bytes) throws IOException
{
ImageInputStream input = ImageIO.createImageInputStream(new ByteArrayInputStream(bytes));
Iterator<ImageReader> readers = ImageIO.getImageReaders(input);
if (readers == null || !readers.hasNext())
{
input.close();
throw new RuntimeException("No ImageReaders found");
}
// read the raster information only
// avoid to access the meta information
ImageReader reader = (ImageReader) readers.next();
reader.setInput(input);
Raster raster = reader.readRaster(0, reader.getDefaultReadParam());
input.close();
reader.dispose();
return raster;
}
// CMYK jpegs are not supported by JAI, so that we have to do the conversion on our own
private BufferedImage convertCMYK2RGB(Raster raster, PDColorSpace colorspace) throws IOException
{
// create a java color space to be used for conversion
ColorSpace cs = colorspace.getJavaColorSpace();
int width = raster.getWidth();
int height = raster.getHeight();
byte[] rgb = new byte[width * height * 3];
int rgbIndex = 0;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
// get the source color values
float[] srcColorValues = raster.getPixel(j,i, (float[])null);
// convert values from 0..255 to 0..1
for (int k = 0; k < 4; k++)
{
srcColorValues[k] /= 255f;
}
// convert CMYK to RGB
float[] rgbValues = cs.toRGB(srcColorValues);
// convert values from 0..1 to 0..255
for (int k = 0; k < 3; k++)
{
rgb[rgbIndex+k] = (byte)(rgbValues[k] * 255);
}
rgbIndex +=3;
}
}
return createRGBBufferedImage(ColorSpace.getInstance(ColorSpace.CS_sRGB), rgb, width, height);
}
// YCbCrK jpegs are not supported by JAI, so that we have to do the conversion on our own
private BufferedImage convertYCCK2RGB(Raster raster) throws IOException
{
int width = raster.getWidth();
int height = raster.getHeight();
byte[] rgb = new byte[width * height * 3];
int rgbIndex = 0;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
float[] srcColorValues = raster.getPixel(j,i, (float[])null);
float k = srcColorValues[3];
float y = srcColorValues[0];
float c1=srcColorValues[1];
float c2=srcColorValues[2];
double val = y + 1.402 * ( c2 - 128 ) - k;
rgb[rgbIndex] = val < 0.0 ? (byte)0 : (val>255.0? (byte)0xff : (byte)(val+0.5));
val = y - 0.34414 * ( c1 - 128 ) - 0.71414 * ( c2 - 128 ) - k;
rgb[rgbIndex+1] = val<0.0? (byte)0: val>255.0? (byte)0xff: (byte)(val+0.5);
val = y + 1.772 * ( c1 - 128 ) - k;
rgb[rgbIndex+2] = val<0.0? (byte)0: val>255.0? (byte)0xff: (byte)(val+0.5);
rgbIndex +=3;
}
}
return createRGBBufferedImage(ColorSpace.getInstance(ColorSpace.CS_sRGB), rgb, width, height);
}
// Separation and DeviceN colorspaces are using a tint transform function to convert color values
private BufferedImage processTintTransformation(Raster raster, PDFunction function, ColorSpace colorspace)
throws IOException
{
int numberOfInputValues = function.getNumberOfInputParameters();
int numberOfOutputValues = function.getNumberOfOutputParameters();
int width = raster.getWidth();
int height = raster.getHeight();
byte[] rgb = new byte[width * height * numberOfOutputValues];
int bufferIndex = 0;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
// get the source color values
float[] srcColorValues = raster.getPixel(j,i, (float[])null);
// convert values from 0..255 to 0..1
for (int k = 0; k < numberOfInputValues; k++)
{
srcColorValues[k] /= 255f;
}
// transform the color values using the tint function
float[] convertedValues = function.eval(srcColorValues);
// convert values from 0..1 to 0..255
for (int k = 0; k < numberOfOutputValues; k++)
{
rgb[bufferIndex+k] = (byte)(convertedValues[k] * 255);
}
bufferIndex +=numberOfOutputValues;
}
}
return createRGBBufferedImage(colorspace, rgb, width, height);
}
private BufferedImage createRGBBufferedImage(ColorSpace cs, byte[] rgb, int width, int height)
{
// create a RGB color model
ColorModel cm = new ComponentColorModel(cs, false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
// create the target raster
WritableRaster writeableRaster = cm.createCompatibleWritableRaster(width, height);
// get the data buffer of the raster
DataBufferByte buffer = (DataBufferByte)writeableRaster.getDataBuffer();
byte[] bufferData = buffer.getData();
// copy all the converted data to the raster buffer
System.arraycopy( rgb, 0,bufferData, 0,rgb.length );
// create an image using the converted color values
return new BufferedImage(cm, writeableRaster, true, null);
}
}
| false | true | public BufferedImage getRGBImage() throws IOException
{
if (image != null)
{
return image;
}
BufferedImage bi = null;
boolean readError = false;
ByteArrayOutputStream os = new ByteArrayOutputStream();
removeAllFiltersButDCT(os);
os.close();
byte[] img = os.toByteArray();
PDColorSpace cs = getColorSpace();
try
{
if (cs instanceof PDDeviceCMYK
|| (cs instanceof PDICCBased && cs.getNumberOfComponents() == 4))
{
// JPEGs may contain CMYK, YCbCr or YCCK decoded image data
int transform = getApp14AdobeTransform(img);
// create BufferedImage based on the converted color values
if (transform == 0)
{
bi = convertCMYK2RGB(readImage(img), cs);
}
else if (transform == 1)
{
// TODO YCbCr
}
else if (transform == 2)
{
bi = convertYCCK2RGB(readImage(img));
}
}
else if (cs instanceof PDSeparation)
{
// create BufferedImage based on the converted color values
bi = processTintTransformation(readImage(img),
((PDSeparation)cs).getTintTransform(), cs.getJavaColorSpace());
}
else if (cs instanceof PDDeviceN)
{
// create BufferedImage based on the converted color values
bi = processTintTransformation(readImage(img),
((PDDeviceN)cs).getTintTransform(), cs.getJavaColorSpace());
}
else
{
ByteArrayInputStream bai = new ByteArrayInputStream(img);
bi = ImageIO.read(bai);
}
}
catch(IIOException exception)
{
readError = true;
}
// 2. try to read jpeg again. some jpegs have some strange header containing
// "Adobe " at some place. so just replace the header with a valid jpeg header.
// TODO : not sure if it works for all cases
if (bi == null && readError)
{
byte[] newImage = replaceHeader(img);
ByteArrayInputStream bai = new ByteArrayInputStream(newImage);
bi = ImageIO.read(bai);
}
// If there is a 'soft mask' or 'mask' image then we use that as a transparency mask.
return applyMasks(bi);
}
| public BufferedImage getRGBImage() throws IOException
{
if (image != null)
{
// use the cached image
return image;
}
BufferedImage bi = null;
boolean readError = false;
ByteArrayOutputStream os = new ByteArrayOutputStream();
removeAllFiltersButDCT(os);
os.close();
byte[] img = os.toByteArray();
PDColorSpace cs = getColorSpace();
try
{
if (cs instanceof PDDeviceCMYK
|| (cs instanceof PDICCBased && cs.getNumberOfComponents() == 4))
{
// JPEGs may contain CMYK, YCbCr or YCCK decoded image data
int transform = getApp14AdobeTransform(img);
// create BufferedImage based on the converted color values
if (transform == 0)
{
bi = convertCMYK2RGB(readImage(img), cs);
}
else if (transform == 1)
{
// TODO YCbCr
}
else if (transform == 2)
{
bi = convertYCCK2RGB(readImage(img));
}
}
else if (cs instanceof PDSeparation)
{
// create BufferedImage based on the converted color values
bi = processTintTransformation(readImage(img),
((PDSeparation)cs).getTintTransform(), cs.getJavaColorSpace());
}
else if (cs instanceof PDDeviceN)
{
// create BufferedImage based on the converted color values
bi = processTintTransformation(readImage(img),
((PDDeviceN)cs).getTintTransform(), cs.getJavaColorSpace());
}
else
{
ByteArrayInputStream bai = new ByteArrayInputStream(img);
bi = ImageIO.read(bai);
}
}
catch(IIOException exception)
{
readError = true;
}
// 2. try to read jpeg again. some jpegs have some strange header containing
// "Adobe " at some place. so just replace the header with a valid jpeg header.
// TODO : not sure if it works for all cases
if (bi == null && readError)
{
byte[] newImage = replaceHeader(img);
ByteArrayInputStream bai = new ByteArrayInputStream(newImage);
bi = ImageIO.read(bai);
}
// If there is a 'soft mask' or 'mask' image then we use that as a transparency mask.
image = applyMasks(bi);
return image;
}
|
diff --git a/JMapMatchingGUI/src/org/life/sl/routefinder/RouteFinder.java b/JMapMatchingGUI/src/org/life/sl/routefinder/RouteFinder.java
index 4c53e10..68289c4 100644
--- a/JMapMatchingGUI/src/org/life/sl/routefinder/RouteFinder.java
+++ b/JMapMatchingGUI/src/org/life/sl/routefinder/RouteFinder.java
@@ -1,624 +1,623 @@
package org.life.sl.routefinder;
/*
JMapMatcher
Copyright (c) 2011 Bernhard Barkow, Hans Skov-Petersen, Bernhard Snizek and Contributors
mail: [email protected]
web: http://www.bikeability.dk
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/>.
*/
import gnu.trove.TIntProcedure;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import java.util.Stack;
import org.apache.log4j.Logger;
import org.life.sl.graphs.PathSegmentGraph;
import org.life.sl.mapmatching.EdgeStatistics;
import org.life.sl.routefinder.Label;
import org.life.sl.utils.Timer;
//import org.life.sl.shapefilereader.ShapeFileReader;
//import cern.jet.random.Uniform;
import com.infomatiq.jsi.Rectangle;
import com.infomatiq.jsi.SpatialIndex;
import com.infomatiq.jsi.test.SpatialIndexFactory;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.operation.linemerge.LineMergeEdge;
//import com.vividsolutions.jts.operation.linemerge.LineMergeGraph;
import com.vividsolutions.jts.planargraph.DirectedEdge;
import com.vividsolutions.jts.planargraph.Edge;
import com.vividsolutions.jts.planargraph.Node;
/**
* A Routefinder. Finds all routes in a graph from origin to destination.
*
* @author Pimin Kostas Kefaloukos
* @author Bernhard Snizek
* @author Bernhard Barkow
*/
public class RouteFinder {
public static enum LabelTraversal {
None, ///< no special sorting
Shuffle, ///< shuffle labels before advancing in the iteration
ShuffleReset, ///< shuffle labels before advancing in the iteration, and reset the search after a route was found
BestFirst, ///< traverse label in reverse natural order (highest score first) - this should find the globally best route first
BestFirstDR, ///< like BestFirst, but including a Dead Reckoning fallback strategy
WorstFirst, ///< traverse label in natural order (highest score last)
BestLastEdge; ///< traverse label in reverse natural order, considering only the last edge
}
private int iShowProgressDetail = 2; ///< show a progress indicator while finding routes?
private LabelTraversal itLabelOrder = LabelTraversal.BestFirst;
private float kNearestEdgeDistance = 50.f; // the larger, the slower
// Initialization:
private RFParams rfParams;// = new Constraints();
private Node startNode = null; ///< route start node (Origin)
private Node endNode = null; ///< route end node (Destination)
private PathSegmentGraph network = null; ///< graph to search (all routes are in this network)
// articulation points identified in graph
// private Collection<Node> articulationPoints = new ArrayList<Node>();
// bridges identified in graph
// private Collection<Edge> bridges = new ArrayList<Edge>();
private long numLabels = 0; ///< number of labels (states) generated when running algorithm
int numExpansions = 0; ///< number of expansions that were performed
private long numLabels_rejected = 0; ///< number of labels (states) that have been rejected due to constraints
private long rejectedLabelsLimit = 0; ///< limit for number of labels (states) that have been rejected
private long numLabels_overlap = 0; ///< number of labels that have overlapping nodes
private long numLabels_psOverlap = 0;
private long maxLabels = 0; ///< maximum number of labels to compute
private double maxRuntime = 0; ///< maximum computation time per route, in seconds
private int nGenBack = 0;
private SpatialIndex si;
private HashMap<Integer, Edge> counter__edge;
private double gpsPathLength = 0.;
private double maxPathLength = 0.;
private double maxPSOverlap = 0.;
private EdgeStatistics edgeStatistics = null;
ArrayList<Label> results = null;
private Logger logger = Logger.getLogger("RouteFinder");
private MatchStats stats = new MatchStats();
/**
* create a Routefinder from a PathSegmentGraph, using default parameters
* @param network the input PathSegmentGraph
*/
public RouteFinder(PathSegmentGraph network) {
initDefaults(); // initialize algorithm parameters
this.network = network; // set network for further use
}
/**
* create a Routefinder from a PathSegmentGraph, using a defined parameter set
* @param network the input PathSegmentGraph
*/
public RouteFinder(PathSegmentGraph network, RFParams rfParams0) {
this(network, rfParams0, null);
}
/**
* create a Routefinder from a PathSegmentGraph, using a defined parameter set
* @param network the input PathSegmentGraph
*/
public RouteFinder(PathSegmentGraph network, RFParams rfParams0, ArrayList<Label> labels0) {
this(network);
rfParams = rfParams0;
if (labels0 != null && !labels0.isEmpty()) this.results = labels0;
else this.results = new ArrayList<Label>();
}
/**
* create default parameter set for the algorithm
*/
private void initDefaults() {
rfParams = new RFParams();
rfParams.setInt(RFParams.Type.MaximumNumberOfRoutes, 1000); ///< maximum number of routes to find (or 0 for infinite)
rfParams.setInt(RFParams.Type.BridgeOverlap, 1);
rfParams.setInt(RFParams.Type.EdgeOverlap, 1); ///< how often each edge may be used
// constraints.setInt(Constraints.Type.ArticulationPointOverlap, 2);
rfParams.setInt(RFParams.Type.NodeOverlap, 1); ///< how often each single node may be crossed
rfParams.setDouble(RFParams.Type.DistanceFactor, 1.1); ///< how much the route may deviate from the shortest possible
rfParams.setDouble(RFParams.Type.MinimumLength, 0.0); ///< minimum route length
rfParams.setDouble(RFParams.Type.MaximumLength, 1.e20); ///< maximum route length (quasi no limit here)
rfParams.setDouble(RFParams.Type.MaxPSOverlap, .8); ///< maximum allowed overlap between routes
rfParams.setDouble(RFParams.Type.NetworkBufferSize2, 0.); ///< initial buffer size in meters (!)
rfParams.setDouble(RFParams.Type.NetworkBufferSize, 100.); ///< buffer size in meters (!)
rfParams.setInt(RFParams.Type.RejectedLabelsLimit, 0); ///< limit for unsuccessful labels
rfParams.setInt(RFParams.Type.NoLabelsResizeNetwork, 0); ///< factor to resize network buffer if no routes were found
rfParams.set(RFParams.Type.LabelTraversal, LabelTraversal.BestFirst.toString()); ///< way of label traversal
rfParams.set(RFParams.Type.LabelTraversal2, LabelTraversal.ShuffleReset.toString()); ///< way of label traversal
rfParams.setInt(RFParams.Type.ShowProgressDetail, 2); ///< how often each edge may be used
}
/**
* external interface to set constraints for the algorithm
* @param ic HashMap of integer constraints
* @param dc HashMap of double constraints
*/
public void setConstraints(HashMap<RFParams.Type, Integer> ic, HashMap<RFParams.Type, Double> dc) {
rfParams.setConstraints(ic, dc);
}
public void setEdgeStatistics(EdgeStatistics eStat) {
edgeStatistics = eStat;
}
public double getMaxPathLength() {
return maxPathLength;
}
public double getGPSPathLength() {
return gpsPathLength;
}
/**
* Find all routes between startNode and endNode in the network this.network as list of labels;
* Label.getRouteAsEdges() can then be used to get a list of DirectedEdges that represent the route.
* @param startNode Routes should start in this node
* @param endNode Routes should end in this node
* @return A list of the routes found (represented by a list of Labels)
*/
public ArrayList<Label> findRoutes(Node startNode, Node endNode, double gpsPathLength0) {
//*** INITIALIZATION ***//
// check that startNode and endNode belong to same graph
if (network.findClosestNode(startNode.getCoordinate()) == null ||
network.findClosestNode(endNode.getCoordinate()) == null) {
logger.error("Origin and/or destination are not in network!"); // indicate failure
return new ArrayList<Label>();
}
if (rfParams.getBool(RFParams.Type.SwapOD)) {
this.startNode = endNode;
this.endNode = startNode;
} else {
this.startNode = startNode;
this.endNode = endNode;
}
this.gpsPathLength = gpsPathLength0;
numLabels = 0;
int numDeadEnds = 0;
numExpansions = 0;
this.itLabelOrder = LabelTraversal.valueOf(rfParams.getString(RFParams.Type.LabelTraversal));
this.nGenBack = rfParams.getInt(RFParams.Type.ShuffleResetNBack);
this.rejectedLabelsLimit = rfParams.getInt(RFParams.Type.RejectedLabelsLimit);
this.maxLabels = rfParams.getInt(RFParams.Type.MaxLabels);
this.maxRuntime = rfParams.getDouble(RFParams.Type.MaxRuntime);
this.iShowProgressDetail = rfParams.getInt(RFParams.Type.ShowProgressDetail);
// precalculate the minimum path length, for use as a constraint in label expansion:
maxPathLength = gpsPathLength * rfParams.getDouble(RFParams.Type.DistanceFactor);
maxPSOverlap = rfParams.getDouble(RFParams.Type.MaxPSOverlap);
// if there was a problem, use the given maximum length constraint:
double minDist = this.startNode.getCoordinate().distance(this.endNode.getCoordinate()); // compare to Euclidian distance
if (maxPathLength < minDist) {
System.err.println("Warning: invalid GPS data? referencePathLength < minDist (" + maxPathLength + " < " + minDist + ")");
maxPathLength = 0.;
}
// populate statistics
stats.status = MatchStats.Status.OK;
stats.sourceRouteID = network.getSourceRouteID();
stats.trackLength = gpsPathLength;
stats.ODDist = minDist;
stats.maxLength = maxPathLength;
stats.maxPSOverlap = maxPSOverlap;
stats.network_edges = network.getSize_Edges();
stats.network_nodes = network.getSize_Nodes();
stats.network_meanDegree = network.getMeanDegree();
stats.network_maxRoutesEst = Math.pow(stats.network_meanDegree-1., (double)stats.network_nodes/2.);
logger.info("Euclidian GPS Path length = " + gpsPathLength + ", path length limit = " + maxPathLength + "; O-D-Distance = " + minDist);
logger.info("Network size: " + stats.network_edges + " edges, " + stats.network_nodes + " nodes");
logger.info("Graph: max. route estimate: " + stats.network_maxRoutesEst + " / " + network.getNCombinations());
System.gc(); // can't hurt...
Stack<Label> stack = new Stack<Label>();
//*** START OF ALGORITHM ***//
Label rootLabel = new Label(this.startNode);
stack.push(rootLabel); // push start node to stack
// set up tree traversal strategy:
LabelTraversal itLabelOrder_orig = itLabelOrder;
int shuffleResetExtraRoutes = rfParams.getInt(RFParams.Type.ShuffleResetExtraRoutes);
if (itLabelOrder == LabelTraversal.ShuffleReset && shuffleResetExtraRoutes > 0) itLabelOrder = LabelTraversal.BestFirstDR;
logger.info("Initial tree traversal strategy: " + itLabelOrder.toString());
Label.LastEdgeComparator lastEdgeComp = new Label.LastEdgeComparator(itLabelOrder);
Timer timer = new Timer(); // timer to observe total runtime
timer.init();
stackLoop:
while (!stack.empty()) { // algorithm's main loop
// create label expansion (next generation):
Label expandingLabel = stack.pop(); // get last label from stack and expand it:
ArrayList<Label> expansion = expandLabel(expandingLabel); // calculate the expansion of the label (continuation from last node along all available edges)
if (expansion.size() > 0) {
if (itLabelOrder == LabelTraversal.Shuffle || itLabelOrder == LabelTraversal.ShuffleReset) Collections.shuffle(expansion); // randomize the order in which the labels are treated
// Attention: sorting the labels affects two parts:
// 1. the expansion array, which is processed linearly
// 2. the stack, which is effectively processed in reverse order!
/*else if (itLabelOrder == LabelTraversal.BestFirst) Collections.sort(expansion, lastEdgeComp); // order labels in ascending order (lowest score is treated first), so that the highest score ends up on top of the stack
else if (itLabelOrder == LabelTraversal.WorstFirst) Collections.sort(expansion, lastEdgeCompRev); // order labels in descending order (highest score first), so the best label ends up at the bottom of the stack
// Update: since the labels are identical up to the parent node, we compare only the last Edge
else if (itLabelOrder == LabelTraversal.BestLastEdge) Collections.sort(expansion, lastEdgeComp);*/
else Collections.sort(expansion, lastEdgeComp);
// test the newly created labels:
for (Label currentLabel : expansion) { // loop over all next-generation labels
numLabels++;
// is label a new valid route?
boolean bStoreRoute = isValidRoute(currentLabel);
if (bStoreRoute) { // valid route means: it ends in the destination node and fulfills the length constraints
- if (itLabelOrder == LabelTraversal.ShuffleReset) { // reset search:
- // check if this route already exists:
+ // for the ShuffleReset strategy: check if this route already exists:
+ if (itLabelOrder == LabelTraversal.ShuffleReset) {
for (Label l : results) {
- if (currentLabel.equals(l)) { bStoreRoute = false; break; }
+ if (currentLabel.equals(l)) { bStoreRoute = false; break; } // don't store the route if identical to any existing
}
- if (bStoreRoute) results.add(currentLabel);
- } //else without comparison - labels are all different due to search strategy
+ } // else perform no comparison,, since the labels are all different due to the search strategy
if (bStoreRoute) results.add(currentLabel); // add the valid route to list of routes
// check for shuffleResetExtraRoutes and switch to ShuffleReset mode, if applicable:
if (itLabelOrder != LabelTraversal.ShuffleReset && itLabelOrder_orig == LabelTraversal.ShuffleReset && results.size() >= shuffleResetExtraRoutes) {
itLabelOrder = itLabelOrder_orig;
logger.info("Switching tree traversal strategy: " + itLabelOrder.toString());
}
// in ShuffleReset mode, stop tree search and start again at the root node (Origin):
if (itLabelOrder == LabelTraversal.ShuffleReset) {
if (nGenBack == 0) { // remove all elements except for the root node
stack.removeAllElements(); // faster: remove all, ...
stack.push(rootLabel); // ... then return the root node to the stack
} else { // step back a certain number of generations
Label backLabel = currentLabel.getNthParent(nGenBack);
while (stack.size() > 0 && stack.pop() != backLabel) {
stack.push(backLabel); // put it back on stack and start from there
}
}
}
// check if maximum number of routes is reached
int nMaxRoutes = rfParams.getInt(RFParams.Type.MaximumNumberOfRoutes);
if (nMaxRoutes > 0 && results.size() >= nMaxRoutes) { // stop after the defined max. number of routes
logger.warn("["+network.getSourceRouteID()+"] Maximum number of routes reached (Constraint.MaximumNumberOfRoutes = " + rfParams.getInt(RFParams.Type.MaximumNumberOfRoutes) + ")");
stats.status = MatchStats.Status.MAXROUTES;
break stackLoop;
}
}
if (!bStoreRoute) { // check for maxLabels condition:
if (maxLabels > 0 && numLabels > maxLabels) {
logger.warn("["+network.getSourceRouteID()+"] Maximum number of labels reached (Constraint.MaxLabels = " + rfParams.getInt(RFParams.Type.MaxLabels) + ")");
stats.status = MatchStats.Status.MAXLABELS;
break stackLoop;
}
else stack.push(currentLabel); // destination is not reached yet: store the label on stack for the next iteration
}
}
if (iShowProgressDetail > 0) { // some log output?
if (iShowProgressDetail > 1 && numLabels%50000 == 0) System.out.print(".");
if (numLabels%5000000 == 0) {
System.out.printf("[%d] dead ends: %d - overlaps: %d - PSOverlap: %d - rejected: %d\n", network.getSourceRouteID(), numDeadEnds, numLabels_overlap, numLabels_psOverlap, numLabels_rejected);
String s = "lbl: " + numLabels;
if (iShowProgressDetail > 1) s += " - l: " + (expandingLabel.getLength() / gpsPathLength);
s += " - exp: " + numExpansions + " - res: " + results.size();
System.out.println(s);
}
long freeMem = Runtime.getRuntime().freeMemory();
if (numLabels%500000 == 0 && freeMem / (double)Runtime.getRuntime().maxMemory() < .1) {
System.out.print("Mem: " + freeMem/(1024*1024) + "MB");
System.gc();
System.out.println(" / " + Runtime.getRuntime().freeMemory()/(1024*1024) + "MB");
// if there is really no memory left, just stop:
if (Runtime.getRuntime().freeMemory() < 250000000) { // 10MB
logger.error("Stopping due to memory overload!");
stats.status = MatchStats.Status.MEMORY;
break stackLoop;
}
}
}
// check for rejectedLabelsLimit-constraint:
if (rejectedLabelsLimit > 0 && numLabels_rejected > 0 && numLabels_rejected%rejectedLabelsLimit == 0 && results.size() == 0) {
logger.warn("Reached rejectedLabelsLimit - increase network buffer size?");
}
} else { // "dead end" - this label is invalid
numDeadEnds++;
expandingLabel = null;
}
// check the runtime constraint (top priority):
if (maxRuntime > 0 && timer.getRunTime(false) > maxRuntime) {
logger.warn("Reached maximum runtime of "+maxRuntime+" s");
break stackLoop;
}
}
// some statistics on the computation:
System.out.printf("\nlabels analyzed:\t%14d\nvalid routes:\t\t%14d\ndead end-labels:\t%14d\t(%2.2f%%)\nlabels rejected:\t%14d\t(%2.2f%%)\nnodes in network:\t%14d\n\n",
numLabels, results.size(), numDeadEnds, (100.*numDeadEnds/numLabels), numLabels_rejected, (100.*numLabels_rejected/numLabels),
network.getNodes().size());
// populate statistics container:
stats.nLabels = numLabels;
stats.nExpansions = numExpansions;
stats.nRoutes = results.size();
stats.nRejected_length = numLabels_rejected - numLabels_overlap;
stats.nRejected_overlap = numLabels_overlap;
stats.nRejected_psOverlap = numLabels_psOverlap;
stats.nDeadEnds = numDeadEnds;
return results;
}
/**
* Checks if the labeled route is valid, i.e. if it ends in the end node and fulfills the length constraints
* @param label the label to check
* @return true if the route is valid
*/
private boolean isValidRoute(Label label) {
boolean b = (
label.getNode() == this.endNode &&
label.getLength() >= rfParams.getDouble(RFParams.Type.MinimumLength) &&
label.getLength() <= rfParams.getDouble(RFParams.Type.MaximumLength)
);
// check for overlap constraint:
if (b && maxPSOverlap > 0) {
b = (label.getOverlapWithSet(results, false, maxPSOverlap) <= maxPSOverlap); // TODO: better control of useDir!!
if (!b) numLabels_psOverlap++;
}
return b;
}
/**
* create the expansion from a label, i.e. the list of routes leaving from the current node (next generation labels);
* ignore expansion along the backEdge! (BB)
* @param parentLabel the label where from to expand
* @return an ArrayList containing the valid labels found for the next generation
*/
private ArrayList<Label> expandLabel(Label parentLabel) {
ArrayList<Label> expansion = new ArrayList<Label>();
Label newLabel;
// if ((int)(parentLabel.getNode().getCoordinate().x/10) == 72354) {
// System.out.println("I'm here!");
// }
//double maxLen = rfParams.getDouble(RFParams.Type.MaximumLength); // use exact estimate for maximum path length
double parentLength = parentLabel.getLength();
/////////////////////////////////////
// MAKE LABELS FROM NEIGHBORS
/////////////////////////////////////
@SuppressWarnings("unchecked")
List<Label> labels = (List<Label>)parentLabel.getNode().getOutEdges().getEdges();
if (labels.size() > 1) numExpansions++; // size() == 1 means that the only edge is the backedge
for(Object obj : labels ) { // loop over all edges leaving from the current node
DirectedEdge currentEdge = (DirectedEdge) obj;
// check if the current edge is identical to the parent node, where we just came from:
DirectedEdge pe = parentLabel.getBackEdge();
if (pe != null && currentEdge.getEdge() == pe.getEdge()) continue; // going back the same edge where we come from is prohibited!
double lastEdgeLength = ((LineMergeEdge)currentEdge.getEdge()).getLine().getLength(); // length of new last edge
double length = parentLength + lastEdgeLength; // new total length
newLabel = new Label(parentLabel, currentEdge.getToNode(), currentEdge, length, lastEdgeLength);
numLabels_rejected++; // increment by default, decrement again if label is not rejected
/////////////////////////////////////
// EDGE CONSTRAINTS
/////////////////////////////////////
// int edgeOccurances = newLabel.getOccurancesOfEdge(currentEdge);
// // bridge has been visited the maximum number of times already?
// if(this.bridges.contains(currentEdge) && (edgeOccurances > getIntegerConstraint(Constraint.BridgeOverlap))) {
// continue;
// }
// // edge has been visited the maximum number of times already?
// if(!this.bridges.contains(currentEdge) && edgeOccurances > getIntegerConstraint(Constraint.EdgeOverlap)) {
// continue;
// }
/////////////////////////////////////
// PATH-LENGTH CONSTRAINTS
/////////////////////////////////////
// 1. path length exceeded maxLength constraint with this edge?
//if (checkPathLength(length, maxLen, "length")) continue; // don't store the label at all, because the route is too long anyway
if (maxPathLength > 0.) { // only if we have a valid path length
// 2. Length + Euclidian distance to endNode greater than referencePathLength? (can't reach endNode)
// (Using the Euclidian distance is a quick worst-case check; using the shortest path is exact, but slower.)
if (checkPathLength(length + newLabel.getDistanceTo(endNode), maxPathLength, "eucl.")) continue;
/*// 3. try with the shortest realistic path: AStar
// TODO: get this value from database, after it has been precalculated and stored in a table
// TODO: check how this performs - it might be faster to calculate more labels instead of calculating the path distance every time!!
if (alwaysUseShortestPath) {
distanceToEndNode = shortestDistanceBetweenNodes(newLabel.getNode(), endNode);
if (checkPathLength(length + distanceToEndNode, referencePathLength, "AStar")) continue;
}*/
}
/////////////////////////////////////
// NODE CONSTRAINTS
/////////////////////////////////////
// rules for node occurrences:
// 1) the start-node is counted except in the beginning of the route
// 2) the end-node is counted except if at the end of the route
// 3) all other occurrences are counted
// get current total overlap for node
int nodeOccurrences = newLabel.getOccurrencesOfNode(newLabel.getNode());
// adjust the number of time the node occours, according to cases above
if (newLabel.getNode() == startNode) nodeOccurrences--;
if (newLabel.getNode() == endNode) nodeOccurrences--;
// Now, check if a constraint is broken:
// if(this.articulationPoints.contains(newLabel.getNode())) { // node is an articulation point, so we check for a special max. overlap:
// if (nodeOccurances > getIntegerConstraint(Constraint.ArticulationPointOverlap)) continue;
// } else { // node is not an articulation point, so we have to check for max. overlap:
if (nodeOccurrences > rfParams.getInt(RFParams.Type.NodeOverlap)) {
logger.trace("Constraint reached: NodeOccurrences = " + nodeOccurrences);
numLabels_overlap++;
continue; // don't consider this label
}
// }
// no constraints broken:
newLabel.calcScore(edgeStatistics); // shall we do this here and sort the list in findRoutes(), or shall we rather shuffle?
expansion.add(newLabel); // store new label (i.e., it is a valid expansion)
numLabels++;
numLabels_rejected--; // inelegantly reset to previous state
}
return expansion;
}
/**
* check if the given minimum path length exceeds the limit, and write out a corresponding log message
* @param len minimum (or real) path length
* @param maxLen path length limit
* @param msg additional description for log message
* @return true if the path is too long
*/
private boolean checkPathLength(double len, double maxLen, String msg) {
boolean b = (len > maxLen);
if (b) {
logger.trace("Constraint reached: distance too large (" + msg + "). " + len + " > " + maxLen);
}
return b;
}
/**
* @return Get the number of Labels generated when finding routes during the last call to findRoutes()
*/
public long getNumLabels() {
return numLabels;
}
public MatchStats getStats() { return stats; }
/**
* ??
* set up SpatialIndex, which is then used to calculate nearest edges (?)
*/
public void calculateNearest() {
Properties p = new Properties();
p.setProperty("MinNodeEntries", "1");
p.setProperty("MaxNodeEntries", "10");
si = SpatialIndexFactory.newInstance("rtree.RTree", p);
counter__edge = new HashMap<Integer, Edge>();
int counter = 0;
// loop over all edges in the network
for (Edge edge : network.getEdges()) {
counter++;
counter__edge.put(counter, edge); // store edges in the hash map
LineMergeEdge de = (LineMergeEdge)edge;
Geometry env = de.getLine().getBoundary();
// (minx, miny), (maxx, miny), (maxx, maxy), (minx, maxy), (minx, miny).
if (env.getNumGeometries() > 0) {
Point p1 = (Point) env.getGeometryN(0);
Point p2 = (Point) env.getGeometryN(1);
si.add(new Rectangle((float) p1.getX(),
(float) p1.getY(),
(float) p2.getX(),
(float) p2.getY()),
counter);
}
}
}
/**
* Find the edge nearest to a given point
* @param p point for which to calculate the nearest edge
* @return the nearest edge to the point
*/
public Edge getNearestEdge(Point p) {
com.infomatiq.jsi.Point pp = new com.infomatiq.jsi.Point((float) p.getX(), (float) p.getY());
ReturnArray r = new ReturnArray();
this.si.nearestNUnsorted(pp, r, 8, kNearestEdgeDistance); // TODO: decide how to choose value for furthestDistance? 10 meters is just a guess.
double dMin = Double.MAX_VALUE, d = 0;
Edge e0 = null;
for (Integer i : r.getResult()) {
Edge e = (Edge) this.counter__edge.get(i);
d = p.distance(((LineMergeEdge)e).getLine());
if (d < dMin) {
dMin = d;
e0 = e;
}
}
return e0;
}
}
/**
* Result container; looks like a bit of overkill, but is required by SpatialIndex...
*/
class Return implements TIntProcedure {
private int result;
public boolean execute(int value) {
this.result = value;
return true;
}
int getResult() {
return this.result;
}
}
/**
* Result container; looks like a bit of overkill, but is required by SpatialIndex...
*/
class ReturnArray implements TIntProcedure {
private ArrayList<Integer> result = new ArrayList<Integer>();
public boolean execute(int value) {
this.result.add(value);
return true;
}
ArrayList<Integer> getResult() {
return this.result;
}
}
| false | true | public ArrayList<Label> findRoutes(Node startNode, Node endNode, double gpsPathLength0) {
//*** INITIALIZATION ***//
// check that startNode and endNode belong to same graph
if (network.findClosestNode(startNode.getCoordinate()) == null ||
network.findClosestNode(endNode.getCoordinate()) == null) {
logger.error("Origin and/or destination are not in network!"); // indicate failure
return new ArrayList<Label>();
}
if (rfParams.getBool(RFParams.Type.SwapOD)) {
this.startNode = endNode;
this.endNode = startNode;
} else {
this.startNode = startNode;
this.endNode = endNode;
}
this.gpsPathLength = gpsPathLength0;
numLabels = 0;
int numDeadEnds = 0;
numExpansions = 0;
this.itLabelOrder = LabelTraversal.valueOf(rfParams.getString(RFParams.Type.LabelTraversal));
this.nGenBack = rfParams.getInt(RFParams.Type.ShuffleResetNBack);
this.rejectedLabelsLimit = rfParams.getInt(RFParams.Type.RejectedLabelsLimit);
this.maxLabels = rfParams.getInt(RFParams.Type.MaxLabels);
this.maxRuntime = rfParams.getDouble(RFParams.Type.MaxRuntime);
this.iShowProgressDetail = rfParams.getInt(RFParams.Type.ShowProgressDetail);
// precalculate the minimum path length, for use as a constraint in label expansion:
maxPathLength = gpsPathLength * rfParams.getDouble(RFParams.Type.DistanceFactor);
maxPSOverlap = rfParams.getDouble(RFParams.Type.MaxPSOverlap);
// if there was a problem, use the given maximum length constraint:
double minDist = this.startNode.getCoordinate().distance(this.endNode.getCoordinate()); // compare to Euclidian distance
if (maxPathLength < minDist) {
System.err.println("Warning: invalid GPS data? referencePathLength < minDist (" + maxPathLength + " < " + minDist + ")");
maxPathLength = 0.;
}
// populate statistics
stats.status = MatchStats.Status.OK;
stats.sourceRouteID = network.getSourceRouteID();
stats.trackLength = gpsPathLength;
stats.ODDist = minDist;
stats.maxLength = maxPathLength;
stats.maxPSOverlap = maxPSOverlap;
stats.network_edges = network.getSize_Edges();
stats.network_nodes = network.getSize_Nodes();
stats.network_meanDegree = network.getMeanDegree();
stats.network_maxRoutesEst = Math.pow(stats.network_meanDegree-1., (double)stats.network_nodes/2.);
logger.info("Euclidian GPS Path length = " + gpsPathLength + ", path length limit = " + maxPathLength + "; O-D-Distance = " + minDist);
logger.info("Network size: " + stats.network_edges + " edges, " + stats.network_nodes + " nodes");
logger.info("Graph: max. route estimate: " + stats.network_maxRoutesEst + " / " + network.getNCombinations());
System.gc(); // can't hurt...
Stack<Label> stack = new Stack<Label>();
//*** START OF ALGORITHM ***//
Label rootLabel = new Label(this.startNode);
stack.push(rootLabel); // push start node to stack
// set up tree traversal strategy:
LabelTraversal itLabelOrder_orig = itLabelOrder;
int shuffleResetExtraRoutes = rfParams.getInt(RFParams.Type.ShuffleResetExtraRoutes);
if (itLabelOrder == LabelTraversal.ShuffleReset && shuffleResetExtraRoutes > 0) itLabelOrder = LabelTraversal.BestFirstDR;
logger.info("Initial tree traversal strategy: " + itLabelOrder.toString());
Label.LastEdgeComparator lastEdgeComp = new Label.LastEdgeComparator(itLabelOrder);
Timer timer = new Timer(); // timer to observe total runtime
timer.init();
stackLoop:
while (!stack.empty()) { // algorithm's main loop
// create label expansion (next generation):
Label expandingLabel = stack.pop(); // get last label from stack and expand it:
ArrayList<Label> expansion = expandLabel(expandingLabel); // calculate the expansion of the label (continuation from last node along all available edges)
if (expansion.size() > 0) {
if (itLabelOrder == LabelTraversal.Shuffle || itLabelOrder == LabelTraversal.ShuffleReset) Collections.shuffle(expansion); // randomize the order in which the labels are treated
// Attention: sorting the labels affects two parts:
// 1. the expansion array, which is processed linearly
// 2. the stack, which is effectively processed in reverse order!
/*else if (itLabelOrder == LabelTraversal.BestFirst) Collections.sort(expansion, lastEdgeComp); // order labels in ascending order (lowest score is treated first), so that the highest score ends up on top of the stack
else if (itLabelOrder == LabelTraversal.WorstFirst) Collections.sort(expansion, lastEdgeCompRev); // order labels in descending order (highest score first), so the best label ends up at the bottom of the stack
// Update: since the labels are identical up to the parent node, we compare only the last Edge
else if (itLabelOrder == LabelTraversal.BestLastEdge) Collections.sort(expansion, lastEdgeComp);*/
else Collections.sort(expansion, lastEdgeComp);
// test the newly created labels:
for (Label currentLabel : expansion) { // loop over all next-generation labels
numLabels++;
// is label a new valid route?
boolean bStoreRoute = isValidRoute(currentLabel);
if (bStoreRoute) { // valid route means: it ends in the destination node and fulfills the length constraints
if (itLabelOrder == LabelTraversal.ShuffleReset) { // reset search:
// check if this route already exists:
for (Label l : results) {
if (currentLabel.equals(l)) { bStoreRoute = false; break; }
}
if (bStoreRoute) results.add(currentLabel);
} //else without comparison - labels are all different due to search strategy
if (bStoreRoute) results.add(currentLabel); // add the valid route to list of routes
// check for shuffleResetExtraRoutes and switch to ShuffleReset mode, if applicable:
if (itLabelOrder != LabelTraversal.ShuffleReset && itLabelOrder_orig == LabelTraversal.ShuffleReset && results.size() >= shuffleResetExtraRoutes) {
itLabelOrder = itLabelOrder_orig;
logger.info("Switching tree traversal strategy: " + itLabelOrder.toString());
}
// in ShuffleReset mode, stop tree search and start again at the root node (Origin):
if (itLabelOrder == LabelTraversal.ShuffleReset) {
if (nGenBack == 0) { // remove all elements except for the root node
stack.removeAllElements(); // faster: remove all, ...
stack.push(rootLabel); // ... then return the root node to the stack
} else { // step back a certain number of generations
Label backLabel = currentLabel.getNthParent(nGenBack);
while (stack.size() > 0 && stack.pop() != backLabel) {
stack.push(backLabel); // put it back on stack and start from there
}
}
}
// check if maximum number of routes is reached
int nMaxRoutes = rfParams.getInt(RFParams.Type.MaximumNumberOfRoutes);
if (nMaxRoutes > 0 && results.size() >= nMaxRoutes) { // stop after the defined max. number of routes
logger.warn("["+network.getSourceRouteID()+"] Maximum number of routes reached (Constraint.MaximumNumberOfRoutes = " + rfParams.getInt(RFParams.Type.MaximumNumberOfRoutes) + ")");
stats.status = MatchStats.Status.MAXROUTES;
break stackLoop;
}
}
if (!bStoreRoute) { // check for maxLabels condition:
if (maxLabels > 0 && numLabels > maxLabels) {
logger.warn("["+network.getSourceRouteID()+"] Maximum number of labels reached (Constraint.MaxLabels = " + rfParams.getInt(RFParams.Type.MaxLabels) + ")");
stats.status = MatchStats.Status.MAXLABELS;
break stackLoop;
}
else stack.push(currentLabel); // destination is not reached yet: store the label on stack for the next iteration
}
}
if (iShowProgressDetail > 0) { // some log output?
if (iShowProgressDetail > 1 && numLabels%50000 == 0) System.out.print(".");
if (numLabels%5000000 == 0) {
System.out.printf("[%d] dead ends: %d - overlaps: %d - PSOverlap: %d - rejected: %d\n", network.getSourceRouteID(), numDeadEnds, numLabels_overlap, numLabels_psOverlap, numLabels_rejected);
String s = "lbl: " + numLabels;
if (iShowProgressDetail > 1) s += " - l: " + (expandingLabel.getLength() / gpsPathLength);
s += " - exp: " + numExpansions + " - res: " + results.size();
System.out.println(s);
}
long freeMem = Runtime.getRuntime().freeMemory();
if (numLabels%500000 == 0 && freeMem / (double)Runtime.getRuntime().maxMemory() < .1) {
System.out.print("Mem: " + freeMem/(1024*1024) + "MB");
System.gc();
System.out.println(" / " + Runtime.getRuntime().freeMemory()/(1024*1024) + "MB");
// if there is really no memory left, just stop:
if (Runtime.getRuntime().freeMemory() < 250000000) { // 10MB
logger.error("Stopping due to memory overload!");
stats.status = MatchStats.Status.MEMORY;
break stackLoop;
}
}
}
// check for rejectedLabelsLimit-constraint:
if (rejectedLabelsLimit > 0 && numLabels_rejected > 0 && numLabels_rejected%rejectedLabelsLimit == 0 && results.size() == 0) {
logger.warn("Reached rejectedLabelsLimit - increase network buffer size?");
}
} else { // "dead end" - this label is invalid
numDeadEnds++;
expandingLabel = null;
}
// check the runtime constraint (top priority):
if (maxRuntime > 0 && timer.getRunTime(false) > maxRuntime) {
logger.warn("Reached maximum runtime of "+maxRuntime+" s");
break stackLoop;
}
}
// some statistics on the computation:
System.out.printf("\nlabels analyzed:\t%14d\nvalid routes:\t\t%14d\ndead end-labels:\t%14d\t(%2.2f%%)\nlabels rejected:\t%14d\t(%2.2f%%)\nnodes in network:\t%14d\n\n",
numLabels, results.size(), numDeadEnds, (100.*numDeadEnds/numLabels), numLabels_rejected, (100.*numLabels_rejected/numLabels),
network.getNodes().size());
// populate statistics container:
stats.nLabels = numLabels;
stats.nExpansions = numExpansions;
stats.nRoutes = results.size();
stats.nRejected_length = numLabels_rejected - numLabels_overlap;
stats.nRejected_overlap = numLabels_overlap;
stats.nRejected_psOverlap = numLabels_psOverlap;
stats.nDeadEnds = numDeadEnds;
return results;
}
| public ArrayList<Label> findRoutes(Node startNode, Node endNode, double gpsPathLength0) {
//*** INITIALIZATION ***//
// check that startNode and endNode belong to same graph
if (network.findClosestNode(startNode.getCoordinate()) == null ||
network.findClosestNode(endNode.getCoordinate()) == null) {
logger.error("Origin and/or destination are not in network!"); // indicate failure
return new ArrayList<Label>();
}
if (rfParams.getBool(RFParams.Type.SwapOD)) {
this.startNode = endNode;
this.endNode = startNode;
} else {
this.startNode = startNode;
this.endNode = endNode;
}
this.gpsPathLength = gpsPathLength0;
numLabels = 0;
int numDeadEnds = 0;
numExpansions = 0;
this.itLabelOrder = LabelTraversal.valueOf(rfParams.getString(RFParams.Type.LabelTraversal));
this.nGenBack = rfParams.getInt(RFParams.Type.ShuffleResetNBack);
this.rejectedLabelsLimit = rfParams.getInt(RFParams.Type.RejectedLabelsLimit);
this.maxLabels = rfParams.getInt(RFParams.Type.MaxLabels);
this.maxRuntime = rfParams.getDouble(RFParams.Type.MaxRuntime);
this.iShowProgressDetail = rfParams.getInt(RFParams.Type.ShowProgressDetail);
// precalculate the minimum path length, for use as a constraint in label expansion:
maxPathLength = gpsPathLength * rfParams.getDouble(RFParams.Type.DistanceFactor);
maxPSOverlap = rfParams.getDouble(RFParams.Type.MaxPSOverlap);
// if there was a problem, use the given maximum length constraint:
double minDist = this.startNode.getCoordinate().distance(this.endNode.getCoordinate()); // compare to Euclidian distance
if (maxPathLength < minDist) {
System.err.println("Warning: invalid GPS data? referencePathLength < minDist (" + maxPathLength + " < " + minDist + ")");
maxPathLength = 0.;
}
// populate statistics
stats.status = MatchStats.Status.OK;
stats.sourceRouteID = network.getSourceRouteID();
stats.trackLength = gpsPathLength;
stats.ODDist = minDist;
stats.maxLength = maxPathLength;
stats.maxPSOverlap = maxPSOverlap;
stats.network_edges = network.getSize_Edges();
stats.network_nodes = network.getSize_Nodes();
stats.network_meanDegree = network.getMeanDegree();
stats.network_maxRoutesEst = Math.pow(stats.network_meanDegree-1., (double)stats.network_nodes/2.);
logger.info("Euclidian GPS Path length = " + gpsPathLength + ", path length limit = " + maxPathLength + "; O-D-Distance = " + minDist);
logger.info("Network size: " + stats.network_edges + " edges, " + stats.network_nodes + " nodes");
logger.info("Graph: max. route estimate: " + stats.network_maxRoutesEst + " / " + network.getNCombinations());
System.gc(); // can't hurt...
Stack<Label> stack = new Stack<Label>();
//*** START OF ALGORITHM ***//
Label rootLabel = new Label(this.startNode);
stack.push(rootLabel); // push start node to stack
// set up tree traversal strategy:
LabelTraversal itLabelOrder_orig = itLabelOrder;
int shuffleResetExtraRoutes = rfParams.getInt(RFParams.Type.ShuffleResetExtraRoutes);
if (itLabelOrder == LabelTraversal.ShuffleReset && shuffleResetExtraRoutes > 0) itLabelOrder = LabelTraversal.BestFirstDR;
logger.info("Initial tree traversal strategy: " + itLabelOrder.toString());
Label.LastEdgeComparator lastEdgeComp = new Label.LastEdgeComparator(itLabelOrder);
Timer timer = new Timer(); // timer to observe total runtime
timer.init();
stackLoop:
while (!stack.empty()) { // algorithm's main loop
// create label expansion (next generation):
Label expandingLabel = stack.pop(); // get last label from stack and expand it:
ArrayList<Label> expansion = expandLabel(expandingLabel); // calculate the expansion of the label (continuation from last node along all available edges)
if (expansion.size() > 0) {
if (itLabelOrder == LabelTraversal.Shuffle || itLabelOrder == LabelTraversal.ShuffleReset) Collections.shuffle(expansion); // randomize the order in which the labels are treated
// Attention: sorting the labels affects two parts:
// 1. the expansion array, which is processed linearly
// 2. the stack, which is effectively processed in reverse order!
/*else if (itLabelOrder == LabelTraversal.BestFirst) Collections.sort(expansion, lastEdgeComp); // order labels in ascending order (lowest score is treated first), so that the highest score ends up on top of the stack
else if (itLabelOrder == LabelTraversal.WorstFirst) Collections.sort(expansion, lastEdgeCompRev); // order labels in descending order (highest score first), so the best label ends up at the bottom of the stack
// Update: since the labels are identical up to the parent node, we compare only the last Edge
else if (itLabelOrder == LabelTraversal.BestLastEdge) Collections.sort(expansion, lastEdgeComp);*/
else Collections.sort(expansion, lastEdgeComp);
// test the newly created labels:
for (Label currentLabel : expansion) { // loop over all next-generation labels
numLabels++;
// is label a new valid route?
boolean bStoreRoute = isValidRoute(currentLabel);
if (bStoreRoute) { // valid route means: it ends in the destination node and fulfills the length constraints
// for the ShuffleReset strategy: check if this route already exists:
if (itLabelOrder == LabelTraversal.ShuffleReset) {
for (Label l : results) {
if (currentLabel.equals(l)) { bStoreRoute = false; break; } // don't store the route if identical to any existing
}
} // else perform no comparison,, since the labels are all different due to the search strategy
if (bStoreRoute) results.add(currentLabel); // add the valid route to list of routes
// check for shuffleResetExtraRoutes and switch to ShuffleReset mode, if applicable:
if (itLabelOrder != LabelTraversal.ShuffleReset && itLabelOrder_orig == LabelTraversal.ShuffleReset && results.size() >= shuffleResetExtraRoutes) {
itLabelOrder = itLabelOrder_orig;
logger.info("Switching tree traversal strategy: " + itLabelOrder.toString());
}
// in ShuffleReset mode, stop tree search and start again at the root node (Origin):
if (itLabelOrder == LabelTraversal.ShuffleReset) {
if (nGenBack == 0) { // remove all elements except for the root node
stack.removeAllElements(); // faster: remove all, ...
stack.push(rootLabel); // ... then return the root node to the stack
} else { // step back a certain number of generations
Label backLabel = currentLabel.getNthParent(nGenBack);
while (stack.size() > 0 && stack.pop() != backLabel) {
stack.push(backLabel); // put it back on stack and start from there
}
}
}
// check if maximum number of routes is reached
int nMaxRoutes = rfParams.getInt(RFParams.Type.MaximumNumberOfRoutes);
if (nMaxRoutes > 0 && results.size() >= nMaxRoutes) { // stop after the defined max. number of routes
logger.warn("["+network.getSourceRouteID()+"] Maximum number of routes reached (Constraint.MaximumNumberOfRoutes = " + rfParams.getInt(RFParams.Type.MaximumNumberOfRoutes) + ")");
stats.status = MatchStats.Status.MAXROUTES;
break stackLoop;
}
}
if (!bStoreRoute) { // check for maxLabels condition:
if (maxLabels > 0 && numLabels > maxLabels) {
logger.warn("["+network.getSourceRouteID()+"] Maximum number of labels reached (Constraint.MaxLabels = " + rfParams.getInt(RFParams.Type.MaxLabels) + ")");
stats.status = MatchStats.Status.MAXLABELS;
break stackLoop;
}
else stack.push(currentLabel); // destination is not reached yet: store the label on stack for the next iteration
}
}
if (iShowProgressDetail > 0) { // some log output?
if (iShowProgressDetail > 1 && numLabels%50000 == 0) System.out.print(".");
if (numLabels%5000000 == 0) {
System.out.printf("[%d] dead ends: %d - overlaps: %d - PSOverlap: %d - rejected: %d\n", network.getSourceRouteID(), numDeadEnds, numLabels_overlap, numLabels_psOverlap, numLabels_rejected);
String s = "lbl: " + numLabels;
if (iShowProgressDetail > 1) s += " - l: " + (expandingLabel.getLength() / gpsPathLength);
s += " - exp: " + numExpansions + " - res: " + results.size();
System.out.println(s);
}
long freeMem = Runtime.getRuntime().freeMemory();
if (numLabels%500000 == 0 && freeMem / (double)Runtime.getRuntime().maxMemory() < .1) {
System.out.print("Mem: " + freeMem/(1024*1024) + "MB");
System.gc();
System.out.println(" / " + Runtime.getRuntime().freeMemory()/(1024*1024) + "MB");
// if there is really no memory left, just stop:
if (Runtime.getRuntime().freeMemory() < 250000000) { // 10MB
logger.error("Stopping due to memory overload!");
stats.status = MatchStats.Status.MEMORY;
break stackLoop;
}
}
}
// check for rejectedLabelsLimit-constraint:
if (rejectedLabelsLimit > 0 && numLabels_rejected > 0 && numLabels_rejected%rejectedLabelsLimit == 0 && results.size() == 0) {
logger.warn("Reached rejectedLabelsLimit - increase network buffer size?");
}
} else { // "dead end" - this label is invalid
numDeadEnds++;
expandingLabel = null;
}
// check the runtime constraint (top priority):
if (maxRuntime > 0 && timer.getRunTime(false) > maxRuntime) {
logger.warn("Reached maximum runtime of "+maxRuntime+" s");
break stackLoop;
}
}
// some statistics on the computation:
System.out.printf("\nlabels analyzed:\t%14d\nvalid routes:\t\t%14d\ndead end-labels:\t%14d\t(%2.2f%%)\nlabels rejected:\t%14d\t(%2.2f%%)\nnodes in network:\t%14d\n\n",
numLabels, results.size(), numDeadEnds, (100.*numDeadEnds/numLabels), numLabels_rejected, (100.*numLabels_rejected/numLabels),
network.getNodes().size());
// populate statistics container:
stats.nLabels = numLabels;
stats.nExpansions = numExpansions;
stats.nRoutes = results.size();
stats.nRejected_length = numLabels_rejected - numLabels_overlap;
stats.nRejected_overlap = numLabels_overlap;
stats.nRejected_psOverlap = numLabels_psOverlap;
stats.nDeadEnds = numDeadEnds;
return results;
}
|
diff --git a/spring-security-oauth/src/test/java/org/springframework/security/oauth/consumer/TestOAuthConsumerContextFilter.java b/spring-security-oauth/src/test/java/org/springframework/security/oauth/consumer/TestOAuthConsumerContextFilter.java
index 010d185d..df68e75f 100644
--- a/spring-security-oauth/src/test/java/org/springframework/security/oauth/consumer/TestOAuthConsumerContextFilter.java
+++ b/spring-security-oauth/src/test/java/org/springframework/security/oauth/consumer/TestOAuthConsumerContextFilter.java
@@ -1,116 +1,117 @@
package org.springframework.security.oauth.consumer;
import static org.easymock.EasyMock.*;
import junit.framework.TestCase;
import org.springframework.security.oauth.common.OAuthProviderParameter;
import org.springframework.security.oauth.consumer.rememberme.NoOpOAuthRememberMeServices;
import org.springframework.security.oauth.consumer.rememberme.OAuthRememberMeServices;
import org.springframework.security.oauth.consumer.token.OAuthConsumerToken;
import org.springframework.security.oauth.consumer.token.OAuthConsumerTokenServices;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author Ryan Heaton
*/
public class TestOAuthConsumerContextFilter extends TestCase {
/**
* tests getting the user authorization redirect URL.
*/
public void testGetUserAuthorizationRedirectURL() throws Exception {
ProtectedResourceDetails details = createMock(ProtectedResourceDetails.class);
OAuthConsumerContextFilter filter = new OAuthConsumerContextFilter();
OAuthConsumerToken token = new OAuthConsumerToken();
token.setResourceId("resourceId");
token.setValue("mytoken");
expect(details.getUserAuthorizationURL()).andReturn("http://user-auth/context?with=some&queryParams");
expect(details.isUse10a()).andReturn(false);
replay(details);
assertEquals("http://user-auth/context?with=some&queryParams&oauth_token=mytoken&oauth_callback=urn%3A%2F%2Fcallback%3Fwith%3Dsome%26query%3Dparams",
filter.getUserAuthorizationRedirectURL(details, token, "urn://callback?with=some&query=params"));
verify(details);
reset(details);
expect(details.getUserAuthorizationURL()).andReturn("http://user-auth/context?with=some&queryParams");
expect(details.isUse10a()).andReturn(true);
replay(details);
assertEquals("http://user-auth/context?with=some&queryParams&oauth_token=mytoken",
filter.getUserAuthorizationRedirectURL(details, token, "urn://callback?with=some&query=params"));
verify(details);
reset(details);
}
/**
* tests the filter.
*/
public void testDoFilter() throws Exception {
HttpServletRequest request = createMock(HttpServletRequest.class);
HttpServletResponse response = createMock(HttpServletResponse.class);
FilterChain filterChain=createMock(FilterChain.class);
final OAuthConsumerTokenServices tokenServices = createMock(OAuthConsumerTokenServices.class);
final OAuthConsumerSupport support = createMock(OAuthConsumerSupport.class);
final OAuthRememberMeServices rememberMeServices = new NoOpOAuthRememberMeServices();
final BaseProtectedResourceDetails resource = new BaseProtectedResourceDetails();
resource.setId("dep1");
OAuthConsumerContextFilter filter = new OAuthConsumerContextFilter() {
@Override
protected String getCallbackURL(HttpServletRequest request) {
return "urn:callback";
}
@Override
protected String getUserAuthorizationRedirectURL(ProtectedResourceDetails details, OAuthConsumerToken requestToken, String callbackURL) {
return callbackURL + "&" + requestToken.getResourceId();
}
};
filter.setTokenServices(tokenServices);
filter.setConsumerSupport(support);
filter.setRememberMeServices(rememberMeServices);
request.setAttribute((String) anyObject(), anyObject());
filterChain.doFilter(request, response);
expectLastCall().andThrow(new AccessTokenRequiredException(resource));
expect(tokenServices.getToken("dep1")).andReturn(null);
+ expect(request.getParameter("oauth_verifier")).andReturn(null);
expect(response.encodeRedirectURL("urn:callback")).andReturn("urn:callback?query");
OAuthConsumerToken token = new OAuthConsumerToken();
token.setAccessToken(false);
token.setResourceId(resource.getId());
expect(support.getUnauthorizedRequestToken("dep1", "urn:callback?query")).andReturn(token);
tokenServices.storeToken("dep1", token);
response.sendRedirect("urn:callback?query&dep1");
replay(request, response, filterChain, tokenServices, support);
filter.doFilter(request, response, filterChain);
verify(request, response, filterChain, tokenServices, support);
reset(request, response, filterChain, tokenServices, support);
request.setAttribute((String) anyObject(), anyObject());
filterChain.doFilter(request, response);
expectLastCall().andThrow(new AccessTokenRequiredException(resource));
expect(tokenServices.getToken("dep1")).andReturn(token);
expect(request.getParameter(OAuthProviderParameter.oauth_verifier.toString())).andReturn("verifier");
OAuthConsumerToken accessToken = new OAuthConsumerToken();
expect(support.getAccessToken(token, "verifier")).andReturn(accessToken);
tokenServices.removeToken("dep1");
tokenServices.storeToken("dep1", accessToken);
expect(response.isCommitted()).andReturn(false);
request.setAttribute((String) anyObject(), anyObject());
filterChain.doFilter(request, response);
replay(request, response, filterChain, tokenServices, support);
filter.doFilter(request, response, filterChain);
verify(request, response, filterChain, tokenServices, support);
reset(request, response, filterChain, tokenServices, support);
}
@Override
protected void tearDown() throws Exception {
OAuthSecurityContextHolder.setContext(null);
}
}
| true | true | public void testDoFilter() throws Exception {
HttpServletRequest request = createMock(HttpServletRequest.class);
HttpServletResponse response = createMock(HttpServletResponse.class);
FilterChain filterChain=createMock(FilterChain.class);
final OAuthConsumerTokenServices tokenServices = createMock(OAuthConsumerTokenServices.class);
final OAuthConsumerSupport support = createMock(OAuthConsumerSupport.class);
final OAuthRememberMeServices rememberMeServices = new NoOpOAuthRememberMeServices();
final BaseProtectedResourceDetails resource = new BaseProtectedResourceDetails();
resource.setId("dep1");
OAuthConsumerContextFilter filter = new OAuthConsumerContextFilter() {
@Override
protected String getCallbackURL(HttpServletRequest request) {
return "urn:callback";
}
@Override
protected String getUserAuthorizationRedirectURL(ProtectedResourceDetails details, OAuthConsumerToken requestToken, String callbackURL) {
return callbackURL + "&" + requestToken.getResourceId();
}
};
filter.setTokenServices(tokenServices);
filter.setConsumerSupport(support);
filter.setRememberMeServices(rememberMeServices);
request.setAttribute((String) anyObject(), anyObject());
filterChain.doFilter(request, response);
expectLastCall().andThrow(new AccessTokenRequiredException(resource));
expect(tokenServices.getToken("dep1")).andReturn(null);
expect(response.encodeRedirectURL("urn:callback")).andReturn("urn:callback?query");
OAuthConsumerToken token = new OAuthConsumerToken();
token.setAccessToken(false);
token.setResourceId(resource.getId());
expect(support.getUnauthorizedRequestToken("dep1", "urn:callback?query")).andReturn(token);
tokenServices.storeToken("dep1", token);
response.sendRedirect("urn:callback?query&dep1");
replay(request, response, filterChain, tokenServices, support);
filter.doFilter(request, response, filterChain);
verify(request, response, filterChain, tokenServices, support);
reset(request, response, filterChain, tokenServices, support);
request.setAttribute((String) anyObject(), anyObject());
filterChain.doFilter(request, response);
expectLastCall().andThrow(new AccessTokenRequiredException(resource));
expect(tokenServices.getToken("dep1")).andReturn(token);
expect(request.getParameter(OAuthProviderParameter.oauth_verifier.toString())).andReturn("verifier");
OAuthConsumerToken accessToken = new OAuthConsumerToken();
expect(support.getAccessToken(token, "verifier")).andReturn(accessToken);
tokenServices.removeToken("dep1");
tokenServices.storeToken("dep1", accessToken);
expect(response.isCommitted()).andReturn(false);
request.setAttribute((String) anyObject(), anyObject());
filterChain.doFilter(request, response);
replay(request, response, filterChain, tokenServices, support);
filter.doFilter(request, response, filterChain);
verify(request, response, filterChain, tokenServices, support);
reset(request, response, filterChain, tokenServices, support);
}
| public void testDoFilter() throws Exception {
HttpServletRequest request = createMock(HttpServletRequest.class);
HttpServletResponse response = createMock(HttpServletResponse.class);
FilterChain filterChain=createMock(FilterChain.class);
final OAuthConsumerTokenServices tokenServices = createMock(OAuthConsumerTokenServices.class);
final OAuthConsumerSupport support = createMock(OAuthConsumerSupport.class);
final OAuthRememberMeServices rememberMeServices = new NoOpOAuthRememberMeServices();
final BaseProtectedResourceDetails resource = new BaseProtectedResourceDetails();
resource.setId("dep1");
OAuthConsumerContextFilter filter = new OAuthConsumerContextFilter() {
@Override
protected String getCallbackURL(HttpServletRequest request) {
return "urn:callback";
}
@Override
protected String getUserAuthorizationRedirectURL(ProtectedResourceDetails details, OAuthConsumerToken requestToken, String callbackURL) {
return callbackURL + "&" + requestToken.getResourceId();
}
};
filter.setTokenServices(tokenServices);
filter.setConsumerSupport(support);
filter.setRememberMeServices(rememberMeServices);
request.setAttribute((String) anyObject(), anyObject());
filterChain.doFilter(request, response);
expectLastCall().andThrow(new AccessTokenRequiredException(resource));
expect(tokenServices.getToken("dep1")).andReturn(null);
expect(request.getParameter("oauth_verifier")).andReturn(null);
expect(response.encodeRedirectURL("urn:callback")).andReturn("urn:callback?query");
OAuthConsumerToken token = new OAuthConsumerToken();
token.setAccessToken(false);
token.setResourceId(resource.getId());
expect(support.getUnauthorizedRequestToken("dep1", "urn:callback?query")).andReturn(token);
tokenServices.storeToken("dep1", token);
response.sendRedirect("urn:callback?query&dep1");
replay(request, response, filterChain, tokenServices, support);
filter.doFilter(request, response, filterChain);
verify(request, response, filterChain, tokenServices, support);
reset(request, response, filterChain, tokenServices, support);
request.setAttribute((String) anyObject(), anyObject());
filterChain.doFilter(request, response);
expectLastCall().andThrow(new AccessTokenRequiredException(resource));
expect(tokenServices.getToken("dep1")).andReturn(token);
expect(request.getParameter(OAuthProviderParameter.oauth_verifier.toString())).andReturn("verifier");
OAuthConsumerToken accessToken = new OAuthConsumerToken();
expect(support.getAccessToken(token, "verifier")).andReturn(accessToken);
tokenServices.removeToken("dep1");
tokenServices.storeToken("dep1", accessToken);
expect(response.isCommitted()).andReturn(false);
request.setAttribute((String) anyObject(), anyObject());
filterChain.doFilter(request, response);
replay(request, response, filterChain, tokenServices, support);
filter.doFilter(request, response, filterChain);
verify(request, response, filterChain, tokenServices, support);
reset(request, response, filterChain, tokenServices, support);
}
|
diff --git a/src/net/sf/hajdbc/dialect/HSQLDBDialect.java b/src/net/sf/hajdbc/dialect/HSQLDBDialect.java
index 09af8acd..27e3b7df 100644
--- a/src/net/sf/hajdbc/dialect/HSQLDBDialect.java
+++ b/src/net/sf/hajdbc/dialect/HSQLDBDialect.java
@@ -1,84 +1,84 @@
/*
* HA-JDBC: High-Availability JDBC
* Copyright (c) 2004-2006 Paul Ferraro
*
* 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
*
* Contact: [email protected]
*/
package net.sf.hajdbc.dialect;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
/**
* Dialect for <a href="http://www.hsqldb.org">HSQLDB</a>.
*
* @author Paul Ferraro
* @since 1.1
*/
public class HSQLDBDialect extends DefaultDialect
{
/**
* @see net.sf.hajdbc.dialect.DefaultDialect#getSimpleSQL()
*/
@Override
public String getSimpleSQL()
{
return "CALL NOW()";
}
/**
* @see net.sf.hajdbc.dialect.DefaultDialect#getSequences(java.sql.Connection)
*/
@Override
public Map<String, Long> getSequences(Connection connection) throws SQLException
{
Map<String, Long> sequenceMap = new HashMap<String, Long>();
ResultSet resultSet = connection.createStatement().executeQuery("SELECT SEQUENCE_SCHEMA, SEQUENCE_NAME, NEXT_VALUE FROM INFORMATION_SCHEMA.SYSTEM_SEQUENCES");
while (resultSet.next())
{
StringBuilder builder = new StringBuilder();
String schema = resultSet.getString(1);
if (schema != null)
{
builder.append(schema).append(".");
}
- sequenceMap.put(builder.append(resultSet.getString(2)).toString(), resultSet.getLong(2));
+ sequenceMap.put(builder.append(resultSet.getString(2)).toString(), resultSet.getLong(3));
}
resultSet.getStatement().close();
return sequenceMap;
}
/**
* Deferrability clause is not supported.
* @see net.sf.hajdbc.dialect.DefaultDialect#createForeignKeyFormat()
*/
@Override
protected String createForeignKeyFormat()
{
return "ALTER TABLE {1} ADD CONSTRAINT {0} FOREIGN KEY ({2}) REFERENCES {3} ({4}) ON DELETE {5,choice,0#CASCADE|1#RESTRICT|2#SET NULL|3#NO ACTION|4#SET DEFAULT} ON UPDATE {6,choice,0#CASCADE|1#RESTRICT|2#SET NULL|3#NO ACTION|4#SET DEFAULT}";
}
}
| true | true | public Map<String, Long> getSequences(Connection connection) throws SQLException
{
Map<String, Long> sequenceMap = new HashMap<String, Long>();
ResultSet resultSet = connection.createStatement().executeQuery("SELECT SEQUENCE_SCHEMA, SEQUENCE_NAME, NEXT_VALUE FROM INFORMATION_SCHEMA.SYSTEM_SEQUENCES");
while (resultSet.next())
{
StringBuilder builder = new StringBuilder();
String schema = resultSet.getString(1);
if (schema != null)
{
builder.append(schema).append(".");
}
sequenceMap.put(builder.append(resultSet.getString(2)).toString(), resultSet.getLong(2));
}
resultSet.getStatement().close();
return sequenceMap;
}
| public Map<String, Long> getSequences(Connection connection) throws SQLException
{
Map<String, Long> sequenceMap = new HashMap<String, Long>();
ResultSet resultSet = connection.createStatement().executeQuery("SELECT SEQUENCE_SCHEMA, SEQUENCE_NAME, NEXT_VALUE FROM INFORMATION_SCHEMA.SYSTEM_SEQUENCES");
while (resultSet.next())
{
StringBuilder builder = new StringBuilder();
String schema = resultSet.getString(1);
if (schema != null)
{
builder.append(schema).append(".");
}
sequenceMap.put(builder.append(resultSet.getString(2)).toString(), resultSet.getLong(3));
}
resultSet.getStatement().close();
return sequenceMap;
}
|
diff --git a/StevenDimDoors/mod_pocketDim/items/itemLinkSignature.java b/StevenDimDoors/mod_pocketDim/items/itemLinkSignature.java
index a205763..415ed84 100644
--- a/StevenDimDoors/mod_pocketDim/items/itemLinkSignature.java
+++ b/StevenDimDoors/mod_pocketDim/items/itemLinkSignature.java
@@ -1,275 +1,275 @@
package StevenDimDoors.mod_pocketDim.items;
import java.util.List;
import StevenDimDoors.mod_pocketDim.LinkData;
import StevenDimDoors.mod_pocketDim.dimHelper;
import StevenDimDoors.mod_pocketDim.mod_pocketDim;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class itemLinkSignature extends Item
{
private Material doorMaterial;
public itemLinkSignature(int par1)
{
super(par1);
this.setMaxStackSize(1);
// this.setTextureFile("/PocketBlockTextures.png");
this.setCreativeTab(CreativeTabs.tabTransport);
// this.itemIcon=5;
this.setMaxDamage(0);
this.hasSubtypes=true;
//TODO move to proxy
}
@SideOnly(Side.CLIENT)
@Override
public boolean hasEffect(ItemStack par1ItemStack)
{
// adds effect if item has a link stored
if(par1ItemStack.hasTagCompound())
{
if(par1ItemStack.stackTagCompound.getBoolean("isCreated"))
{
return true;
}
}
return false;
}
public void registerIcons(IconRegister par1IconRegister)
{
this.itemIcon = par1IconRegister.registerIcon(mod_pocketDim.modid + ":" + this.getUnlocalizedName());
}
@Override
public boolean onItemUse(ItemStack par1ItemStack, EntityPlayer par2EntityPlayer, World par3World, int par4, int par5, int par6, int par7, float par8, float par9, float par10)
{
int key;
LinkData linkData;
int thisWorldID=par3World.provider.dimensionId;
if(!par3World.isRemote)
{
//par1ItemStack= par2EntityPlayer.getCurrentEquippedItem();
Integer[] linkCoords =this.readFromNBT(par1ItemStack);
//System.out.println(key);
int offset = 2;
if(par3World.getBlockId(par4, par5, par6)==Block.snow.blockID)
{
offset = 1;
}
if(par3World.getBlockId(par4, par5, par6)==mod_pocketDim.dimDoorID&&par3World.getBlockId(par4, par5+1, par6)==mod_pocketDim.dimDoorID)
{
offset = 1;
}
else
if(par3World.getBlockId(par4, par5, par6)==mod_pocketDim.ExitDoorID&&par3World.getBlockId(par4, par5+1, par6)==mod_pocketDim.ExitDoorID)
{
offset = 1;
}
else
if(par3World.getBlockId(par4, par5, par6)==mod_pocketDim.dimDoorID&&par3World.getBlockId(par4, par5-1, par6)==mod_pocketDim.dimDoorID)
{
offset = 0;
}
else
if(par3World.getBlockId(par4, par5, par6)==mod_pocketDim.ExitDoorID&&par3World.getBlockId(par4, par5-1, par6)==mod_pocketDim.ExitDoorID)
{
offset = 0;
}
int orientation = MathHelper.floor_double((double)((par2EntityPlayer.rotationYaw + 180.0F) * 4.0F / 360.0F) - 0.5D) & 3;
for(int count = 0;count<3;count++)
{
if(dimHelper.instance.getLinkDataFromCoords(par4, par5+count, par6,par3World)!=null)
{
int id= (par3World.getBlockId(par4, par5+count, par6));
if(id == mod_pocketDim.dimDoorID||id==mod_pocketDim.ExitDoorID||id==mod_pocketDim.chaosDoorID)
{
orientation = dimHelper.instance.getLinkDataFromCoords(par4, par5+count, par6,par3World).linkOrientation;
}
}
}
if(par1ItemStack.getTagCompound()!=null)
{
if(par1ItemStack.getTagCompound().getBoolean("isCreated"))
{
// checks to see if the item has a link stored, if so, it creates it
- dimHelper.instance.createLink(par3World.provider.dimensionId, linkCoords[3], par4, par5+offset, par6, linkCoords[0], linkCoords[1], linkCoords[2],linkCoords[4]);
- dimHelper.instance.createLink(linkCoords[3], par3World.provider.dimensionId, linkCoords[0], linkCoords[1], linkCoords[2],par4, par5+offset, par6,orientation);
+ dimHelper.instance.createLink(par3World.provider.dimensionId, linkCoords[3], par4, par5+offset, par6, linkCoords[0], linkCoords[1], linkCoords[2],orientation);
+ dimHelper.instance.createLink(linkCoords[3], par3World.provider.dimensionId, linkCoords[0], linkCoords[1], linkCoords[2],par4, par5+offset, par6,linkCoords[4]);
--par1ItemStack.stackSize;
par2EntityPlayer.sendChatToPlayer("Rift Created");
par1ItemStack.stackTagCompound=null;
/**
else
{
par2EntityPlayer.sendChatToPlayer("Both ends of a single rift cannot exist in the same dimension.");
}
**/
}
}
else
{
//otherwise, it creates the first half of the link. Next click will complete it.
key= dimHelper.instance.createUniqueInterDimLinkKey();
this.writeToNBT(par1ItemStack, par4, par5+offset, par6,par3World.provider.dimensionId,orientation);
par2EntityPlayer.sendChatToPlayer("Rift Signature Stored");
}
//dimHelper.instance.save();
}
return true;
}
@SideOnly(Side.CLIENT)
/**
* allows items to add custom lines of information to the mouseover description
*/
public void addInformation(ItemStack par1ItemStack, EntityPlayer par2EntityPlayer, List par3List, boolean par4)
{
if(par1ItemStack.hasTagCompound())
{
if(par1ItemStack.stackTagCompound.getBoolean("isCreated"))
{
Integer[] coords = this.readFromNBT(par1ItemStack);
par3List.add(String.valueOf("Leads to dim "+coords[3] +" with depth "+dimHelper.instance.getDimDepth(dimHelper.instance.getDimDepth(coords[3]))));
par3List.add("at x="+coords[0]+" y="+coords[1]+" z="+coords[2]);
}
}
else
{
par3List.add("First click stores location,");
par3List.add ("second click creates two rifts,");
par3List.add("that link the first location");
par3List.add("with the second location");
}
}
public void writeToNBT(ItemStack itemStack,int x, int y, int z, int dimID,int orientation)
{
NBTTagCompound tag;
if(itemStack.hasTagCompound())
{
tag = itemStack.getTagCompound();
}
else
{
tag= new NBTTagCompound();
}
tag.setInteger("linkX", x);
tag.setInteger("linkY", y);
tag.setInteger("linkZ", z);
tag.setInteger("linkDimID", dimID);
tag.setBoolean("isCreated", true);
tag.setInteger("orientation", orientation);
itemStack.setTagCompound(tag);
}
/**
* Read the stack fields from a NBT object.
*/
public Integer[] readFromNBT(ItemStack itemStack)
{
NBTTagCompound tag;
Integer[] linkCoords = new Integer[5];
if(itemStack.hasTagCompound())
{
tag = itemStack.getTagCompound();
if(!tag.getBoolean("isCreated"))
{
return null;
}
linkCoords[0]=tag.getInteger("linkX");
linkCoords[1]=tag.getInteger("linkY");
linkCoords[2]=tag.getInteger("linkZ");
linkCoords[3]=tag.getInteger("linkDimID");
linkCoords[4]=tag.getInteger("orientation");
}
return linkCoords;
}
@Override
public void onCreated(ItemStack par1ItemStack, World par2World, EntityPlayer par3EntityPlayer)
{
if(!par2World.isRemote)
{
/**
//creates the first half of the link on item creation
int key= dimHelper.instance.createUniqueInterDimLinkKey();
LinkData linkData= new LinkData(par2World.provider.dimensionId,MathHelper.floor_double(par3EntityPlayer.posX),MathHelper.floor_double(par3EntityPlayer.posY),MathHelper.floor_double(par3EntityPlayer.posZ));
System.out.println(key);
dimHelper.instance.interDimLinkList.put(key, linkData);
par1ItemStack.setItemDamage(key);
**/
}
}
}
| true | true | public boolean onItemUse(ItemStack par1ItemStack, EntityPlayer par2EntityPlayer, World par3World, int par4, int par5, int par6, int par7, float par8, float par9, float par10)
{
int key;
LinkData linkData;
int thisWorldID=par3World.provider.dimensionId;
if(!par3World.isRemote)
{
//par1ItemStack= par2EntityPlayer.getCurrentEquippedItem();
Integer[] linkCoords =this.readFromNBT(par1ItemStack);
//System.out.println(key);
int offset = 2;
if(par3World.getBlockId(par4, par5, par6)==Block.snow.blockID)
{
offset = 1;
}
if(par3World.getBlockId(par4, par5, par6)==mod_pocketDim.dimDoorID&&par3World.getBlockId(par4, par5+1, par6)==mod_pocketDim.dimDoorID)
{
offset = 1;
}
else
if(par3World.getBlockId(par4, par5, par6)==mod_pocketDim.ExitDoorID&&par3World.getBlockId(par4, par5+1, par6)==mod_pocketDim.ExitDoorID)
{
offset = 1;
}
else
if(par3World.getBlockId(par4, par5, par6)==mod_pocketDim.dimDoorID&&par3World.getBlockId(par4, par5-1, par6)==mod_pocketDim.dimDoorID)
{
offset = 0;
}
else
if(par3World.getBlockId(par4, par5, par6)==mod_pocketDim.ExitDoorID&&par3World.getBlockId(par4, par5-1, par6)==mod_pocketDim.ExitDoorID)
{
offset = 0;
}
int orientation = MathHelper.floor_double((double)((par2EntityPlayer.rotationYaw + 180.0F) * 4.0F / 360.0F) - 0.5D) & 3;
for(int count = 0;count<3;count++)
{
if(dimHelper.instance.getLinkDataFromCoords(par4, par5+count, par6,par3World)!=null)
{
int id= (par3World.getBlockId(par4, par5+count, par6));
if(id == mod_pocketDim.dimDoorID||id==mod_pocketDim.ExitDoorID||id==mod_pocketDim.chaosDoorID)
{
orientation = dimHelper.instance.getLinkDataFromCoords(par4, par5+count, par6,par3World).linkOrientation;
}
}
}
if(par1ItemStack.getTagCompound()!=null)
{
if(par1ItemStack.getTagCompound().getBoolean("isCreated"))
{
// checks to see if the item has a link stored, if so, it creates it
dimHelper.instance.createLink(par3World.provider.dimensionId, linkCoords[3], par4, par5+offset, par6, linkCoords[0], linkCoords[1], linkCoords[2],linkCoords[4]);
dimHelper.instance.createLink(linkCoords[3], par3World.provider.dimensionId, linkCoords[0], linkCoords[1], linkCoords[2],par4, par5+offset, par6,orientation);
--par1ItemStack.stackSize;
par2EntityPlayer.sendChatToPlayer("Rift Created");
par1ItemStack.stackTagCompound=null;
/**
else
{
par2EntityPlayer.sendChatToPlayer("Both ends of a single rift cannot exist in the same dimension.");
}
**/
}
}
else
{
//otherwise, it creates the first half of the link. Next click will complete it.
key= dimHelper.instance.createUniqueInterDimLinkKey();
this.writeToNBT(par1ItemStack, par4, par5+offset, par6,par3World.provider.dimensionId,orientation);
par2EntityPlayer.sendChatToPlayer("Rift Signature Stored");
}
//dimHelper.instance.save();
}
return true;
}
| public boolean onItemUse(ItemStack par1ItemStack, EntityPlayer par2EntityPlayer, World par3World, int par4, int par5, int par6, int par7, float par8, float par9, float par10)
{
int key;
LinkData linkData;
int thisWorldID=par3World.provider.dimensionId;
if(!par3World.isRemote)
{
//par1ItemStack= par2EntityPlayer.getCurrentEquippedItem();
Integer[] linkCoords =this.readFromNBT(par1ItemStack);
//System.out.println(key);
int offset = 2;
if(par3World.getBlockId(par4, par5, par6)==Block.snow.blockID)
{
offset = 1;
}
if(par3World.getBlockId(par4, par5, par6)==mod_pocketDim.dimDoorID&&par3World.getBlockId(par4, par5+1, par6)==mod_pocketDim.dimDoorID)
{
offset = 1;
}
else
if(par3World.getBlockId(par4, par5, par6)==mod_pocketDim.ExitDoorID&&par3World.getBlockId(par4, par5+1, par6)==mod_pocketDim.ExitDoorID)
{
offset = 1;
}
else
if(par3World.getBlockId(par4, par5, par6)==mod_pocketDim.dimDoorID&&par3World.getBlockId(par4, par5-1, par6)==mod_pocketDim.dimDoorID)
{
offset = 0;
}
else
if(par3World.getBlockId(par4, par5, par6)==mod_pocketDim.ExitDoorID&&par3World.getBlockId(par4, par5-1, par6)==mod_pocketDim.ExitDoorID)
{
offset = 0;
}
int orientation = MathHelper.floor_double((double)((par2EntityPlayer.rotationYaw + 180.0F) * 4.0F / 360.0F) - 0.5D) & 3;
for(int count = 0;count<3;count++)
{
if(dimHelper.instance.getLinkDataFromCoords(par4, par5+count, par6,par3World)!=null)
{
int id= (par3World.getBlockId(par4, par5+count, par6));
if(id == mod_pocketDim.dimDoorID||id==mod_pocketDim.ExitDoorID||id==mod_pocketDim.chaosDoorID)
{
orientation = dimHelper.instance.getLinkDataFromCoords(par4, par5+count, par6,par3World).linkOrientation;
}
}
}
if(par1ItemStack.getTagCompound()!=null)
{
if(par1ItemStack.getTagCompound().getBoolean("isCreated"))
{
// checks to see if the item has a link stored, if so, it creates it
dimHelper.instance.createLink(par3World.provider.dimensionId, linkCoords[3], par4, par5+offset, par6, linkCoords[0], linkCoords[1], linkCoords[2],orientation);
dimHelper.instance.createLink(linkCoords[3], par3World.provider.dimensionId, linkCoords[0], linkCoords[1], linkCoords[2],par4, par5+offset, par6,linkCoords[4]);
--par1ItemStack.stackSize;
par2EntityPlayer.sendChatToPlayer("Rift Created");
par1ItemStack.stackTagCompound=null;
/**
else
{
par2EntityPlayer.sendChatToPlayer("Both ends of a single rift cannot exist in the same dimension.");
}
**/
}
}
else
{
//otherwise, it creates the first half of the link. Next click will complete it.
key= dimHelper.instance.createUniqueInterDimLinkKey();
this.writeToNBT(par1ItemStack, par4, par5+offset, par6,par3World.provider.dimensionId,orientation);
par2EntityPlayer.sendChatToPlayer("Rift Signature Stored");
}
//dimHelper.instance.save();
}
return true;
}
|
diff --git a/web/src/main/java/de/betterform/agent/web/event/EventQueue.java b/web/src/main/java/de/betterform/agent/web/event/EventQueue.java
index 97d3083e..a0eda8c9 100644
--- a/web/src/main/java/de/betterform/agent/web/event/EventQueue.java
+++ b/web/src/main/java/de/betterform/agent/web/event/EventQueue.java
@@ -1,180 +1,180 @@
/*
* Copyright (c) 2010. betterForm Project - http://www.betterform.de
* Licensed under the terms of BSD License
*/
package de.betterform.agent.web.event;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import de.betterform.xml.events.BetterFormEventNames;
import de.betterform.xml.events.XMLEvent;
import de.betterform.xml.events.XMLEventFactory;
import de.betterform.xml.events.impl.DefaultXMLEventService;
import de.betterform.xml.events.impl.XercesXMLEventFactory;
import de.betterform.xml.events.impl.DefaultXMLEventInitializer;
import de.betterform.xml.events.impl.XercesXMLEvent;
import de.betterform.xml.xforms.XFormsConstants;
import org.w3c.dom.Element;
import java.util.*;
/**
* EventQueue logs all events happening in XForms processor and build a DOM
* document which represent those events.
*
* @author Joern Turner Lars Windauer
* @version $Id: EventLog.java 2612 2007-07-24 14:51:21Z joern $
*/
public class EventQueue {
public static List<String> HELPER_ELEMENTS = Arrays.asList(XFormsConstants.LABEL, XFormsConstants.HELP, XFormsConstants.HINT, XFormsConstants.ALERT, XFormsConstants.VALUE);
private List<XMLEvent> eventList;
protected static Log LOGGER = LogFactory.getLog(EventQueue.class);
private List<XMLEvent> loadEmbedEventList;
public EventQueue() {
this.eventList = new ArrayList<XMLEvent>();
this.loadEmbedEventList = new ArrayList<XMLEvent>();
}
public List<XMLEvent> getEventList() {
return aggregateEventList();
}
/** Adding XMLEvents to the EventQueue to be processed on the client
* EventTarget is nulled to avoid sending it over the wire, targetName and targetId (received from EventTarget)
* are stored instead in the ContextInfo Map
*
* @param event XMLEvent received from processor
*/
public void add(XMLEvent event) {
try {
XMLEvent clonedEvent = (XMLEvent) event.clone();
Element target = (Element) clonedEvent.getTarget();
clonedEvent.addProperty("targetId", target.getAttributeNS(null, "id"));
String targetName = target.getLocalName();
clonedEvent.addProperty("targetName", targetName);
if (BetterFormEventNames.STATE_CHANGED.equals(clonedEvent.getType()) && HELPER_ELEMENTS.contains(targetName)) {
// parent id is needed for updating all helper elements cause they
// are identified by '<parentId>-label' etc. rather than their own id
String parentId = ((Element) target.getParentNode()).getAttributeNS(null, "id");
clonedEvent.addProperty("parentId", parentId);
}
((XercesXMLEvent) clonedEvent).target=null;
((XercesXMLEvent) clonedEvent).currentTarget=null;
if(isLoadEmbedEvent(clonedEvent)){
this.loadEmbedEventList.add(clonedEvent);
}else {
this.eventList.add(clonedEvent);
}
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public XMLEvent add(String type, String targetId, String targetName) {
DefaultXMLEventService xmlEventService = new DefaultXMLEventService();
xmlEventService.setXMLEventFactory(new XercesXMLEventFactory());
xmlEventService.setXMLEventInitializer(new DefaultXMLEventInitializer());
XMLEventFactory xmlEventFactory = xmlEventService.getXMLEventFactory();
XMLEvent xmlEvent = xmlEventFactory.createXMLEvent(type);
xmlEvent.initXMLEvent(type,false,false,null);
xmlEvent.addProperty("targetid",targetId);
xmlEvent.addProperty("targetName",targetName);
this.eventList.add(xmlEvent);
return xmlEvent;
}
private boolean isLoadEmbedEvent(XMLEvent xmlEvent) {
if(xmlEvent.getType() == null || xmlEvent.getContextInfo() == null) {
return false;
}
if(xmlEvent.getType().equals(BetterFormEventNames.LOAD_URI) &&( "embed".equals(xmlEvent.getContextInfo("show")) || "none".equals(xmlEvent.getContextInfo("show")))){
return true;
}
return false;
}
/**
* clean the EventQueue
*/
public void flush() {
this.eventList.clear();
}
public void addProperty(XMLEvent progressEvent, String key, String value) {
Map contextInfo = progressEvent.getContextInfo();
if(contextInfo != null) {
contextInfo.put(key,value);
}
}
public List<XMLEvent> aggregateEventList() {
// Stack is used to "navigate" through the event list
Stack<XMLEvent> aggregatedInsertEventsStack = new Stack();
Stack<XMLEvent> aggregatedEmbedEventsStack = new Stack();
ArrayList<XMLEvent> aggregatedEventList = new ArrayList<XMLEvent>(eventList.size());
for(XMLEvent xmlEvent: this.loadEmbedEventList){
aggregatedEventList.add(xmlEvent);
}
this.loadEmbedEventList.clear();
for(int i =0;i< eventList.size(); i++) {
XercesXMLEvent xmlEvent = (XercesXMLEvent) eventList.get(i);
XercesXMLEvent xmlEventToAdd = new XercesXMLEvent();
// Map PROTOTYPE_CLONED event to betterform-insert-repeatitem or betterform-insert-itemset event
// and copy event properties to new created XMLEvent
- if(xmlEvent.getType().equals (BetterFormEventNames.PROTOTYPE_CLONED)){
+ if(xmlEvent.getType().equals(BetterFormEventNames.PROTOTYPE_CLONED)){
if(xmlEvent.getContextInfo("targetName").equals(XFormsConstants.ITEMSET)){
xmlEventToAdd.initXMLEvent("betterform-insert-itemset", xmlEvent.getBubbles(), xmlEvent.getCancelable(), xmlEvent.getContextInfo());
}else{
xmlEventToAdd.initXMLEvent("betterform-insert-repeatitem", xmlEvent.getBubbles(), xmlEvent.getCancelable(), xmlEvent.getContextInfo());
}
xmlEventToAdd.target = xmlEvent.target;
xmlEvent.addProperty("generatedIds", new HashMap());
aggregatedEventList.add(xmlEventToAdd);
// push XMLEvent to Stack for further processing
aggregatedInsertEventsStack.push(xmlEventToAdd);
}
// add all generated ids to surrounding betterform-insert-repeatitem or betterform-insert-itemset event
else if (xmlEvent.getType().equals(BetterFormEventNames.ID_GENERATED) && aggregatedInsertEventsStack.size() >0) {
XMLEvent aggregatingInsertEvent = aggregatedInsertEventsStack.peek();
((HashMap)aggregatingInsertEvent.getContextInfo("generatedIds")).put(xmlEvent.getContextInfo("originalId"), xmlEvent.getContextInfo("targetId"));
}
// add insert position to surrounding betterform-insert-repeatitem or betterform-insert-itemset event
else if(xmlEvent.getType().equals(BetterFormEventNames.ITEM_INSERTED)){
XMLEvent tmpEvent = aggregatedInsertEventsStack.pop();
tmpEvent.addProperty("position", xmlEvent.getContextInfo("position"));
tmpEvent.addProperty("label", xmlEvent.getContextInfo("label"));
tmpEvent.addProperty("value", xmlEvent.getContextInfo("value"));
}
else if(xmlEvent.getType().equals(BetterFormEventNames.EMBED)){
aggregatedEventList.add(xmlEvent);
aggregatedEmbedEventsStack.push(xmlEvent);
}
else if(xmlEvent.getType().equals(BetterFormEventNames.EMBED_DONE)){
aggregatedEmbedEventsStack.pop().addProperty("targetElement", xmlEvent.getContextInfo("targetElement"));
aggregatedEventList.add(xmlEvent);
}
// all other events within eventList are simply copied to the new eventlist
else {
aggregatedEventList.add(xmlEvent);
}
}
return aggregatedEventList;
}
}
| true | true | public List<XMLEvent> aggregateEventList() {
// Stack is used to "navigate" through the event list
Stack<XMLEvent> aggregatedInsertEventsStack = new Stack();
Stack<XMLEvent> aggregatedEmbedEventsStack = new Stack();
ArrayList<XMLEvent> aggregatedEventList = new ArrayList<XMLEvent>(eventList.size());
for(XMLEvent xmlEvent: this.loadEmbedEventList){
aggregatedEventList.add(xmlEvent);
}
this.loadEmbedEventList.clear();
for(int i =0;i< eventList.size(); i++) {
XercesXMLEvent xmlEvent = (XercesXMLEvent) eventList.get(i);
XercesXMLEvent xmlEventToAdd = new XercesXMLEvent();
// Map PROTOTYPE_CLONED event to betterform-insert-repeatitem or betterform-insert-itemset event
// and copy event properties to new created XMLEvent
if(xmlEvent.getType().equals (BetterFormEventNames.PROTOTYPE_CLONED)){
if(xmlEvent.getContextInfo("targetName").equals(XFormsConstants.ITEMSET)){
xmlEventToAdd.initXMLEvent("betterform-insert-itemset", xmlEvent.getBubbles(), xmlEvent.getCancelable(), xmlEvent.getContextInfo());
}else{
xmlEventToAdd.initXMLEvent("betterform-insert-repeatitem", xmlEvent.getBubbles(), xmlEvent.getCancelable(), xmlEvent.getContextInfo());
}
xmlEventToAdd.target = xmlEvent.target;
xmlEvent.addProperty("generatedIds", new HashMap());
aggregatedEventList.add(xmlEventToAdd);
// push XMLEvent to Stack for further processing
aggregatedInsertEventsStack.push(xmlEventToAdd);
}
// add all generated ids to surrounding betterform-insert-repeatitem or betterform-insert-itemset event
else if (xmlEvent.getType().equals(BetterFormEventNames.ID_GENERATED) && aggregatedInsertEventsStack.size() >0) {
XMLEvent aggregatingInsertEvent = aggregatedInsertEventsStack.peek();
((HashMap)aggregatingInsertEvent.getContextInfo("generatedIds")).put(xmlEvent.getContextInfo("originalId"), xmlEvent.getContextInfo("targetId"));
}
// add insert position to surrounding betterform-insert-repeatitem or betterform-insert-itemset event
else if(xmlEvent.getType().equals(BetterFormEventNames.ITEM_INSERTED)){
XMLEvent tmpEvent = aggregatedInsertEventsStack.pop();
tmpEvent.addProperty("position", xmlEvent.getContextInfo("position"));
tmpEvent.addProperty("label", xmlEvent.getContextInfo("label"));
tmpEvent.addProperty("value", xmlEvent.getContextInfo("value"));
}
else if(xmlEvent.getType().equals(BetterFormEventNames.EMBED)){
aggregatedEventList.add(xmlEvent);
aggregatedEmbedEventsStack.push(xmlEvent);
}
else if(xmlEvent.getType().equals(BetterFormEventNames.EMBED_DONE)){
aggregatedEmbedEventsStack.pop().addProperty("targetElement", xmlEvent.getContextInfo("targetElement"));
aggregatedEventList.add(xmlEvent);
}
// all other events within eventList are simply copied to the new eventlist
else {
aggregatedEventList.add(xmlEvent);
}
}
return aggregatedEventList;
}
| public List<XMLEvent> aggregateEventList() {
// Stack is used to "navigate" through the event list
Stack<XMLEvent> aggregatedInsertEventsStack = new Stack();
Stack<XMLEvent> aggregatedEmbedEventsStack = new Stack();
ArrayList<XMLEvent> aggregatedEventList = new ArrayList<XMLEvent>(eventList.size());
for(XMLEvent xmlEvent: this.loadEmbedEventList){
aggregatedEventList.add(xmlEvent);
}
this.loadEmbedEventList.clear();
for(int i =0;i< eventList.size(); i++) {
XercesXMLEvent xmlEvent = (XercesXMLEvent) eventList.get(i);
XercesXMLEvent xmlEventToAdd = new XercesXMLEvent();
// Map PROTOTYPE_CLONED event to betterform-insert-repeatitem or betterform-insert-itemset event
// and copy event properties to new created XMLEvent
if(xmlEvent.getType().equals(BetterFormEventNames.PROTOTYPE_CLONED)){
if(xmlEvent.getContextInfo("targetName").equals(XFormsConstants.ITEMSET)){
xmlEventToAdd.initXMLEvent("betterform-insert-itemset", xmlEvent.getBubbles(), xmlEvent.getCancelable(), xmlEvent.getContextInfo());
}else{
xmlEventToAdd.initXMLEvent("betterform-insert-repeatitem", xmlEvent.getBubbles(), xmlEvent.getCancelable(), xmlEvent.getContextInfo());
}
xmlEventToAdd.target = xmlEvent.target;
xmlEvent.addProperty("generatedIds", new HashMap());
aggregatedEventList.add(xmlEventToAdd);
// push XMLEvent to Stack for further processing
aggregatedInsertEventsStack.push(xmlEventToAdd);
}
// add all generated ids to surrounding betterform-insert-repeatitem or betterform-insert-itemset event
else if (xmlEvent.getType().equals(BetterFormEventNames.ID_GENERATED) && aggregatedInsertEventsStack.size() >0) {
XMLEvent aggregatingInsertEvent = aggregatedInsertEventsStack.peek();
((HashMap)aggregatingInsertEvent.getContextInfo("generatedIds")).put(xmlEvent.getContextInfo("originalId"), xmlEvent.getContextInfo("targetId"));
}
// add insert position to surrounding betterform-insert-repeatitem or betterform-insert-itemset event
else if(xmlEvent.getType().equals(BetterFormEventNames.ITEM_INSERTED)){
XMLEvent tmpEvent = aggregatedInsertEventsStack.pop();
tmpEvent.addProperty("position", xmlEvent.getContextInfo("position"));
tmpEvent.addProperty("label", xmlEvent.getContextInfo("label"));
tmpEvent.addProperty("value", xmlEvent.getContextInfo("value"));
}
else if(xmlEvent.getType().equals(BetterFormEventNames.EMBED)){
aggregatedEventList.add(xmlEvent);
aggregatedEmbedEventsStack.push(xmlEvent);
}
else if(xmlEvent.getType().equals(BetterFormEventNames.EMBED_DONE)){
aggregatedEmbedEventsStack.pop().addProperty("targetElement", xmlEvent.getContextInfo("targetElement"));
aggregatedEventList.add(xmlEvent);
}
// all other events within eventList are simply copied to the new eventlist
else {
aggregatedEventList.add(xmlEvent);
}
}
return aggregatedEventList;
}
|
diff --git a/backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/kerberos/JndiAction.java b/backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/kerberos/JndiAction.java
index 6563395a1..9f911deb5 100644
--- a/backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/kerberos/JndiAction.java
+++ b/backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/kerberos/JndiAction.java
@@ -1,242 +1,242 @@
package org.ovirt.engine.core.utils.kerberos;
import java.net.URI;
import java.security.PrivilegedAction;
import java.util.Hashtable;
import javax.naming.AuthenticationException;
import javax.naming.CommunicationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import org.apache.log4j.Logger;
import org.ovirt.engine.core.ldap.LdapProviderType;
import org.ovirt.engine.core.ldap.LdapSRVLocator;
import org.ovirt.engine.core.ldap.RootDSEData;
import org.ovirt.engine.core.utils.dns.DnsSRVLocator.DnsSRVResult;
import org.ovirt.engine.core.utils.ipa.RHDSUserContextMapper;
/**
* JAAS Privileged action to be run when KerbersUtil successfully authenticates. This action performs ldap query to
* retrieve information on the authenticated user and prints the object GUID of that user.
*/
public class JndiAction implements PrivilegedAction {
private String userName;
private final String domainName;
private LdapProviderType ldapProviderType = LdapProviderType.activeDirectory;
private final StringBuffer userGuid;
private final static Logger log = Logger.getLogger(JndiAction.class);
public JndiAction(String userName, String domainName, StringBuffer userGuid, LdapProviderType ldapProviderType) {
this.userName = userName;
this.domainName = domainName;
this.ldapProviderType = ldapProviderType;
this.userGuid = userGuid;
}
@Override
public Object run() {
Hashtable env = new Hashtable(11);
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put("java.naming.ldap.attributes.binary", "objectGUID");
env.put(Context.SECURITY_AUTHENTICATION, "GSSAPI");
env.put("javax.security.sasl.qop", "auth-conf");
// Send an SRV record DNS query to retrieve all the LDAP servers in the domain
LdapSRVLocator locator = new LdapSRVLocator();
DnsSRVResult ldapDnsResult;
try {
ldapDnsResult = locator.getLdapServers(domainName);
} catch (Exception ex) {
return KerberosUtils.convertDNSException(ex);
}
DirContext ctx = null;
String currentLdapServer = null;
if (ldapDnsResult == null || ldapDnsResult.getNumOfValidAddresses() == 0) {
return AuthenticationResult.CANNOT_FIND_LDAP_SERVER_FOR_DOMAIN;
}
// Goes over all the retrieved LDAP servers
for (int counter = 0; counter < ldapDnsResult.getNumOfValidAddresses(); counter++) {
String address = ldapDnsResult.getAddresses()[counter];
try {
// Constructs an LDAP url in a format of ldap://hostname:port (based on the data in the SRV record
// This URL is not enough in order to query for user - as for querying users, we should also provide a
// base dn, for example: ldap://hostname:389/DC=abc,DC=com . However, this URL (ldap:hostname:port)
// suffices for
// getting the rootDSE information, which includes the baseDN.
URI uri = locator.constructURI("LDAP", address);
env.put(Context.PROVIDER_URL, uri.toString());
ctx = new InitialDirContext(env);
// Get the base DN from rootDSE
String domainDN = getDomainDN(ctx);
if (domainDN != null) {
// Append the base DN to the ldap URL in order to construct a full ldap URL (in form of
// ldap:hostname:port/baseDN ) to query for the user
StringBuilder ldapQueryPath = new StringBuilder(uri.toString());
ldapQueryPath.append("/").append(domainDN);
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
// Adding all the three attributes possible, as RHDS doesn't return the nsUniqueId by default
controls.setReturningAttributes(new String[]{"nsUniqueId", "ipaUniqueId","objectGuid","uniqueIdentifier"});
// Added this in order to prevent a warning saying: "the returning obj flag wasn't set, setting it to true"
controls.setReturningObjFlag(true);
currentLdapServer = ldapQueryPath.toString();
env.put(Context.PROVIDER_URL, currentLdapServer);
// Run the LDAP query to get the user
ctx = new InitialDirContext(env);
NamingEnumeration<SearchResult> answer = executeQuery(ctx, controls, prepareQuery());
while (answer.hasMoreElements()) {
// Print the objectGUID for the user
String guid = guidFromResults(answer.next());
if (guid == null) {
break;
}
userGuid.append(guid);
log.debug("User guid is: " + userGuid.toString());
return AuthenticationResult.OK;
}
System.out.println("No user in Directory was found for " + userName
+ ". Trying next LDAP server in list");
} else {
System.out.println(InstallerConstants.ERROR_PREFIX
+ " Failed to query rootDSE in order to get the baseDN. Could not query for user "
- + userName + " in domain" + domainName);
+ + userName + " in domain " + domainName);
}
} catch (CommunicationException ex) {
handleCommunicationException(currentLdapServer, address);
} catch (AuthenticationException ex) {
handleAuthenticationException(ex);
} catch (Exception ex) {
handleGeneralException(ex);
break;
} finally {
if (ctx != null) {
try {
ctx.close();
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} // end of loop on addresses
return AuthenticationResult.NO_USER_INFORMATION_WAS_FOUND_FOR_USER;
}
protected void handleGeneralException(Exception ex) {
System.out.println("General error has occured" + ex.getMessage());
ex.printStackTrace();
}
protected void handleAuthenticationException(AuthenticationException ex) {
ex.printStackTrace();
AuthenticationResult result = AuthenticationResult.OTHER;
KerberosReturnCodeParser parser = new KerberosReturnCodeParser();
result = parser.parse(ex.toString());
String errorMsg = result.getDetailedMessage().replace("Authentication Failed", "LDAP query Failed");
System.out.println(InstallerConstants.ERROR_PREFIX + errorMsg);
log.error("Error from Kerberos: " + ex.getMessage());
}
protected void handleCommunicationException(String currentLdapServer, String address) {
String communicationFailureReason = null;
if (currentLdapServer != null) {
communicationFailureReason = "Cannot connect to LDAP URL: " + currentLdapServer;
} else {
if (address != null) {
communicationFailureReason = "Cannot connect to LDAP server " + address;
} else {
communicationFailureReason =
"Error in connectiong to LDAP server. LDAP server URL could not be obtained";
}
}
System.out.println(communicationFailureReason
+ ". Trying next LDAP server in list (if exists)");
}
private String guidFromResults(SearchResult sr) throws NamingException {
String guidString = "";
try {
if (ldapProviderType.equals(LdapProviderType.ipa)) {
String ipaUniqueId = (String) sr.getAttributes().get("ipaUniqueId").get();
guidString += ipaUniqueId;
} else if (ldapProviderType.equals(LdapProviderType.rhds)) {
String nsUniqueId = (String) sr.getAttributes().get("nsUniqueId").get();
guidString += RHDSUserContextMapper.getGuidFromNsUniqueId(nsUniqueId);
} else if (ldapProviderType.equals(LdapProviderType.itds)) {
String uniqueId = (String) sr.getAttributes().get("uniqueIdentifier").get();
guidString += uniqueId;
} else {
Object objectGuid = sr.getAttributes().get("objectGUID").get();
byte[] guid = (byte[]) objectGuid;
guidString += ((new org.ovirt.engine.core.compat.Guid(guid, false)).toString());
}
} catch (NullPointerException ne) {
System.out.println("LDAP connection successful. But no guid found");
guidString = null;
}
return guidString;
}
private String prepareQuery() {
String query;
if (ldapProviderType.equals(LdapProviderType.ipa)) {
userName = userName.split("@")[0];
query = "(&(objectClass=posixAccount)(objectClass=krbPrincipalAux)(uid=" + userName + "))";
} else if (ldapProviderType.equals(LdapProviderType.rhds)) {
userName = userName.split("@")[0];
query = "(&(objectClass=person)(uid=" + userName + "))";
} else if (ldapProviderType.equals(LdapProviderType.itds)) {
userName = userName.split("@")[0];
query = "(&(objectClass=person)(uid=" + userName + "))";
}
else {
StringBuilder queryBase = new StringBuilder("(&(sAMAccountType=805306368)(");
if (userName.contains("@")) {
queryBase.append("userPrincipalName=" + userName);
} else {
if (userName.length() > 20) {
queryBase.append("userPrincipalName=")
.append(userName)
.append("@")
.append(domainName.toUpperCase());
} else {
queryBase.append("sAMAccountName=").append(userName);
}
}
query = queryBase.append("))").toString();
}
return query;
}
private NamingEnumeration<SearchResult> executeQuery(DirContext ctx, SearchControls controls, String query)
throws NamingException {
NamingEnumeration<SearchResult> answer = ctx.search("", query, controls);
return answer;
}
private String getDomainDN(DirContext ctx) throws NamingException {
RootDSEData rootDSEData = new RootDSEData(ctx);
return rootDSEData.getDomainDN();
}
}
| true | true | public Object run() {
Hashtable env = new Hashtable(11);
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put("java.naming.ldap.attributes.binary", "objectGUID");
env.put(Context.SECURITY_AUTHENTICATION, "GSSAPI");
env.put("javax.security.sasl.qop", "auth-conf");
// Send an SRV record DNS query to retrieve all the LDAP servers in the domain
LdapSRVLocator locator = new LdapSRVLocator();
DnsSRVResult ldapDnsResult;
try {
ldapDnsResult = locator.getLdapServers(domainName);
} catch (Exception ex) {
return KerberosUtils.convertDNSException(ex);
}
DirContext ctx = null;
String currentLdapServer = null;
if (ldapDnsResult == null || ldapDnsResult.getNumOfValidAddresses() == 0) {
return AuthenticationResult.CANNOT_FIND_LDAP_SERVER_FOR_DOMAIN;
}
// Goes over all the retrieved LDAP servers
for (int counter = 0; counter < ldapDnsResult.getNumOfValidAddresses(); counter++) {
String address = ldapDnsResult.getAddresses()[counter];
try {
// Constructs an LDAP url in a format of ldap://hostname:port (based on the data in the SRV record
// This URL is not enough in order to query for user - as for querying users, we should also provide a
// base dn, for example: ldap://hostname:389/DC=abc,DC=com . However, this URL (ldap:hostname:port)
// suffices for
// getting the rootDSE information, which includes the baseDN.
URI uri = locator.constructURI("LDAP", address);
env.put(Context.PROVIDER_URL, uri.toString());
ctx = new InitialDirContext(env);
// Get the base DN from rootDSE
String domainDN = getDomainDN(ctx);
if (domainDN != null) {
// Append the base DN to the ldap URL in order to construct a full ldap URL (in form of
// ldap:hostname:port/baseDN ) to query for the user
StringBuilder ldapQueryPath = new StringBuilder(uri.toString());
ldapQueryPath.append("/").append(domainDN);
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
// Adding all the three attributes possible, as RHDS doesn't return the nsUniqueId by default
controls.setReturningAttributes(new String[]{"nsUniqueId", "ipaUniqueId","objectGuid","uniqueIdentifier"});
// Added this in order to prevent a warning saying: "the returning obj flag wasn't set, setting it to true"
controls.setReturningObjFlag(true);
currentLdapServer = ldapQueryPath.toString();
env.put(Context.PROVIDER_URL, currentLdapServer);
// Run the LDAP query to get the user
ctx = new InitialDirContext(env);
NamingEnumeration<SearchResult> answer = executeQuery(ctx, controls, prepareQuery());
while (answer.hasMoreElements()) {
// Print the objectGUID for the user
String guid = guidFromResults(answer.next());
if (guid == null) {
break;
}
userGuid.append(guid);
log.debug("User guid is: " + userGuid.toString());
return AuthenticationResult.OK;
}
System.out.println("No user in Directory was found for " + userName
+ ". Trying next LDAP server in list");
} else {
System.out.println(InstallerConstants.ERROR_PREFIX
+ " Failed to query rootDSE in order to get the baseDN. Could not query for user "
+ userName + " in domain" + domainName);
}
} catch (CommunicationException ex) {
handleCommunicationException(currentLdapServer, address);
} catch (AuthenticationException ex) {
handleAuthenticationException(ex);
} catch (Exception ex) {
handleGeneralException(ex);
break;
} finally {
if (ctx != null) {
try {
ctx.close();
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} // end of loop on addresses
return AuthenticationResult.NO_USER_INFORMATION_WAS_FOUND_FOR_USER;
}
| public Object run() {
Hashtable env = new Hashtable(11);
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put("java.naming.ldap.attributes.binary", "objectGUID");
env.put(Context.SECURITY_AUTHENTICATION, "GSSAPI");
env.put("javax.security.sasl.qop", "auth-conf");
// Send an SRV record DNS query to retrieve all the LDAP servers in the domain
LdapSRVLocator locator = new LdapSRVLocator();
DnsSRVResult ldapDnsResult;
try {
ldapDnsResult = locator.getLdapServers(domainName);
} catch (Exception ex) {
return KerberosUtils.convertDNSException(ex);
}
DirContext ctx = null;
String currentLdapServer = null;
if (ldapDnsResult == null || ldapDnsResult.getNumOfValidAddresses() == 0) {
return AuthenticationResult.CANNOT_FIND_LDAP_SERVER_FOR_DOMAIN;
}
// Goes over all the retrieved LDAP servers
for (int counter = 0; counter < ldapDnsResult.getNumOfValidAddresses(); counter++) {
String address = ldapDnsResult.getAddresses()[counter];
try {
// Constructs an LDAP url in a format of ldap://hostname:port (based on the data in the SRV record
// This URL is not enough in order to query for user - as for querying users, we should also provide a
// base dn, for example: ldap://hostname:389/DC=abc,DC=com . However, this URL (ldap:hostname:port)
// suffices for
// getting the rootDSE information, which includes the baseDN.
URI uri = locator.constructURI("LDAP", address);
env.put(Context.PROVIDER_URL, uri.toString());
ctx = new InitialDirContext(env);
// Get the base DN from rootDSE
String domainDN = getDomainDN(ctx);
if (domainDN != null) {
// Append the base DN to the ldap URL in order to construct a full ldap URL (in form of
// ldap:hostname:port/baseDN ) to query for the user
StringBuilder ldapQueryPath = new StringBuilder(uri.toString());
ldapQueryPath.append("/").append(domainDN);
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
// Adding all the three attributes possible, as RHDS doesn't return the nsUniqueId by default
controls.setReturningAttributes(new String[]{"nsUniqueId", "ipaUniqueId","objectGuid","uniqueIdentifier"});
// Added this in order to prevent a warning saying: "the returning obj flag wasn't set, setting it to true"
controls.setReturningObjFlag(true);
currentLdapServer = ldapQueryPath.toString();
env.put(Context.PROVIDER_URL, currentLdapServer);
// Run the LDAP query to get the user
ctx = new InitialDirContext(env);
NamingEnumeration<SearchResult> answer = executeQuery(ctx, controls, prepareQuery());
while (answer.hasMoreElements()) {
// Print the objectGUID for the user
String guid = guidFromResults(answer.next());
if (guid == null) {
break;
}
userGuid.append(guid);
log.debug("User guid is: " + userGuid.toString());
return AuthenticationResult.OK;
}
System.out.println("No user in Directory was found for " + userName
+ ". Trying next LDAP server in list");
} else {
System.out.println(InstallerConstants.ERROR_PREFIX
+ " Failed to query rootDSE in order to get the baseDN. Could not query for user "
+ userName + " in domain " + domainName);
}
} catch (CommunicationException ex) {
handleCommunicationException(currentLdapServer, address);
} catch (AuthenticationException ex) {
handleAuthenticationException(ex);
} catch (Exception ex) {
handleGeneralException(ex);
break;
} finally {
if (ctx != null) {
try {
ctx.close();
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} // end of loop on addresses
return AuthenticationResult.NO_USER_INFORMATION_WAS_FOUND_FOR_USER;
}
|
diff --git a/src/net/brwyatt/badscience/levelgrid/LevelGrid.java b/src/net/brwyatt/badscience/levelgrid/LevelGrid.java
index b1cc729..3edfda5 100644
--- a/src/net/brwyatt/badscience/levelgrid/LevelGrid.java
+++ b/src/net/brwyatt/badscience/levelgrid/LevelGrid.java
@@ -1,146 +1,146 @@
package net.brwyatt.badscience.levelgrid;
import java.util.ArrayList;
public class LevelGrid {
private final int vanishingY=-1000;//Constant as changing this would break the horizontal line spacing (for now).
private final int squareWidth=100;//Constant for now. This might be something that can be changed if the viewport size changes
private int viewWidth;
private int viewHeight;
private ArrayList<ArrayList<LevelGridSquare>> gridSquares;
public LevelGrid(int viewWidth,int viewHeight){
this.viewWidth=viewWidth;
this.viewHeight=viewHeight;
gridSquares=new ArrayList<ArrayList<LevelGridSquare>>();
calculateGrid();
}
public void calculateGrid(){
int verticalCount=0;
int horizontalCount=0;
ArrayList<Integer> yValues=new ArrayList<Integer>();
int prevYPos=0;
int yPos=0;
//loop over all the horizontal values (only need to calculate these once
for(int d=-1;prevYPos>=0;d++){
prevYPos=yPos;
if(d==0){
yPos=viewHeight;
}else{
yPos=(int) Math.round((viewHeight-(squareWidth*(48/((Math.sqrt(1872)/d)+3)))));
}
yValues.add(0,yPos);
horizontalCount++;
//int leftX = (int)Math.round((yPos-leftB)/leftM);
//System.out.println("LEFT: ("+leftX+","+yPos+")");
//int rightX = (int)Math.round((yPos-rightB)/rightM);
//System.out.println("RIGHT: ("+rightX+","+yPos+")");
}
int centerX=viewWidth/2;
//Find all grid points
//Loop over vertical lines
for(int offset=squareWidth/2;offset<=750;offset+=squareWidth){//Test should be changed to determine if we have have found the second vertical that isn't visible
double leftM=((vanishingY-viewHeight)/((double)offset));
double leftB=(vanishingY-(leftM*centerX));
System.out.println("LEFT: y=("+leftM+")*x+("+leftB+")");
verticalCount++;
double rightM=((vanishingY-viewHeight)/(-((double)offset)));
double rightB=(vanishingY-(rightM*centerX));
System.out.println("RIGHT: y=("+rightM+")*x+("+rightB+")");
verticalCount++;
if(gridSquares.size()==0){//this is our first loop
ArrayList<LevelGridSquare> col=new ArrayList<LevelGridSquare>();
for(int i=0;i<yValues.size()-1;i++){
int top=yValues.get(i);
int bottom=yValues.get(i+1);
col.add(new LevelGridSquare(
new LevelGridPoint((int)Math.round((top-leftB)/leftM),top),
new LevelGridPoint((int)Math.round((top-rightB)/rightM),top),
new LevelGridPoint((int)Math.round((bottom-leftB)/leftM),bottom),
new LevelGridPoint((int)Math.round((bottom-rightB)/rightM),bottom)
));
if(i>0){
- col.get(i).setBelow(col.get(i+1));
- col.get(i+1).setAbove(col.get(i));
+ col.get(i).setAbove(col.get(i-1));
+ col.get(i-1).setBelow(col.get(i));
}
}
gridSquares.add(col);
}else{//all others
ArrayList<LevelGridSquare> leftCol=new ArrayList<LevelGridSquare>();
ArrayList<LevelGridSquare> lastLeftCol=gridSquares.get(0);
ArrayList<LevelGridSquare> rightCol=new ArrayList<LevelGridSquare>();
ArrayList<LevelGridSquare> lastRightCol=gridSquares.get(gridSquares.size()-1);
for(int i=0;i<yValues.size()-1;i++){
int top=yValues.get(i);
int bottom=yValues.get(i+1);
LevelGridSquare lastLeftSquare=lastLeftCol.get(i);
LevelGridSquare lastRightSquare=lastRightCol.get(i);
LevelGridSquare newLeftSquare=new LevelGridSquare(
new LevelGridPoint((int)Math.round((top-leftB)/leftM),top),
lastLeftSquare.getTopLeft(),
new LevelGridPoint((int)Math.round((bottom-leftB)/leftM),bottom),
lastLeftSquare.getBottomLeft()
);
LevelGridSquare newRightSquare=new LevelGridSquare(
lastRightSquare.getTopRight(),
new LevelGridPoint((int)Math.round((top-rightB)/rightM),top),
lastRightSquare.getBottomRight(),
new LevelGridPoint((int)Math.round((bottom-rightB)/rightM),bottom)
);
leftCol.add(newLeftSquare);
rightCol.add(newRightSquare);
newLeftSquare.setRight(lastLeftSquare);
lastLeftSquare.setLeft(newLeftSquare);
newRightSquare.setLeft(lastRightSquare);
lastRightSquare.setRight(newRightSquare);
if(i>0){
- leftCol.get(i).setBelow(leftCol.get(i+1));
- leftCol.get(i+1).setAbove(leftCol.get(i));
- rightCol.get(i).setBelow(rightCol.get(i+1));
- rightCol.get(i+1).setAbove(rightCol.get(i));
+ leftCol.get(i).setAbove(leftCol.get(i-1));
+ leftCol.get(i-1).setBelow(leftCol.get(i));
+ rightCol.get(i).setAbove(rightCol.get(i-1));
+ rightCol.get(i-1).setBelow(rightCol.get(i));
}
}
gridSquares.add(0,leftCol);
gridSquares.add(rightCol);
}
}
System.out.println("Vertical lines: "+verticalCount);
System.out.println("Horizontal lines: "+horizontalCount);
System.out.println("Grid: "+gridSquares.size()+"x"+gridSquares.get(0).size());
}
public int getViewWidth() {
return viewWidth;
}
public int getViewHeight() {
return viewHeight;
}
public void setViewWidth(int viewWidth) {
this.viewWidth = viewWidth;
}
public void setViewHeight(int viewHeight) {
this.viewHeight = viewHeight;
}
public int getGridWidth(){
return gridSquares.size();
}
public int getGridHeight(){
return gridSquares.get(0).size();
}
public LevelGridSquare getGridSquare(int x, int y){
return gridSquares.get(x).get(y);
}
}
| false | true | public void calculateGrid(){
int verticalCount=0;
int horizontalCount=0;
ArrayList<Integer> yValues=new ArrayList<Integer>();
int prevYPos=0;
int yPos=0;
//loop over all the horizontal values (only need to calculate these once
for(int d=-1;prevYPos>=0;d++){
prevYPos=yPos;
if(d==0){
yPos=viewHeight;
}else{
yPos=(int) Math.round((viewHeight-(squareWidth*(48/((Math.sqrt(1872)/d)+3)))));
}
yValues.add(0,yPos);
horizontalCount++;
//int leftX = (int)Math.round((yPos-leftB)/leftM);
//System.out.println("LEFT: ("+leftX+","+yPos+")");
//int rightX = (int)Math.round((yPos-rightB)/rightM);
//System.out.println("RIGHT: ("+rightX+","+yPos+")");
}
int centerX=viewWidth/2;
//Find all grid points
//Loop over vertical lines
for(int offset=squareWidth/2;offset<=750;offset+=squareWidth){//Test should be changed to determine if we have have found the second vertical that isn't visible
double leftM=((vanishingY-viewHeight)/((double)offset));
double leftB=(vanishingY-(leftM*centerX));
System.out.println("LEFT: y=("+leftM+")*x+("+leftB+")");
verticalCount++;
double rightM=((vanishingY-viewHeight)/(-((double)offset)));
double rightB=(vanishingY-(rightM*centerX));
System.out.println("RIGHT: y=("+rightM+")*x+("+rightB+")");
verticalCount++;
if(gridSquares.size()==0){//this is our first loop
ArrayList<LevelGridSquare> col=new ArrayList<LevelGridSquare>();
for(int i=0;i<yValues.size()-1;i++){
int top=yValues.get(i);
int bottom=yValues.get(i+1);
col.add(new LevelGridSquare(
new LevelGridPoint((int)Math.round((top-leftB)/leftM),top),
new LevelGridPoint((int)Math.round((top-rightB)/rightM),top),
new LevelGridPoint((int)Math.round((bottom-leftB)/leftM),bottom),
new LevelGridPoint((int)Math.round((bottom-rightB)/rightM),bottom)
));
if(i>0){
col.get(i).setBelow(col.get(i+1));
col.get(i+1).setAbove(col.get(i));
}
}
gridSquares.add(col);
}else{//all others
ArrayList<LevelGridSquare> leftCol=new ArrayList<LevelGridSquare>();
ArrayList<LevelGridSquare> lastLeftCol=gridSquares.get(0);
ArrayList<LevelGridSquare> rightCol=new ArrayList<LevelGridSquare>();
ArrayList<LevelGridSquare> lastRightCol=gridSquares.get(gridSquares.size()-1);
for(int i=0;i<yValues.size()-1;i++){
int top=yValues.get(i);
int bottom=yValues.get(i+1);
LevelGridSquare lastLeftSquare=lastLeftCol.get(i);
LevelGridSquare lastRightSquare=lastRightCol.get(i);
LevelGridSquare newLeftSquare=new LevelGridSquare(
new LevelGridPoint((int)Math.round((top-leftB)/leftM),top),
lastLeftSquare.getTopLeft(),
new LevelGridPoint((int)Math.round((bottom-leftB)/leftM),bottom),
lastLeftSquare.getBottomLeft()
);
LevelGridSquare newRightSquare=new LevelGridSquare(
lastRightSquare.getTopRight(),
new LevelGridPoint((int)Math.round((top-rightB)/rightM),top),
lastRightSquare.getBottomRight(),
new LevelGridPoint((int)Math.round((bottom-rightB)/rightM),bottom)
);
leftCol.add(newLeftSquare);
rightCol.add(newRightSquare);
newLeftSquare.setRight(lastLeftSquare);
lastLeftSquare.setLeft(newLeftSquare);
newRightSquare.setLeft(lastRightSquare);
lastRightSquare.setRight(newRightSquare);
if(i>0){
leftCol.get(i).setBelow(leftCol.get(i+1));
leftCol.get(i+1).setAbove(leftCol.get(i));
rightCol.get(i).setBelow(rightCol.get(i+1));
rightCol.get(i+1).setAbove(rightCol.get(i));
}
}
gridSquares.add(0,leftCol);
gridSquares.add(rightCol);
}
}
System.out.println("Vertical lines: "+verticalCount);
System.out.println("Horizontal lines: "+horizontalCount);
System.out.println("Grid: "+gridSquares.size()+"x"+gridSquares.get(0).size());
}
| public void calculateGrid(){
int verticalCount=0;
int horizontalCount=0;
ArrayList<Integer> yValues=new ArrayList<Integer>();
int prevYPos=0;
int yPos=0;
//loop over all the horizontal values (only need to calculate these once
for(int d=-1;prevYPos>=0;d++){
prevYPos=yPos;
if(d==0){
yPos=viewHeight;
}else{
yPos=(int) Math.round((viewHeight-(squareWidth*(48/((Math.sqrt(1872)/d)+3)))));
}
yValues.add(0,yPos);
horizontalCount++;
//int leftX = (int)Math.round((yPos-leftB)/leftM);
//System.out.println("LEFT: ("+leftX+","+yPos+")");
//int rightX = (int)Math.round((yPos-rightB)/rightM);
//System.out.println("RIGHT: ("+rightX+","+yPos+")");
}
int centerX=viewWidth/2;
//Find all grid points
//Loop over vertical lines
for(int offset=squareWidth/2;offset<=750;offset+=squareWidth){//Test should be changed to determine if we have have found the second vertical that isn't visible
double leftM=((vanishingY-viewHeight)/((double)offset));
double leftB=(vanishingY-(leftM*centerX));
System.out.println("LEFT: y=("+leftM+")*x+("+leftB+")");
verticalCount++;
double rightM=((vanishingY-viewHeight)/(-((double)offset)));
double rightB=(vanishingY-(rightM*centerX));
System.out.println("RIGHT: y=("+rightM+")*x+("+rightB+")");
verticalCount++;
if(gridSquares.size()==0){//this is our first loop
ArrayList<LevelGridSquare> col=new ArrayList<LevelGridSquare>();
for(int i=0;i<yValues.size()-1;i++){
int top=yValues.get(i);
int bottom=yValues.get(i+1);
col.add(new LevelGridSquare(
new LevelGridPoint((int)Math.round((top-leftB)/leftM),top),
new LevelGridPoint((int)Math.round((top-rightB)/rightM),top),
new LevelGridPoint((int)Math.round((bottom-leftB)/leftM),bottom),
new LevelGridPoint((int)Math.round((bottom-rightB)/rightM),bottom)
));
if(i>0){
col.get(i).setAbove(col.get(i-1));
col.get(i-1).setBelow(col.get(i));
}
}
gridSquares.add(col);
}else{//all others
ArrayList<LevelGridSquare> leftCol=new ArrayList<LevelGridSquare>();
ArrayList<LevelGridSquare> lastLeftCol=gridSquares.get(0);
ArrayList<LevelGridSquare> rightCol=new ArrayList<LevelGridSquare>();
ArrayList<LevelGridSquare> lastRightCol=gridSquares.get(gridSquares.size()-1);
for(int i=0;i<yValues.size()-1;i++){
int top=yValues.get(i);
int bottom=yValues.get(i+1);
LevelGridSquare lastLeftSquare=lastLeftCol.get(i);
LevelGridSquare lastRightSquare=lastRightCol.get(i);
LevelGridSquare newLeftSquare=new LevelGridSquare(
new LevelGridPoint((int)Math.round((top-leftB)/leftM),top),
lastLeftSquare.getTopLeft(),
new LevelGridPoint((int)Math.round((bottom-leftB)/leftM),bottom),
lastLeftSquare.getBottomLeft()
);
LevelGridSquare newRightSquare=new LevelGridSquare(
lastRightSquare.getTopRight(),
new LevelGridPoint((int)Math.round((top-rightB)/rightM),top),
lastRightSquare.getBottomRight(),
new LevelGridPoint((int)Math.round((bottom-rightB)/rightM),bottom)
);
leftCol.add(newLeftSquare);
rightCol.add(newRightSquare);
newLeftSquare.setRight(lastLeftSquare);
lastLeftSquare.setLeft(newLeftSquare);
newRightSquare.setLeft(lastRightSquare);
lastRightSquare.setRight(newRightSquare);
if(i>0){
leftCol.get(i).setAbove(leftCol.get(i-1));
leftCol.get(i-1).setBelow(leftCol.get(i));
rightCol.get(i).setAbove(rightCol.get(i-1));
rightCol.get(i-1).setBelow(rightCol.get(i));
}
}
gridSquares.add(0,leftCol);
gridSquares.add(rightCol);
}
}
System.out.println("Vertical lines: "+verticalCount);
System.out.println("Horizontal lines: "+horizontalCount);
System.out.println("Grid: "+gridSquares.size()+"x"+gridSquares.get(0).size());
}
|
diff --git a/src/gov/nih/nci/ncicb/cadsr/loader/persister/OcRecPersister.java b/src/gov/nih/nci/ncicb/cadsr/loader/persister/OcRecPersister.java
index fa9b95f7..3b8b5dc2 100755
--- a/src/gov/nih/nci/ncicb/cadsr/loader/persister/OcRecPersister.java
+++ b/src/gov/nih/nci/ncicb/cadsr/loader/persister/OcRecPersister.java
@@ -1,140 +1,140 @@
package gov.nih.nci.ncicb.cadsr.loader.persister;
import gov.nih.nci.ncicb.cadsr.dao.*;
import gov.nih.nci.ncicb.cadsr.domain.*;
import gov.nih.nci.ncicb.cadsr.loader.ElementsLists;
import gov.nih.nci.ncicb.cadsr.loader.util.PropertyAccessor;
import gov.nih.nci.ncicb.cadsr.loader.defaults.UMLDefaults;
import org.apache.log4j.Logger;
import java.util.*;
public class OcRecPersister extends UMLPersister {
private static Logger logger = Logger.getLogger(OcRecPersister.class.getName());
public OcRecPersister(ElementsLists list) {
this.elements = list;
defaults = UMLDefaults.getInstance();
}
public void persist() throws PersisterException {
ObjectClassRelationship ocr = DomainObjectFactory.newObjectClassRelationship();
List ocrs = (List) elements.getElements(ocr.getClass());
if (ocrs != null) {
for (ListIterator it = ocrs.listIterator(); it.hasNext();) {
ocr = (ObjectClassRelationship) it.next();
ocr.setContext(defaults.getContext());
ocr.setAudit(defaults.getAudit());
ocr.setVersion(defaults.getVersion());
ocr.setWorkflowStatus(defaults.getWorkflowStatus());
String sourcePackage = getPackageName(ocr.getSource());
String targetPackage = getPackageName(ocr.getTarget());
ocr.setPreferredDefinition(new OCRDefinitionBuilder().buildDefinition(ocr));
if ((ocr.getLongName() == null) ||
(ocr.getLongName().length() == 0)) {
logger.debug("No Role name for association. Generating one");
ocr.setLongName(new OCRRoleNameBuilder().buildRoleName(ocr));
}
List ocs = elements.
getElements(DomainObjectFactory.newObjectClass()
.getClass());
for (int j = 0; j < ocs.size(); j++) {
ObjectClass o = (ObjectClass) ocs.get(j);
if (o.getLongName().equals(ocr.getSource().getLongName())) {
ocr.setSource(o);
}
if (o.getLongName().equals(ocr.getTarget()
.getLongName())) {
ocr.setTarget(o);
}
}
// logger.info(PropertyAccessor
// .getProperty("created.association"));
LogUtil.logAc(ocr, logger);
logger.info(PropertyAccessor
.getProperty("source.role", ocr.getSourceRole()));
logger.info(PropertyAccessor
.getProperty("source.class", ocr.getSource().getLongName()));
logger.info(PropertyAccessor.getProperty
("source.cardinality", new Object[]
{new Integer(ocr.getSourceLowCardinality()),
new Integer(ocr.getSourceHighCardinality())}));
logger.info(PropertyAccessor
.getProperty("target.role", ocr.getTargetRole()));
logger.info(PropertyAccessor
.getProperty("target.class", ocr.getTarget().getLongName()));
logger.info(PropertyAccessor.getProperty
("target.cardinality", new Object[]
{new Integer(ocr.getTargetLowCardinality()),
new Integer(ocr.getTargetHighCardinality())}));
logger.info(PropertyAccessor.getProperty
("direction", ocr.getDirection()));
logger.info(PropertyAccessor.getProperty
("type", ocr.getType()));
// check if association already exists
ObjectClassRelationship ocr2 = DomainObjectFactory.newObjectClassRelationship();
ocr2.setSource(ocr.getSource());
ocr2.setSourceRole(ocr.getSourceRole());
ocr2.setTarget(ocr.getTarget());
ocr2.setTargetRole(ocr.getTargetRole());
List eager = new ArrayList();
eager.add(EagerConstants.AC_CS_CSI);
List l = objectClassRelationshipDAO.find(ocr2, eager);
// boolean found = false;
// if (l.size() > 0) {
// for (Iterator it2 = l.iterator(); it2.hasNext();) {
// ocr2 = (ObjectClassRelationship) it2.next();
// List acCsCsis = (List) ocr2.getAcCsCsis();
// for (Iterator it3 = acCsCsis.iterator(); it3.hasNext();) {
// AdminComponentClassSchemeClassSchemeItem acCsCsi = (AdminComponentClassSchemeClassSchemeItem) it3.next();
// if (acCsCsi.getCsCsi().getCs().getLongName().equals(defaults.getProjectCs().getLongName())) {
// found = true;
// logger.debug("Association with same classification already found");
// }
// }
// }
// }
if (l.size() > 0) {
logger.info(PropertyAccessor.getProperty("existed.association"));
ocr = (ObjectClassRelationship)l.get(0);
} else {
- ocr.setPreferredName(
- ocr.getSource().getPublicId() + "-" +
- ocr.getSource().getVersion() + ":" +
- ocr.getTarget().getPublicId() + "-" +
- ocr.getTarget().getVersion()
- );
+// ocr.setPreferredName(
+// ocr.getSource().getPublicId() + "-" +
+// ocr.getSource().getVersion() + ":" +
+// ocr.getTarget().getPublicId() + "-" +
+// ocr.getTarget().getVersion()
+// );
ocr.setId(objectClassRelationshipDAO.create(ocr));
// addProjectCs(ocr);
logger.info(PropertyAccessor.getProperty("created.association"));
}
addPackageClassification(ocr, sourcePackage);
addPackageClassification(ocr, targetPackage);
}
}
}
}
| true | true | public void persist() throws PersisterException {
ObjectClassRelationship ocr = DomainObjectFactory.newObjectClassRelationship();
List ocrs = (List) elements.getElements(ocr.getClass());
if (ocrs != null) {
for (ListIterator it = ocrs.listIterator(); it.hasNext();) {
ocr = (ObjectClassRelationship) it.next();
ocr.setContext(defaults.getContext());
ocr.setAudit(defaults.getAudit());
ocr.setVersion(defaults.getVersion());
ocr.setWorkflowStatus(defaults.getWorkflowStatus());
String sourcePackage = getPackageName(ocr.getSource());
String targetPackage = getPackageName(ocr.getTarget());
ocr.setPreferredDefinition(new OCRDefinitionBuilder().buildDefinition(ocr));
if ((ocr.getLongName() == null) ||
(ocr.getLongName().length() == 0)) {
logger.debug("No Role name for association. Generating one");
ocr.setLongName(new OCRRoleNameBuilder().buildRoleName(ocr));
}
List ocs = elements.
getElements(DomainObjectFactory.newObjectClass()
.getClass());
for (int j = 0; j < ocs.size(); j++) {
ObjectClass o = (ObjectClass) ocs.get(j);
if (o.getLongName().equals(ocr.getSource().getLongName())) {
ocr.setSource(o);
}
if (o.getLongName().equals(ocr.getTarget()
.getLongName())) {
ocr.setTarget(o);
}
}
// logger.info(PropertyAccessor
// .getProperty("created.association"));
LogUtil.logAc(ocr, logger);
logger.info(PropertyAccessor
.getProperty("source.role", ocr.getSourceRole()));
logger.info(PropertyAccessor
.getProperty("source.class", ocr.getSource().getLongName()));
logger.info(PropertyAccessor.getProperty
("source.cardinality", new Object[]
{new Integer(ocr.getSourceLowCardinality()),
new Integer(ocr.getSourceHighCardinality())}));
logger.info(PropertyAccessor
.getProperty("target.role", ocr.getTargetRole()));
logger.info(PropertyAccessor
.getProperty("target.class", ocr.getTarget().getLongName()));
logger.info(PropertyAccessor.getProperty
("target.cardinality", new Object[]
{new Integer(ocr.getTargetLowCardinality()),
new Integer(ocr.getTargetHighCardinality())}));
logger.info(PropertyAccessor.getProperty
("direction", ocr.getDirection()));
logger.info(PropertyAccessor.getProperty
("type", ocr.getType()));
// check if association already exists
ObjectClassRelationship ocr2 = DomainObjectFactory.newObjectClassRelationship();
ocr2.setSource(ocr.getSource());
ocr2.setSourceRole(ocr.getSourceRole());
ocr2.setTarget(ocr.getTarget());
ocr2.setTargetRole(ocr.getTargetRole());
List eager = new ArrayList();
eager.add(EagerConstants.AC_CS_CSI);
List l = objectClassRelationshipDAO.find(ocr2, eager);
// boolean found = false;
// if (l.size() > 0) {
// for (Iterator it2 = l.iterator(); it2.hasNext();) {
// ocr2 = (ObjectClassRelationship) it2.next();
// List acCsCsis = (List) ocr2.getAcCsCsis();
// for (Iterator it3 = acCsCsis.iterator(); it3.hasNext();) {
// AdminComponentClassSchemeClassSchemeItem acCsCsi = (AdminComponentClassSchemeClassSchemeItem) it3.next();
// if (acCsCsi.getCsCsi().getCs().getLongName().equals(defaults.getProjectCs().getLongName())) {
// found = true;
// logger.debug("Association with same classification already found");
// }
// }
// }
// }
if (l.size() > 0) {
logger.info(PropertyAccessor.getProperty("existed.association"));
ocr = (ObjectClassRelationship)l.get(0);
} else {
ocr.setPreferredName(
ocr.getSource().getPublicId() + "-" +
ocr.getSource().getVersion() + ":" +
ocr.getTarget().getPublicId() + "-" +
ocr.getTarget().getVersion()
);
ocr.setId(objectClassRelationshipDAO.create(ocr));
// addProjectCs(ocr);
logger.info(PropertyAccessor.getProperty("created.association"));
}
addPackageClassification(ocr, sourcePackage);
addPackageClassification(ocr, targetPackage);
}
}
}
| public void persist() throws PersisterException {
ObjectClassRelationship ocr = DomainObjectFactory.newObjectClassRelationship();
List ocrs = (List) elements.getElements(ocr.getClass());
if (ocrs != null) {
for (ListIterator it = ocrs.listIterator(); it.hasNext();) {
ocr = (ObjectClassRelationship) it.next();
ocr.setContext(defaults.getContext());
ocr.setAudit(defaults.getAudit());
ocr.setVersion(defaults.getVersion());
ocr.setWorkflowStatus(defaults.getWorkflowStatus());
String sourcePackage = getPackageName(ocr.getSource());
String targetPackage = getPackageName(ocr.getTarget());
ocr.setPreferredDefinition(new OCRDefinitionBuilder().buildDefinition(ocr));
if ((ocr.getLongName() == null) ||
(ocr.getLongName().length() == 0)) {
logger.debug("No Role name for association. Generating one");
ocr.setLongName(new OCRRoleNameBuilder().buildRoleName(ocr));
}
List ocs = elements.
getElements(DomainObjectFactory.newObjectClass()
.getClass());
for (int j = 0; j < ocs.size(); j++) {
ObjectClass o = (ObjectClass) ocs.get(j);
if (o.getLongName().equals(ocr.getSource().getLongName())) {
ocr.setSource(o);
}
if (o.getLongName().equals(ocr.getTarget()
.getLongName())) {
ocr.setTarget(o);
}
}
// logger.info(PropertyAccessor
// .getProperty("created.association"));
LogUtil.logAc(ocr, logger);
logger.info(PropertyAccessor
.getProperty("source.role", ocr.getSourceRole()));
logger.info(PropertyAccessor
.getProperty("source.class", ocr.getSource().getLongName()));
logger.info(PropertyAccessor.getProperty
("source.cardinality", new Object[]
{new Integer(ocr.getSourceLowCardinality()),
new Integer(ocr.getSourceHighCardinality())}));
logger.info(PropertyAccessor
.getProperty("target.role", ocr.getTargetRole()));
logger.info(PropertyAccessor
.getProperty("target.class", ocr.getTarget().getLongName()));
logger.info(PropertyAccessor.getProperty
("target.cardinality", new Object[]
{new Integer(ocr.getTargetLowCardinality()),
new Integer(ocr.getTargetHighCardinality())}));
logger.info(PropertyAccessor.getProperty
("direction", ocr.getDirection()));
logger.info(PropertyAccessor.getProperty
("type", ocr.getType()));
// check if association already exists
ObjectClassRelationship ocr2 = DomainObjectFactory.newObjectClassRelationship();
ocr2.setSource(ocr.getSource());
ocr2.setSourceRole(ocr.getSourceRole());
ocr2.setTarget(ocr.getTarget());
ocr2.setTargetRole(ocr.getTargetRole());
List eager = new ArrayList();
eager.add(EagerConstants.AC_CS_CSI);
List l = objectClassRelationshipDAO.find(ocr2, eager);
// boolean found = false;
// if (l.size() > 0) {
// for (Iterator it2 = l.iterator(); it2.hasNext();) {
// ocr2 = (ObjectClassRelationship) it2.next();
// List acCsCsis = (List) ocr2.getAcCsCsis();
// for (Iterator it3 = acCsCsis.iterator(); it3.hasNext();) {
// AdminComponentClassSchemeClassSchemeItem acCsCsi = (AdminComponentClassSchemeClassSchemeItem) it3.next();
// if (acCsCsi.getCsCsi().getCs().getLongName().equals(defaults.getProjectCs().getLongName())) {
// found = true;
// logger.debug("Association with same classification already found");
// }
// }
// }
// }
if (l.size() > 0) {
logger.info(PropertyAccessor.getProperty("existed.association"));
ocr = (ObjectClassRelationship)l.get(0);
} else {
// ocr.setPreferredName(
// ocr.getSource().getPublicId() + "-" +
// ocr.getSource().getVersion() + ":" +
// ocr.getTarget().getPublicId() + "-" +
// ocr.getTarget().getVersion()
// );
ocr.setId(objectClassRelationshipDAO.create(ocr));
// addProjectCs(ocr);
logger.info(PropertyAccessor.getProperty("created.association"));
}
addPackageClassification(ocr, sourcePackage);
addPackageClassification(ocr, targetPackage);
}
}
}
|
diff --git a/domainiser-core/src/test/java/com/knaptus/domainiser/example/ExampleDomainResolver.java b/domainiser-core/src/test/java/com/knaptus/domainiser/example/ExampleDomainResolver.java
index 41d5c2c..132ee85 100644
--- a/domainiser-core/src/test/java/com/knaptus/domainiser/example/ExampleDomainResolver.java
+++ b/domainiser-core/src/test/java/com/knaptus/domainiser/example/ExampleDomainResolver.java
@@ -1,17 +1,17 @@
package com.knaptus.domainiser.example;
import com.knaptus.domainiser.core.DomainResolver;
/**
* Example of a domain resolver.
*
* @author Aditya Bhardwaj
*/
public class ExampleDomainResolver implements DomainResolver {
@Override
public boolean isDomainModel(Class domain) {
- return domain.getCanonicalName().contains("intelladept");
+ return domain.getCanonicalName().contains("knaptus");
}
}
| true | true | public boolean isDomainModel(Class domain) {
return domain.getCanonicalName().contains("intelladept");
}
| public boolean isDomainModel(Class domain) {
return domain.getCanonicalName().contains("knaptus");
}
|
diff --git a/tools/examplePackagerPlugin/src/main/java/org/overture/tools/maven/examplepackager/ExamplePackagerMojo.java b/tools/examplePackagerPlugin/src/main/java/org/overture/tools/maven/examplepackager/ExamplePackagerMojo.java
index 01e8f29bb5..efb4c6b326 100644
--- a/tools/examplePackagerPlugin/src/main/java/org/overture/tools/maven/examplepackager/ExamplePackagerMojo.java
+++ b/tools/examplePackagerPlugin/src/main/java/org/overture/tools/maven/examplepackager/ExamplePackagerMojo.java
@@ -1,145 +1,145 @@
package org.overture.tools.maven.examplepackager;
import java.io.File;
import java.util.List;
import java.util.Vector;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.overture.tools.examplepackager.Controller;
import org.overture.tools.examplepackager.Dialect;
/**
* Example Packager
*
*/
@Mojo(name="package-examples",
defaultPhase=LifecyclePhase.PROCESS_RESOURCES)
public class ExamplePackagerMojo extends AbstractMojo {
/**
* A boolean indicating whether example zips should be generated
*
*/
@Parameter(alias="output-zip")
protected boolean outputZipFiles = true;
/**
* A boolean indicating whether web pages should be generated
*
*/
@Parameter(alias="output-web")
protected boolean outputWebFiles = false;
/**
* A list of directories containing subdirectories with example
* VDM-SL projects. Note that the name of the output bundle will
* be derived from the name of the base directory.
*
*/
@Parameter(alias="slExamples")
protected List<File> exampleSLBaseDirectories;
/**
* A list of directories containing subdirectories with example
* VDM-PP projects. Note that the name of the output bundle will
* be derived from the name of the base directory.
*
*/
@Parameter(alias="ppExamples")
protected List<File> examplePPBaseDirectories;
/**
* A list of directories containing subdirectories with example
* VDM-RT projects. Note that the name of the output bundle will
* be derived from the name of the base directory.
*
*/
@Parameter(alias="rtExamples")
protected List<File> exampleRTBaseDirectories;
/**
* A prefix to the output zip filename.
*
*/
@Parameter(defaultValue="Examples-")
protected String outputPrefix;
/**
* Name of the directory into which the packaged examples will be
* placed. Readonly at the moment as the only place they should
* be dropped is in the project's usual target directory.
*/
@Parameter(defaultValue="${project.build.directory}")
protected File outputDirectory;
/**
* Location of the staging directory for the example packager.
*/
@Parameter(defaultValue="${project.build.directory}/generated-resources/example-packager", readonly=true)
protected File tmpdir;
private boolean overtureCSSWeb= true;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
File zipFile;
Controller controller;
List<Controller> controllers = new Vector<Controller>();
List<File> zipFiles = new Vector<File>();
for (File exampleDir : exampleSLBaseDirectories) {
zipFile = new File(outputDirectory, outputPrefix + exampleDir.getName() + ".zip");
zipFiles.add(zipFile);
controller = new Controller(Dialect.VDM_SL, exampleDir, outputDirectory, false);
controllers.add(controller);
controller.packExamples(new File(tmpdir, exampleDir.getName()), zipFile, !outputZipFiles);
if(outputWebFiles)
{
controller.createWebSite(overtureCSSWeb);
}
}
for (File exampleDir : examplePPBaseDirectories) {
zipFile = new File(outputDirectory, outputPrefix + exampleDir.getName() + ".zip");
zipFiles.add(zipFile);
controller = new Controller(Dialect.VDM_PP, exampleDir, outputDirectory, false);
controllers.add(controller);
controller.packExamples(new File(tmpdir, exampleDir.getName()), zipFile, !outputZipFiles);
if(outputWebFiles)
{
controller.createWebSite(overtureCSSWeb);
}
}
for (File exampleDir : exampleRTBaseDirectories) {
zipFile = new File(outputDirectory, outputPrefix + exampleDir.getName() + ".zip");
zipFiles.add(zipFile);
controller = new Controller(Dialect.VDM_RT, exampleDir, outputDirectory, false);
controllers.add(controller);
controller.packExamples(new File(tmpdir, exampleDir.getName()), zipFile, !outputZipFiles);
if(outputWebFiles)
{
controller.createWebSite(overtureCSSWeb);
}
}
- if(!controllers.isEmpty())
+ if(outputWebFiles && !controllers.isEmpty())
{
controllers.iterator().next().createWebOverviewPage(controllers, zipFiles,overtureCSSWeb);
}
}
}
| true | true | public void execute() throws MojoExecutionException, MojoFailureException {
File zipFile;
Controller controller;
List<Controller> controllers = new Vector<Controller>();
List<File> zipFiles = new Vector<File>();
for (File exampleDir : exampleSLBaseDirectories) {
zipFile = new File(outputDirectory, outputPrefix + exampleDir.getName() + ".zip");
zipFiles.add(zipFile);
controller = new Controller(Dialect.VDM_SL, exampleDir, outputDirectory, false);
controllers.add(controller);
controller.packExamples(new File(tmpdir, exampleDir.getName()), zipFile, !outputZipFiles);
if(outputWebFiles)
{
controller.createWebSite(overtureCSSWeb);
}
}
for (File exampleDir : examplePPBaseDirectories) {
zipFile = new File(outputDirectory, outputPrefix + exampleDir.getName() + ".zip");
zipFiles.add(zipFile);
controller = new Controller(Dialect.VDM_PP, exampleDir, outputDirectory, false);
controllers.add(controller);
controller.packExamples(new File(tmpdir, exampleDir.getName()), zipFile, !outputZipFiles);
if(outputWebFiles)
{
controller.createWebSite(overtureCSSWeb);
}
}
for (File exampleDir : exampleRTBaseDirectories) {
zipFile = new File(outputDirectory, outputPrefix + exampleDir.getName() + ".zip");
zipFiles.add(zipFile);
controller = new Controller(Dialect.VDM_RT, exampleDir, outputDirectory, false);
controllers.add(controller);
controller.packExamples(new File(tmpdir, exampleDir.getName()), zipFile, !outputZipFiles);
if(outputWebFiles)
{
controller.createWebSite(overtureCSSWeb);
}
}
if(!controllers.isEmpty())
{
controllers.iterator().next().createWebOverviewPage(controllers, zipFiles,overtureCSSWeb);
}
}
| public void execute() throws MojoExecutionException, MojoFailureException {
File zipFile;
Controller controller;
List<Controller> controllers = new Vector<Controller>();
List<File> zipFiles = new Vector<File>();
for (File exampleDir : exampleSLBaseDirectories) {
zipFile = new File(outputDirectory, outputPrefix + exampleDir.getName() + ".zip");
zipFiles.add(zipFile);
controller = new Controller(Dialect.VDM_SL, exampleDir, outputDirectory, false);
controllers.add(controller);
controller.packExamples(new File(tmpdir, exampleDir.getName()), zipFile, !outputZipFiles);
if(outputWebFiles)
{
controller.createWebSite(overtureCSSWeb);
}
}
for (File exampleDir : examplePPBaseDirectories) {
zipFile = new File(outputDirectory, outputPrefix + exampleDir.getName() + ".zip");
zipFiles.add(zipFile);
controller = new Controller(Dialect.VDM_PP, exampleDir, outputDirectory, false);
controllers.add(controller);
controller.packExamples(new File(tmpdir, exampleDir.getName()), zipFile, !outputZipFiles);
if(outputWebFiles)
{
controller.createWebSite(overtureCSSWeb);
}
}
for (File exampleDir : exampleRTBaseDirectories) {
zipFile = new File(outputDirectory, outputPrefix + exampleDir.getName() + ".zip");
zipFiles.add(zipFile);
controller = new Controller(Dialect.VDM_RT, exampleDir, outputDirectory, false);
controllers.add(controller);
controller.packExamples(new File(tmpdir, exampleDir.getName()), zipFile, !outputZipFiles);
if(outputWebFiles)
{
controller.createWebSite(overtureCSSWeb);
}
}
if(outputWebFiles && !controllers.isEmpty())
{
controllers.iterator().next().createWebOverviewPage(controllers, zipFiles,overtureCSSWeb);
}
}
|
diff --git a/stripes/src/net/sourceforge/stripes/validation/EmailTypeConverter.java b/stripes/src/net/sourceforge/stripes/validation/EmailTypeConverter.java
index 442cc79..423a29f 100644
--- a/stripes/src/net/sourceforge/stripes/validation/EmailTypeConverter.java
+++ b/stripes/src/net/sourceforge/stripes/validation/EmailTypeConverter.java
@@ -1,77 +1,77 @@
/* Copyright 2005-2006 Tim Fennell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sourceforge.stripes.validation;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import java.util.Collection;
import java.util.Locale;
/**
* <p>A faux TypeConverter that validates that the String supplied is a valid email address.
* Relies on javax.mail.internet.InternetAddress for the bulk of the work (note that this means
* in order to use this type converter you must have JavaMail available in your classpath).</p>
*
* <p>If the String cannot be parsed, or it represents a "local" address (one with no @domain) a
* single error message will be generated. The error message is a scoped message with a default
* scope of <tt>converter.email</tt> and name <tt>invalidEmail</tt>. As a result error messages
* will be looked for in the following order:</p>
*
* <ul>
* <li>beanClassFQN.fieldName.invalidEmail</li>
* <li>actionPath.fieldName.invalidEmail</li>
* <li>fieldName.invalidEmail</li>
* <li>beanClassFQN.invalidEmail</li>
* <li>actionPath.invalidEmail</li>
* <li>converter.email.invalidEmail</li>
* </ul>
*
* @author Tim Fennell
* @since Stripes 1.2
*/
public class EmailTypeConverter implements TypeConverter<String> {
/** Accepts the Locale provided, but does nothing with it since emails are Locale-less. */
public void setLocale(Locale locale) { /** Doesn't matter for email. */}
/**
* Validates the user input to ensure that it is a valid email address.
*
* @param input the String input, always a non-null non-empty String
* @param targetType realistically always String since java.lang.String is final
* @param errors a non-null collection of errors to populate in case of error
* @return the parsed address, or null if there are no errors. Note that the parsed address
* may be different from the input if extraneous characters were removed.
*/
public String convert(String input,
Class<? extends String> targetType,
Collection<ValidationError> errors) {
String result = null;
try {
- InternetAddress address = new InternetAddress(input);
+ InternetAddress address = new InternetAddress(input, true);
result = address.getAddress();
if (!result.contains("@")) {
result = null;
throw new AddressException();
}
}
catch (AddressException ae) {
errors.add( new ScopedLocalizableError("converter.email", "invalidEmail") );
}
return result;
}
}
| true | true | public String convert(String input,
Class<? extends String> targetType,
Collection<ValidationError> errors) {
String result = null;
try {
InternetAddress address = new InternetAddress(input);
result = address.getAddress();
if (!result.contains("@")) {
result = null;
throw new AddressException();
}
}
catch (AddressException ae) {
errors.add( new ScopedLocalizableError("converter.email", "invalidEmail") );
}
return result;
}
| public String convert(String input,
Class<? extends String> targetType,
Collection<ValidationError> errors) {
String result = null;
try {
InternetAddress address = new InternetAddress(input, true);
result = address.getAddress();
if (!result.contains("@")) {
result = null;
throw new AddressException();
}
}
catch (AddressException ae) {
errors.add( new ScopedLocalizableError("converter.email", "invalidEmail") );
}
return result;
}
|
diff --git a/modules/quality-test/src/main/java/net/sf/qualitytest/blueprint/BluePrint.java b/modules/quality-test/src/main/java/net/sf/qualitytest/blueprint/BluePrint.java
index d7a9d5b..0e0d49c 100644
--- a/modules/quality-test/src/main/java/net/sf/qualitytest/blueprint/BluePrint.java
+++ b/modules/quality-test/src/main/java/net/sf/qualitytest/blueprint/BluePrint.java
@@ -1,482 +1,482 @@
/*******************************************************************************
* Copyright 2013 Dominik Seichter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package net.sf.qualitytest.blueprint;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.util.Random;
import java.util.UUID;
import net.sf.qualitycheck.Check;
import net.sf.qualitycheck.Throws;
import net.sf.qualitycheck.exception.IllegalNullArgumentException;
import net.sf.qualitytest.ModifierBits;
import net.sf.qualitytest.blueprint.configuration.DefaultBluePrintConfiguration;
import net.sf.qualitytest.blueprint.configuration.RandomBluePrintConfiguration;
import net.sf.qualitytest.exception.BluePrintException;
/**
* Blueprinting is a technique that makes writing test easier. For unit-testing you often need data-objects, where the
* actual content of the objects does not matter. {@code BluePrint} creates data-objects filled with random or defined
* data automatically based on the "Blue-Print" which is the Class itself.
*
* Blueprinting makes tests more maintainable as they depend less on test-data. Imagine, you add a new required
* attribute to a class. Usually, you have to add this to all tests using this class. With blueprinting you just have to
* add it to certain tests where the contents of the logic does actually matter. Most of the time the randomly generated
* value by {@code BluePrint} is just fine.
*
* {@code BluePrint} is similar to C#'s AutoFixture (https://github.com/AutoFixture/AutoFixture#readme).
*
* A simple example:
*
* <code>
* final BluePrintConfiguration config = new RandomBluePrintConfiguration().with("email", "[email protected]");
* final User user = BluePrint.object(User.class, config);
* </code>
*
* or simpler
*
* <code>
* final User user = BluePrint.random().with("email", "[email protected]").object(User.class);
* </code>
*
* {@code BluePrint} offers to custome configurations. A {@code DefaultBluePrintConfiguration} which fills any object
* using default, empty or 0 values. The second configuration, {@code RandomBluePrintConfiguration} will always generate
* a random value. Both fill child objects using a deep-tree-search.
*
* Utilities for collections can be found in {@code CollectionBluePrint}.
*
* @see DefaultBluePrintConfiguration
* @see RandomBluePrintConfiguration
*
* @author Dominik Seichter
*
*/
public final class BluePrint {
private static final BluePrintConfiguration DEFAULT_CONFIG = new DefaultBluePrintConfiguration();
private static final int MAX_ARRAY_SIZE = 7;
private static final Random random = new Random();
private static final String SETTER_PREFIX = "set";
/**
* Blueprint an array value using a {@code DefaultBluePrintConfiguration}.
*
* This method will return an array with a random generated dimension between 1 and {@code BluePrint.MAX_ARRAY_SIZE
* + 1},
*
* @param <T>
* @param array
* the class of an array.
* @return a valid array.
*/
@Throws(IllegalNullArgumentException.class)
public static <T> Object array(final Class<T> array) {
return BluePrint.array(array, DEFAULT_CONFIG);
}
/**
* Blueprint an array value.
*
* This method will return an array with a random generated dimension between 1 and {@code BluePrint.MAX_ARRAY_SIZE
* + 1},
*
* @param <T>
* @param array
* the class of an array.
* @param config
* a {@code BluePrintConfiguration}
* @return a valid array.
*/
@Throws(IllegalNullArgumentException.class)
public static <T> Object array(final Class<T> array, final BluePrintConfiguration config) {
Check.notNull(array, "array");
Check.notNull(config, "config");
final int arraySize = random.nextInt(MAX_ARRAY_SIZE) + 1;
final Object value = Array.newInstance(array.getComponentType(), arraySize);
if (!array.getComponentType().isPrimitive()) {
initializeArray(array, arraySize, value, config);
}
return value;
}
/**
* Blueprint a Java-Bean.
*
* This method will call the default constructor and fill all setters using blueprints.
*
* @param <T>
* @param clazz
* a class, which must have a default constructor.
* @param config
* a BluePrintConfiguration
* @return a blue printed instance of {@code T}
*/
@Throws(IllegalNullArgumentException.class)
private static <T> T bean(final Class<T> clazz, final BluePrintConfiguration config) {
Check.notNull(clazz, "clazz");
Check.notNull(config, "config");
final T obj = safeNewInstance(clazz);
bluePrintSetters(obj, clazz, config);
return obj;
}
/**
* Blueprint a method.
*
* @param that
* Instance of the object
* @param m
* Setter-Method
* @param config
* configuration to use.
*/
private static void bluePrintMethod(final Object that, final Method m, final BluePrintConfiguration config) {
final ValueCreationStrategy<?> creator = config.findCreationStrategyForMethod(m);
final Class<?>[] parameterTypes = m.getParameterTypes();
final Object[] values = new Object[parameterTypes.length];
if (creator != null && parameterTypes.length == 1) {
values[0] = creator.createValue();
} else {
for (int i = 0; i < parameterTypes.length; i++) {
final Class<?> parameter = parameterTypes[i];
values[i] = object(parameter, config);
}
}
safeInvoke(that, m, values);
}
/**
* Blueprint all setters in an object.
*
* @param <T>
* type of object
* @param obj
* Instance of the object
* @param clazz
* Class of the object
* @param config
* Configuration to apply
*/
private static <T> void bluePrintSetters(final T obj, final Class<T> clazz, final BluePrintConfiguration config) {
for (final Method m : clazz.getMethods()) {
if (isSetter(m)) {
bluePrintMethod(obj, m, config);
}
}
}
/**
* Return a new configuration for default blueprinting with zero or empty default values.
*
* @return a new {@code DefaultBluePrintConfiguration}
*/
public static BluePrintConfiguration def() {
return new DefaultBluePrintConfiguration();
}
/**
* Blueprint an enum value.
*
* This method will return the first enum constant in the enumeration.
*
* @param <T>
* @param enumClazz
* the class of an enumeration.
* @return a valid enum value.
*/
public static <T extends Enum<T>> T enumeration(final Class<T> enumClazz) {
final T[] enumConstants = enumClazz.getEnumConstants();
return enumConstants.length > 0 ? enumConstants[0] : null;
}
/**
* Find the first public constructor in a class.
*
* @param <T>
* type parameter of the class and constructor.
* @param clazz
* the class object
*/
private static <T> Constructor<?> findFirstPublicConstructor(final Class<T> clazz) {
final Constructor<?>[] constructors = clazz.getConstructors();
for (final Constructor<?> c : constructors) {
final boolean isPublic = ModifierBits.isModifierBitSet(c.getModifiers(), Modifier.PUBLIC);
if (isPublic) {
return c;
}
}
return null;
}
/**
* Test if a class has a public default constructor (i.e. a public constructor without constructor arguments).
*
* @param clazz
* the class object.
* @return true if the class has a public default constructor.
*/
private static boolean hasPublicDefaultConstructor(final Class<?> clazz) {
final Constructor<?>[] constructors = clazz.getConstructors();
for (final Constructor<?> c : constructors) {
final boolean isPublic = ModifierBits.isModifierBitSet(c.getModifiers(), Modifier.PUBLIC);
if (isPublic && c.getParameterTypes().length == 0) {
return true;
}
}
return false;
}
/**
* Blueprint an immutable class based on the constructor parameters of the first public constructor.
*
* @param <T>
* type parameter of the blueprinted class
* @param clazz
* the class object
* @param config
* the configuration
* @return a new blueprint of the class with all constructor parameters to filled.
*/
private static <T> T immutable(final Class<T> clazz, final BluePrintConfiguration config) {
final Constructor<?> constructor = findFirstPublicConstructor(clazz);
final Class<?>[] parameterTypes = constructor.getParameterTypes();
final Object[] parameters = new Object[parameterTypes.length];
for (int i = 0; i < parameterTypes.length; i++) {
parameters[i] = object(parameterTypes[i], config);
}
final T obj = safeNewInstance(constructor, parameters);
bluePrintSetters(obj, clazz, config);
return obj;
}
/**
* Initalize an array using blueprinted objects.
*
* @param <T>
* Type parameter of the array.
* @param array
* class of the array
* @param arraySize
* size of the array
* @param value
* object where the array is stored
*/
private static <T> void initializeArray(final Class<T> array, final int arraySize, final Object value,
final BluePrintConfiguration config) {
for (int i = 0; i < arraySize; i++) {
final Object bluePrint = object(array.getComponentType(), config);
Array.set(value, i, bluePrint);
}
}
/**
* Check if a method is setter according to the java
*
* @param m
* a method
* @return true if this is a setter method
*/
protected static boolean isSetter(final Method m) {
final boolean isNotStatic = !ModifierBits.isModifierBitSet(m.getModifiers(), Modifier.STATIC);
final boolean isPublic = ModifierBits.isModifierBitSet(m.getModifiers(), Modifier.PUBLIC);
final boolean isSetterName = m.getName().startsWith(SETTER_PREFIX);
return isNotStatic && isPublic && isSetterName;
}
/**
* Blueprint a Java-Object using a {@code DefaultBluePrintConfiguration}.
*
* If the object has a default constructor, it will be called and all setters will be called. If the object does not
* have a default constructor the first constructor is called and filled with all parameters. Afterwards all setters
* will be called.
*
* @param <T>
* @param clazz
* a class
* @return a blue printed instance of {@code T}
*/
@Throws(IllegalNullArgumentException.class)
public static <T> T object(final Class<T> clazz) {
return BluePrint.object(clazz, DEFAULT_CONFIG);
}
/**
* Blueprint a Java-Object.
*
* If the object has a default constructor, it will be called and all setters will be called. If the object does not
* have a default constructor the first constructor is called and filled with all parameters. Afterwards all setters
* will be called.
*
* @param <T>
* @param clazz
* a class
* @param config
* a {@code BluePrintConfiguration}
* @return a blue printed instance of {@code T}
*/
@SuppressWarnings("unchecked")
@Throws(IllegalNullArgumentException.class)
public static <T> T object(final Class<T> clazz, final BluePrintConfiguration config) {
Check.notNull(clazz, "clazz");
Check.notNull(config, "config");
- final ValueCreationStrategy creator = config.findCreationStrategyForType(clazz);
+ final ValueCreationStrategy<?> creator = config.findCreationStrategyForType(clazz);
if (creator != null) {
return (T) creator.createValue();
} else if (clazz.isEnum()) {
return (T) enumeration((Class<Enum>) clazz);
} else if (clazz.isArray()) {
return (T) array(clazz, config);
} else if (clazz.isInterface()) {
return (T) proxy(clazz, config);
} else if (ModifierBits.isModifierBitSet(clazz.getModifiers(), Modifier.ABSTRACT)) {
throw new BluePrintException("Abstract classes are currently not supported.");
} else if (hasPublicDefaultConstructor(clazz)) {
return bean(clazz, config);
} else {
return immutable(clazz, config);
}
}
/**
* Create a proxy for an interface, which does nothing.
*
* @param <T>
* Class of the interface
* @param iface
* an interace
* @param config
* {@code BluePrintConfiguration}
* @return a new dynamic proxy
*/
@SuppressWarnings("unchecked")
private static <T> T proxy(final Class<T> iface, final BluePrintConfiguration config) {
return (T) Proxy.newProxyInstance(iface.getClassLoader(), new Class[] { iface }, new BluePrintInvocationHandler(config));
}
/**
* Return a new configuration for random blueprinting.
*
* @return a new {@code RandomBluePrintConfiguration}
*/
public static BluePrintConfiguration random() {
return new RandomBluePrintConfiguration();
}
/**
* Safely invoke a method on an object withot having to care about checked exceptions.
*
* @param that
* object
* @param m
* method
* @param values
* paramters
*
* @throws BluePrintException
* in case of any error
*/
private static void safeInvoke(final Object that, final Method m, final Object[] values) {
try {
m.invoke(that, values);
} catch (final IllegalArgumentException e) {
throw new BluePrintException(e);
} catch (final IllegalAccessException e) {
throw new BluePrintException(e);
} catch (final InvocationTargetException e) {
throw new BluePrintException(e);
}
}
/**
* Create a new instance of a class without having to care about the checked exceptions. The class must have an
* accessible default constructor.
*
* @param <T>
* type parameter of the class to create
* @param clazz
* class-object
* @return a new instance of the class
*
* @throws BluePrintException
* in case of any error
*/
private static <T> T safeNewInstance(final Class<T> clazz) {
try {
return (T) clazz.newInstance();
} catch (final InstantiationException e) {
throw new BluePrintException(e);
} catch (final IllegalAccessException e) {
throw new BluePrintException(e);
}
}
/**
* Create a new instance of a class without having to care about the checked exceptions using a given constructor.
*
* @param constructor
* constructor to call
* @param parameters
* constructor arguments
* @throws BluePrintException
* in case of any error
*/
@SuppressWarnings("unchecked")
private static <T> T safeNewInstance(final Constructor<?> constructor, final Object[] parameters) {
try {
return (T) constructor.newInstance(parameters);
} catch (final IllegalArgumentException e) {
throw new BluePrintException(e);
} catch (final InstantiationException e) {
throw new BluePrintException(e);
} catch (final IllegalAccessException e) {
throw new BluePrintException(e);
} catch (final InvocationTargetException e) {
throw new BluePrintException(e);
}
}
/**
* Create a new random string.
*
* @return a new randomly created string.
*/
public static String string() {
return UUID.randomUUID().toString();
}
/**
* <strong>Attention:</strong> This class is not intended to create objects from it.
*/
private BluePrint() {
// This class is not intended to create objects from it.
}
}
| true | true | public static <T> T object(final Class<T> clazz, final BluePrintConfiguration config) {
Check.notNull(clazz, "clazz");
Check.notNull(config, "config");
final ValueCreationStrategy creator = config.findCreationStrategyForType(clazz);
if (creator != null) {
return (T) creator.createValue();
} else if (clazz.isEnum()) {
return (T) enumeration((Class<Enum>) clazz);
} else if (clazz.isArray()) {
return (T) array(clazz, config);
} else if (clazz.isInterface()) {
return (T) proxy(clazz, config);
} else if (ModifierBits.isModifierBitSet(clazz.getModifiers(), Modifier.ABSTRACT)) {
throw new BluePrintException("Abstract classes are currently not supported.");
} else if (hasPublicDefaultConstructor(clazz)) {
return bean(clazz, config);
} else {
return immutable(clazz, config);
}
}
| public static <T> T object(final Class<T> clazz, final BluePrintConfiguration config) {
Check.notNull(clazz, "clazz");
Check.notNull(config, "config");
final ValueCreationStrategy<?> creator = config.findCreationStrategyForType(clazz);
if (creator != null) {
return (T) creator.createValue();
} else if (clazz.isEnum()) {
return (T) enumeration((Class<Enum>) clazz);
} else if (clazz.isArray()) {
return (T) array(clazz, config);
} else if (clazz.isInterface()) {
return (T) proxy(clazz, config);
} else if (ModifierBits.isModifierBitSet(clazz.getModifiers(), Modifier.ABSTRACT)) {
throw new BluePrintException("Abstract classes are currently not supported.");
} else if (hasPublicDefaultConstructor(clazz)) {
return bean(clazz, config);
} else {
return immutable(clazz, config);
}
}
|
diff --git a/management/shell/src/main/java/org/mobicents/ss7/management/console/Subject.java b/management/shell/src/main/java/org/mobicents/ss7/management/console/Subject.java
index 77b639185..4265c5ea3 100644
--- a/management/shell/src/main/java/org/mobicents/ss7/management/console/Subject.java
+++ b/management/shell/src/main/java/org/mobicents/ss7/management/console/Subject.java
@@ -1,53 +1,57 @@
package org.mobicents.ss7.management.console;
/**
* Represents the Subject of command formated as "subject <options>".
*
* @author amit bhayani
*
*/
public enum Subject {
/**
* linkset subject. Any command to manipulate the linkset, should begin with
* linkset subject
*/
LINKSET("linkset"),
SCCP("sccp"),
/**
* M3UA Subject. Any command to manage the M3UA should begin with m3ua
* subject
*/
M3UA("m3ua");
private String subject = null;
private Subject(String subject) {
this.subject = subject;
}
/**
* get the string representation of this subject enum
*
* @return
*/
public String getSubject() {
return subject;
}
/**
* get the corresponding enum for passed subject String. Returns null if
* there is no subject enum defined for passed subject string
*
* @param subject
* @return
*/
public static Subject getSubject(String subject) {
if (subject.compareTo(LINKSET.getSubject()) == 0) {
return LINKSET;
+ } else if (subject.compareTo(M3UA.getSubject()) == 0) {
+ return M3UA;
+ } else if (subject.compareTo(SCCP.getSubject()) == 0){
+ return SCCP;
}
return null;
}
}
| true | true | public static Subject getSubject(String subject) {
if (subject.compareTo(LINKSET.getSubject()) == 0) {
return LINKSET;
}
return null;
}
| public static Subject getSubject(String subject) {
if (subject.compareTo(LINKSET.getSubject()) == 0) {
return LINKSET;
} else if (subject.compareTo(M3UA.getSubject()) == 0) {
return M3UA;
} else if (subject.compareTo(SCCP.getSubject()) == 0){
return SCCP;
}
return null;
}
|
diff --git a/src/com/mahn42/anhalter42/circuit/CircuitHandler42M2003.java b/src/com/mahn42/anhalter42/circuit/CircuitHandler42M2003.java
index 4596a4e..1edad4b 100644
--- a/src/com/mahn42/anhalter42/circuit/CircuitHandler42M2003.java
+++ b/src/com/mahn42/anhalter42/circuit/CircuitHandler42M2003.java
@@ -1,47 +1,52 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.mahn42.anhalter42.circuit;
/**
*
* @author andre
*/
public class CircuitHandler42M2003 extends CircuitHandler {
public CircuitHandler42M2003() {
super("DFP4", "42M2003");
description = "3x3 Redstone Lamp Display 4 Input";
pins.add(CircuitHandler.PinMode.Input);
pins.add(CircuitHandler.PinMode.Input);
pins.add(CircuitHandler.PinMode.Input);
pins.add(CircuitHandler.PinMode.Input);
pins.addArea(CircuitHandler.PinMode.Output, "out", 3);
}
@Override
protected void tick() {
int lCode = getPinValueInt("pin1")
| (getPinValueInt("pin2") << 1)
| (getPinValueInt("pin3") << 2)
| (getPinValueInt("pin4") << 3);
CircuitFont.CircuitFontChar lChar;
if (fContext.circuit.signLine2 != null && !fContext.circuit.signLine2.isEmpty()) {
if (fContext.circuit.signLine2.length() > lCode) {
char lC = fContext.circuit.signLine2.charAt(lCode);
lChar = Circuit.plugin.configASCI_3.getChar("" + lC);
} else {
lChar = Circuit.plugin.configASCI_3.getChar(" ");
}
} else {
lChar = Circuit.plugin.configASCI_3.getChar(lCode);
}
- for(int lX = 1; lX <= 3; lX++) {
- for(int lY = 1; lY <= 3; lY++) {
- setPinInArea("out", lX, lY, lChar.getPixel(lX - 1, 3 - lY));
+ if (lChar == null) {
+ lChar = Circuit.plugin.configASCI_3.getChar(" ");
+ }
+ if (lChar != null) {
+ for(int lX = 1; lX <= 3; lX++) {
+ for(int lY = 1; lY <= 3; lY++) {
+ setPinInArea("out", lX, lY, lChar.getPixel(lX - 1, 3 - lY));
+ }
}
}
}
}
| true | true | protected void tick() {
int lCode = getPinValueInt("pin1")
| (getPinValueInt("pin2") << 1)
| (getPinValueInt("pin3") << 2)
| (getPinValueInt("pin4") << 3);
CircuitFont.CircuitFontChar lChar;
if (fContext.circuit.signLine2 != null && !fContext.circuit.signLine2.isEmpty()) {
if (fContext.circuit.signLine2.length() > lCode) {
char lC = fContext.circuit.signLine2.charAt(lCode);
lChar = Circuit.plugin.configASCI_3.getChar("" + lC);
} else {
lChar = Circuit.plugin.configASCI_3.getChar(" ");
}
} else {
lChar = Circuit.plugin.configASCI_3.getChar(lCode);
}
for(int lX = 1; lX <= 3; lX++) {
for(int lY = 1; lY <= 3; lY++) {
setPinInArea("out", lX, lY, lChar.getPixel(lX - 1, 3 - lY));
}
}
}
| protected void tick() {
int lCode = getPinValueInt("pin1")
| (getPinValueInt("pin2") << 1)
| (getPinValueInt("pin3") << 2)
| (getPinValueInt("pin4") << 3);
CircuitFont.CircuitFontChar lChar;
if (fContext.circuit.signLine2 != null && !fContext.circuit.signLine2.isEmpty()) {
if (fContext.circuit.signLine2.length() > lCode) {
char lC = fContext.circuit.signLine2.charAt(lCode);
lChar = Circuit.plugin.configASCI_3.getChar("" + lC);
} else {
lChar = Circuit.plugin.configASCI_3.getChar(" ");
}
} else {
lChar = Circuit.plugin.configASCI_3.getChar(lCode);
}
if (lChar == null) {
lChar = Circuit.plugin.configASCI_3.getChar(" ");
}
if (lChar != null) {
for(int lX = 1; lX <= 3; lX++) {
for(int lY = 1; lY <= 3; lY++) {
setPinInArea("out", lX, lY, lChar.getPixel(lX - 1, 3 - lY));
}
}
}
}
|
diff --git a/signserver/modules/SignServer-AdminCLI/src/org/signserver/cli/GenerateCertReqCommand.java b/signserver/modules/SignServer-AdminCLI/src/org/signserver/cli/GenerateCertReqCommand.java
index f18b47880..391519e44 100644
--- a/signserver/modules/SignServer-AdminCLI/src/org/signserver/cli/GenerateCertReqCommand.java
+++ b/signserver/modules/SignServer-AdminCLI/src/org/signserver/cli/GenerateCertReqCommand.java
@@ -1,131 +1,131 @@
/*************************************************************************
* *
* SignServer: The OpenSource Automated Signing Server *
* *
* This software 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 any later version. *
* *
* See terms of license at gnu.org. *
* *
*************************************************************************/
package org.signserver.cli;
import java.io.FileOutputStream;
import org.signserver.common.Base64SignerCertReqData;
import org.signserver.common.PKCS10CertReqInfo;
/**
* Commands that requests a signer to generate a PKCS10 certificate request
*
* @version $Id$
*/
public class GenerateCertReqCommand extends BaseCommand {
protected static final int HELP = 0;
protected static final int FAIL = 1;
protected static final int SUCCESS = 2;
/**
* Creates a new instance of SetPropertyCommand
*
* @param args command line arguments
*/
public GenerateCertReqCommand(String[] args) {
super(args);
}
/**
* Runs the command
*
* @throws IllegalAdminCommandException Error in command args
* @throws ErrorAdminCommandException Error running command
*/
protected void execute(String hostname, String[] resources) throws IllegalAdminCommandException, ErrorAdminCommandException {
if (args.length < 5 || args.length > 7) {
throw new IllegalAdminCommandException( resources[HELP]);
}
try{
final String workerid = args[1];
final String dn= args[2];
final String sigAlg = args[3];
final String filename = args[4];
- boolean defaultKey = false;
+ boolean defaultKey = true;
boolean explicitecc = false;
if (args.length > 5) {
if ("-nextkey".equals(args[5])) {
defaultKey = false;
} else if("-explicitecc".equals(args[5])) {
explicitecc = true;
} else {
throw new IllegalAdminCommandException(resources[HELP]);
}
if (args.length > 6) {
if ("-nextkey".equals(args[6])) {
defaultKey = false;
} else if("-explicitecc".equals(args[6])) {
explicitecc = true;
} else {
throw new IllegalAdminCommandException(resources[HELP]);
}
}
}
int id = 0;
if(workerid.substring(0, 1).matches("\\d")){
id = Integer.parseInt(workerid);
}else{
// named worker is requested
id = getCommonAdminInterface(hostname).getWorkerId(workerid);
if(id == 0){
throw new IllegalAdminCommandException(resources[FAIL]);
}
}
PKCS10CertReqInfo certReqInfo = new PKCS10CertReqInfo(sigAlg,dn,null);
Base64SignerCertReqData reqData
= (Base64SignerCertReqData) getCommonAdminInterface(hostname)
.genCertificateRequest(id, certReqInfo, explicitecc, defaultKey);
if (reqData == null) {
throw new Exception("Base64SignerCertReqData returned was null. Unable to generate certificate request.");
}
FileOutputStream fos = new FileOutputStream(filename);
fos.write("-----BEGIN CERTIFICATE REQUEST-----\n".getBytes());
fos.write(reqData.getBase64CertReq());
fos.write("\n-----END CERTIFICATE REQUEST-----\n".getBytes());
fos.close();
getOutputStream().println(resources[SUCCESS] + filename);
} catch (IllegalAdminCommandException e) {
throw e;
} catch (Exception e) {
throw new ErrorAdminCommandException(e);
}
}
public void execute(String hostname) throws IllegalAdminCommandException, ErrorAdminCommandException {
String[] resources = {"Usage: signserver generatecertreq <-host hostname (optional)> <workerid> <dn> <signature algorithm> <cert-req-filename> [-explicitecc] [-nextkey]\n" +
"Example: signserver generatecertreq 1 \"CN=TestCertReq\" \"SHA1WithRSA\" /home/user/certtreq.pem\n"
+ "Example: signserver generatecertreq 1 \"CN=TestCertReq\" \"SHA1WithRSA\" /home/user/certtreq.pem -nextkey\n"
+ "Example: signserver generatecertreq 1 \"CN=TestCertReq\" \"SHA1WithRSA\" /home/user/certtreq.pem -explicitecc\n"
+ "Example: signserver generatecertreq 1 \"CN=TestCertReq\" \"SHA1WithRSA\" /home/user/certtreq.pem -explicitecc -nextkey\n\n",
"Error: No worker with the given name could be found",
"PKCS10 Request successfully written to file "};
execute(hostname,resources);
}
public int getCommandType() {
return TYPE_EXECUTEONMASTER; // Not used
}
}
| true | true | protected void execute(String hostname, String[] resources) throws IllegalAdminCommandException, ErrorAdminCommandException {
if (args.length < 5 || args.length > 7) {
throw new IllegalAdminCommandException( resources[HELP]);
}
try{
final String workerid = args[1];
final String dn= args[2];
final String sigAlg = args[3];
final String filename = args[4];
boolean defaultKey = false;
boolean explicitecc = false;
if (args.length > 5) {
if ("-nextkey".equals(args[5])) {
defaultKey = false;
} else if("-explicitecc".equals(args[5])) {
explicitecc = true;
} else {
throw new IllegalAdminCommandException(resources[HELP]);
}
if (args.length > 6) {
if ("-nextkey".equals(args[6])) {
defaultKey = false;
} else if("-explicitecc".equals(args[6])) {
explicitecc = true;
} else {
throw new IllegalAdminCommandException(resources[HELP]);
}
}
}
int id = 0;
if(workerid.substring(0, 1).matches("\\d")){
id = Integer.parseInt(workerid);
}else{
// named worker is requested
id = getCommonAdminInterface(hostname).getWorkerId(workerid);
if(id == 0){
throw new IllegalAdminCommandException(resources[FAIL]);
}
}
PKCS10CertReqInfo certReqInfo = new PKCS10CertReqInfo(sigAlg,dn,null);
Base64SignerCertReqData reqData
= (Base64SignerCertReqData) getCommonAdminInterface(hostname)
.genCertificateRequest(id, certReqInfo, explicitecc, defaultKey);
if (reqData == null) {
throw new Exception("Base64SignerCertReqData returned was null. Unable to generate certificate request.");
}
FileOutputStream fos = new FileOutputStream(filename);
fos.write("-----BEGIN CERTIFICATE REQUEST-----\n".getBytes());
fos.write(reqData.getBase64CertReq());
fos.write("\n-----END CERTIFICATE REQUEST-----\n".getBytes());
fos.close();
getOutputStream().println(resources[SUCCESS] + filename);
} catch (IllegalAdminCommandException e) {
throw e;
} catch (Exception e) {
throw new ErrorAdminCommandException(e);
}
}
| protected void execute(String hostname, String[] resources) throws IllegalAdminCommandException, ErrorAdminCommandException {
if (args.length < 5 || args.length > 7) {
throw new IllegalAdminCommandException( resources[HELP]);
}
try{
final String workerid = args[1];
final String dn= args[2];
final String sigAlg = args[3];
final String filename = args[4];
boolean defaultKey = true;
boolean explicitecc = false;
if (args.length > 5) {
if ("-nextkey".equals(args[5])) {
defaultKey = false;
} else if("-explicitecc".equals(args[5])) {
explicitecc = true;
} else {
throw new IllegalAdminCommandException(resources[HELP]);
}
if (args.length > 6) {
if ("-nextkey".equals(args[6])) {
defaultKey = false;
} else if("-explicitecc".equals(args[6])) {
explicitecc = true;
} else {
throw new IllegalAdminCommandException(resources[HELP]);
}
}
}
int id = 0;
if(workerid.substring(0, 1).matches("\\d")){
id = Integer.parseInt(workerid);
}else{
// named worker is requested
id = getCommonAdminInterface(hostname).getWorkerId(workerid);
if(id == 0){
throw new IllegalAdminCommandException(resources[FAIL]);
}
}
PKCS10CertReqInfo certReqInfo = new PKCS10CertReqInfo(sigAlg,dn,null);
Base64SignerCertReqData reqData
= (Base64SignerCertReqData) getCommonAdminInterface(hostname)
.genCertificateRequest(id, certReqInfo, explicitecc, defaultKey);
if (reqData == null) {
throw new Exception("Base64SignerCertReqData returned was null. Unable to generate certificate request.");
}
FileOutputStream fos = new FileOutputStream(filename);
fos.write("-----BEGIN CERTIFICATE REQUEST-----\n".getBytes());
fos.write(reqData.getBase64CertReq());
fos.write("\n-----END CERTIFICATE REQUEST-----\n".getBytes());
fos.close();
getOutputStream().println(resources[SUCCESS] + filename);
} catch (IllegalAdminCommandException e) {
throw e;
} catch (Exception e) {
throw new ErrorAdminCommandException(e);
}
}
|
diff --git a/src/com/tautic/drawbotcontrol/DrawbotControlApplication.java b/src/com/tautic/drawbotcontrol/DrawbotControlApplication.java
index 5dcf937..cd7e4b3 100644
--- a/src/com/tautic/drawbotcontrol/DrawbotControlApplication.java
+++ b/src/com/tautic/drawbotcontrol/DrawbotControlApplication.java
@@ -1,541 +1,560 @@
/*
* Copyright (c) 2011 Jayson Tautic
*
* 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.tautic.drawbotcontrol;
import net.Network;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Scale;
import org.eclipse.swt.widgets.Label;
import org.eclipse.wb.swt.SWTResourceManager;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseMoveListener;
import gnu.io.*;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.widgets.Composite;
public class DrawbotControlApplication implements net.Network_iface {
protected Shell shell;
private Text textPages;
private Text textCharsPerPage;
private String portName;
private String portBaudRate = "9600";
private String fileName; //Name of the opened drawing file
static SerialPort serialPort;
private static net.Network network;
private Text text_1;
private Text textPaperHeight;
/**
* Launch the application.
* @param args
*/
public static void main(String[] args) {
try {
DrawbotControlApplication window = new DrawbotControlApplication();
network = new net.Network(0, new DrawbotControlApplication(), 255);
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Open the window.
*/
public void open() {
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
shell.addListener(SWT.Dispose, new Listener() {
@Override
public void handleEvent(Event event) {
if (network.isConnected()) network.disconnect(); //If our port is open, close it.
}
});
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
*/
protected void createContents() {
shell = new Shell();
shell.setSize(623, 729);
shell.setText("Drawbot Control - v2.0");
shell.setLayout(null);
Menu menu = new Menu(shell, SWT.BAR);
shell.setMenuBar(menu);
MenuItem mntmFile = new MenuItem(menu, SWT.CASCADE);
mntmFile.setText("F&ile");
Menu menu_1 = new Menu(mntmFile);
mntmFile.setMenu(menu_1);
MenuItem mntmopenDrawing = new MenuItem(menu_1, SWT.NONE);
mntmopenDrawing.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
//Open Drawing menu item
FileDialog fd = new FileDialog(shell, SWT.OPEN);
fd.setText("Open Drawing File");
String[] filterExtensions = {"*.dbi"};
fd.setFilterExtensions(filterExtensions);
fileName = fd.open();
System.out.println(fileName);
}
});
mntmopenDrawing.setText("&Open Drawing");
new MenuItem(menu_1, SWT.SEPARATOR);
MenuItem mntmExit = new MenuItem(menu_1, SWT.NONE);
mntmExit.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
shell.dispose(); // exit the application
}
});
mntmExit.setText("E&xit");
MenuItem mntmTools = new MenuItem(menu, SWT.CASCADE);
mntmTools.setText("T&ools");
Menu menu_2 = new Menu(mntmTools);
mntmTools.setMenu(menu_2);
MenuItem mntmPort = new MenuItem(menu_2, SWT.CASCADE);
mntmPort.setText("Port");
Menu menu_3 = new Menu(mntmPort);
mntmPort.setMenu(menu_3);
MenuItem mntmBaudRate = new MenuItem(menu_2, SWT.CASCADE);
mntmBaudRate.setText("Baud Rate");
Menu menu_4 = new Menu(mntmBaudRate);
mntmBaudRate.setMenu(menu_4);
MenuItem baud9600 = new MenuItem(menu_4, SWT.CHECK);
baud9600.setSelection(true);
baud9600.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
portBaudRate = "9600";
}
});
baud9600.setText("9600");
MenuItem baud38400 = new MenuItem(menu_4, SWT.CHECK);
baud38400.setText("38400");
MenuItem baud115200 = new MenuItem(menu_4, SWT.CHECK);
baud115200.setText("115200");
new MenuItem(menu_2, SWT.SEPARATOR);
MenuItem mntmClearMemory = new MenuItem(menu_2, SWT.NONE);
mntmClearMemory.setText("Clear Memory");
Canvas canvas = new Canvas(shell, SWT.NONE);
canvas.setBackground(SWTResourceManager.getColor(SWT.COLOR_DARK_GRAY));
canvas.setBounds(382, 27, 200, 200);
Group grpSerialPortSelect = new Group(shell, SWT.NONE);
grpSerialPortSelect.setForeground(SWTResourceManager.getColor(SWT.COLOR_TITLE_BACKGROUND));
grpSerialPortSelect.setFont(SWTResourceManager.getFont("Lucida Grande", 11, SWT.NORMAL));
grpSerialPortSelect.setText("Serial Port Select");
grpSerialPortSelect.setBounds(10, 10, 348, 52);
final Combo comboPorts = new Combo(grpSerialPortSelect, SWT.NONE);
comboPorts.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
portName = comboPorts.getText(); //set variable to selected port name.
}
});
comboPorts.setBounds(84, 18, 248, 22);
Label lblPort = new Label(grpSerialPortSelect, SWT.NONE);
lblPort.setText("Port:");
lblPort.setBounds(8, 22, 59, 14);
Group grpImageFileSettings = new Group(shell, SWT.NONE);
grpImageFileSettings.setForeground(SWTResourceManager.getColor(SWT.COLOR_TITLE_BACKGROUND));
grpImageFileSettings.setFont(SWTResourceManager.getFont("Lucida Grande", 11, SWT.NORMAL));
grpImageFileSettings.setText("Image File Settings");
- grpImageFileSettings.setBounds(10, 68, 348, 254);
+ grpImageFileSettings.setBounds(10, 407, 348, 254);
Label lblCharsPerPage = new Label(grpImageFileSettings, SWT.NONE);
lblCharsPerPage.setBounds(20, 224, 87, 18);
lblCharsPerPage.setText("Bytes Per Page:");
textCharsPerPage = new Text(grpImageFileSettings, SWT.BORDER);
textCharsPerPage.setBounds(113, 221, 64, 19);
textCharsPerPage.setText("128");
Label lblPenType = new Label(grpImageFileSettings, SWT.NONE);
lblPenType.setBounds(20, 191, 55, 15);
lblPenType.setText("Pen Type:");
Spinner spinnerPenType = new Spinner(grpImageFileSettings, SWT.BORDER);
spinnerPenType.setEnabled(false);
spinnerPenType.setBounds(111, 184, 47, 22);
Label lblDrawingDelay1 = new Label(grpImageFileSettings, SWT.NONE);
lblDrawingDelay1.setBounds(20, 146, 88, 14);
lblDrawingDelay1.setText("Drawing Delay:");
Scale scaleDrawingDelay = new Scale(grpImageFileSettings, SWT.NONE);
scaleDrawingDelay.setEnabled(false);
scaleDrawingDelay.setBounds(113, 135, 192, 42);
scaleDrawingDelay.setMaximum(127);
scaleDrawingDelay.setMinimum(1);
scaleDrawingDelay.setSelection(64);
Label lblDrawingDelay = new Label(grpImageFileSettings, SWT.NONE);
lblDrawingDelay.setEnabled(false);
lblDrawingDelay.setBounds(305, 144, 33, 19);
lblDrawingDelay.setText("64");
lblDrawingDelay.setFont(SWTResourceManager.getFont("Lucida Grande", 12, SWT.NORMAL));
final Label lblDrawingSpeed = new Label(grpImageFileSettings, SWT.NONE);
lblDrawingSpeed.setBounds(305, 96, 33, 19);
lblDrawingSpeed.setFont(SWTResourceManager.getFont("Lucida Grande", 12, SWT.NORMAL));
lblDrawingSpeed.setText("64");
final Scale scaleDrawingSpeed = new Scale(grpImageFileSettings, SWT.NONE);
scaleDrawingSpeed.setBounds(113, 87, 192, 42);
scaleDrawingSpeed.addMouseMoveListener(new MouseMoveListener() {
@Override
public void mouseMove(MouseEvent arg0) {
lblDrawingSpeed.setText(Integer.toString(scaleDrawingSpeed.getSelection()));
}
});
scaleDrawingSpeed.setMaximum(127);
scaleDrawingSpeed.setMinimum(1);
scaleDrawingSpeed.setSelection(64);
Label lblCaddySpeed = new Label(grpImageFileSettings, SWT.NONE);
lblCaddySpeed.setBounds(20, 98, 88, 14);
lblCaddySpeed.setText("Drawing Speed:");
Button btnCaddySet = new Button(grpImageFileSettings, SWT.NONE);
btnCaddySet.setBounds(277, 217, 61, 28);
btnCaddySet.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
String scaleAmount = String.valueOf((char)scaleDrawingSpeed.getSelection());
sendCommand("]" + scaleAmount);
System.out.println(scaleAmount);
}
});
btnCaddySet.setText("Set");
Label lblPaperWidth = new Label(grpImageFileSettings, SWT.NONE);
lblPaperWidth.setText("Paper Width:");
lblPaperWidth.setBounds(20, 30, 87, 18);
text_1 = new Text(grpImageFileSettings, SWT.BORDER);
text_1.setEnabled(false);
text_1.setText("18");
text_1.setBounds(113, 27, 64, 19);
Label lblPaperHeight = new Label(grpImageFileSettings, SWT.NONE);
lblPaperHeight.setText("Paper Height:");
lblPaperHeight.setBounds(20, 57, 87, 18);
textPaperHeight = new Text(grpImageFileSettings, SWT.BORDER);
textPaperHeight.setEnabled(false);
textPaperHeight.setText("24");
textPaperHeight.setBounds(113, 54, 64, 19);
Group grpTrimStepper = new Group(shell, SWT.NONE);
grpTrimStepper.setForeground(SWTResourceManager.getColor(SWT.COLOR_TITLE_BACKGROUND));
grpTrimStepper.setFont(SWTResourceManager.getFont("Lucida Grande", 11, SWT.NORMAL));
grpTrimStepper.setText("Trim");
- grpTrimStepper.setBounds(8, 328, 348, 333);
+ grpTrimStepper.setBounds(10, 68, 348, 333);
TabFolder tabFolder_1 = new TabFolder(grpTrimStepper, SWT.NONE);
tabFolder_1.setBounds(10, 24, 328, 299);
TabItem tbtmSteppersTab = new TabItem(tabFolder_1, SWT.NONE);
tbtmSteppersTab.setText("Steppers");
Composite composite_2 = new Composite(tabFolder_1, SWT.NONE);
composite_2.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_BACKGROUND));
tbtmSteppersTab.setControl(composite_2);
Label lblLeftStepper = new Label(composite_2, SWT.NONE);
lblLeftStepper.setBounds(76, 15, 190, 14);
lblLeftStepper.setAlignment(SWT.CENTER);
lblLeftStepper.setText("Left Stepper");
Label lblFine = new Label(composite_2, SWT.NONE);
lblFine.setBounds(9, 60, 58, 14);
lblFine.setText("Fine:");
Button btnLeftUpFine = new Button(composite_2, SWT.NONE);
btnLeftUpFine.setBounds(76, 43, 94, 28);
btnLeftUpFine.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("a"); //Up Left Fine
}
});
btnLeftUpFine.setText("UP");
Button btnRightUpFine = new Button(composite_2, SWT.NONE);
btnRightUpFine.setBounds(76, 75, 94, 28);
btnRightUpFine.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("d");
}
});
btnRightUpFine.setText("UP");
Button btnLeftDownFine = new Button(composite_2, SWT.NONE);
btnLeftDownFine.setBounds(176, 43, 94, 28);
btnLeftDownFine.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("s");
}
});
btnLeftDownFine.setText("DOWN");
Button btnRightDownFine = new Button(composite_2, SWT.NONE);
btnRightDownFine.setBounds(176, 75, 94, 28);
btnRightDownFine.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("f");
}
});
btnRightDownFine.setText("DOWN");
Label lblRightStepper = new Label(composite_2, SWT.NONE);
lblRightStepper.setBounds(77, 117, 190, 14);
lblRightStepper.setText("Right Stepper");
lblRightStepper.setAlignment(SWT.CENTER);
Label label = new Label(composite_2, SWT.SEPARATOR | SWT.HORIZONTAL);
label.setBounds(0, 136, 330, 2);
Label label_1 = new Label(composite_2, SWT.NONE);
label_1.setBounds(75, 141, 190, 14);
label_1.setText("Left Stepper");
label_1.setAlignment(SWT.CENTER);
Label lblCoarse = new Label(composite_2, SWT.NONE);
lblCoarse.setBounds(10, 179, 47, 14);
lblCoarse.setText("Coarse:");
Button btnLeftUpCoarse = new Button(composite_2, SWT.NONE);
btnLeftUpCoarse.setBounds(75, 167, 94, 28);
btnLeftUpCoarse.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("q");
}
});
btnLeftUpCoarse.setText("UP");
Button btnRightUpCoarse = new Button(composite_2, SWT.NONE);
btnRightUpCoarse.setBounds(75, 198, 94, 28);
btnRightUpCoarse.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("e");
}
});
btnRightUpCoarse.setText("UP");
Button btnLeftDownCoarse = new Button(composite_2, SWT.NONE);
btnLeftDownCoarse.setBounds(175, 167, 94, 28);
btnLeftDownCoarse.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("w");
}
});
btnLeftDownCoarse.setText("DOWN");
Button btnRightDownCoarse = new Button(composite_2, SWT.NONE);
btnRightDownCoarse.setBounds(175, 198, 94, 28);
btnRightDownCoarse.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("r");
}
});
btnRightDownCoarse.setText("DOWN");
Label label_2 = new Label(composite_2, SWT.NONE);
label_2.setBounds(74, 238, 190, 14);
label_2.setText("Right Stepper");
label_2.setAlignment(SWT.CENTER);
TabItem tbtmCaddyTab = new TabItem(tabFolder_1, SWT.NONE);
tbtmCaddyTab.setText("Caddy");
Composite composite_3 = new Composite(tabFolder_1, SWT.NONE);
composite_3.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_BACKGROUND));
tbtmCaddyTab.setControl(composite_3);
Button btnUp = new Button(composite_3, SWT.NONE);
btnUp.setBounds(130, 85, 61, 28);
btnUp.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("g");
}
});
btnUp.setText("UP");
Button btnLeft = new Button(composite_3, SWT.NONE);
btnLeft.setBounds(44, 120, 61, 28);
btnLeft.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("j");
}
});
btnLeft.setText("LEFT");
Button btnDown = new Button(composite_3, SWT.NONE);
btnDown.setBounds(130, 154, 61, 28);
btnDown.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("h");
}
});
btnDown.setText("DOWN");
Button btnRight = new Button(composite_3, SWT.NONE);
btnRight.setBounds(211, 120, 61, 28);
btnRight.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("k");
}
});
btnRight.setText("RIGHT");
Button btnStart = new Button(shell, SWT.NONE);
+ btnStart.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ sendCommand("p");
+ }
+ });
btnStart.setBounds(376, 267, 68, 28);
btnStart.setText("Start");
Button btnPause = new Button(shell, SWT.NONE);
+ btnPause.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ sendCommand("p");
+ }
+ });
btnPause.setBounds(450, 267, 68, 28);
btnPause.setText("Pause");
Button btnResume = new Button(shell, SWT.NONE);
+ btnResume.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ sendCommand("a");
+ }
+ });
btnResume.setBounds(524, 267, 68, 28);
btnResume.setText("Resume");
Button btnUpload = new Button(shell, SWT.NONE);
btnUpload.setBounds(407, 233, 75, 25);
btnUpload.setText("Upload");
Button btnDownload = new Button(shell, SWT.NONE);
btnDownload.setEnabled(false);
btnDownload.setBounds(488, 233, 75, 25);
btnDownload.setText("Download");
Label lblPages = new Label(shell, SWT.NONE);
lblPages.setBounds(435, 634, 59, 14);
lblPages.setText("Pages:");
textPages = new Text(shell, SWT.BORDER);
+ textPages.setEnabled(false);
textPages.setBounds(518, 631, 64, 19);
textPages.setText("128");
//Get available ports on system
@SuppressWarnings("unchecked")
java.util.Enumeration<CommPortIdentifier> portEnum = CommPortIdentifier.getPortIdentifiers();
while ( portEnum.hasMoreElements())
{
CommPortIdentifier portIdentifier = portEnum.nextElement();
if (portIdentifier.getPortType() == CommPortIdentifier.PORT_SERIAL) comboPorts.add(portIdentifier.getName());
}
}
@Override
public void writeLog(int id, String text) {
// TODO Auto-generated method stub
System.out.println(text);
}
@Override
public void parseInput(int id, int numBytes, int[] message) {
// TODO Auto-generated method stub
}
@Override
public void networkDisconnected(int id) {
// TODO Auto-generated method stub
}
public void sendCommand(String cmd){
try {
if (portName != null && portName != "") {
if (!network.isConnected()) network.connect(portName, Integer.parseInt(portBaudRate)); //open the selected port if not already open
network.writeSerial(cmd); //Send to port
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
| false | true | protected void createContents() {
shell = new Shell();
shell.setSize(623, 729);
shell.setText("Drawbot Control - v2.0");
shell.setLayout(null);
Menu menu = new Menu(shell, SWT.BAR);
shell.setMenuBar(menu);
MenuItem mntmFile = new MenuItem(menu, SWT.CASCADE);
mntmFile.setText("F&ile");
Menu menu_1 = new Menu(mntmFile);
mntmFile.setMenu(menu_1);
MenuItem mntmopenDrawing = new MenuItem(menu_1, SWT.NONE);
mntmopenDrawing.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
//Open Drawing menu item
FileDialog fd = new FileDialog(shell, SWT.OPEN);
fd.setText("Open Drawing File");
String[] filterExtensions = {"*.dbi"};
fd.setFilterExtensions(filterExtensions);
fileName = fd.open();
System.out.println(fileName);
}
});
mntmopenDrawing.setText("&Open Drawing");
new MenuItem(menu_1, SWT.SEPARATOR);
MenuItem mntmExit = new MenuItem(menu_1, SWT.NONE);
mntmExit.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
shell.dispose(); // exit the application
}
});
mntmExit.setText("E&xit");
MenuItem mntmTools = new MenuItem(menu, SWT.CASCADE);
mntmTools.setText("T&ools");
Menu menu_2 = new Menu(mntmTools);
mntmTools.setMenu(menu_2);
MenuItem mntmPort = new MenuItem(menu_2, SWT.CASCADE);
mntmPort.setText("Port");
Menu menu_3 = new Menu(mntmPort);
mntmPort.setMenu(menu_3);
MenuItem mntmBaudRate = new MenuItem(menu_2, SWT.CASCADE);
mntmBaudRate.setText("Baud Rate");
Menu menu_4 = new Menu(mntmBaudRate);
mntmBaudRate.setMenu(menu_4);
MenuItem baud9600 = new MenuItem(menu_4, SWT.CHECK);
baud9600.setSelection(true);
baud9600.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
portBaudRate = "9600";
}
});
baud9600.setText("9600");
MenuItem baud38400 = new MenuItem(menu_4, SWT.CHECK);
baud38400.setText("38400");
MenuItem baud115200 = new MenuItem(menu_4, SWT.CHECK);
baud115200.setText("115200");
new MenuItem(menu_2, SWT.SEPARATOR);
MenuItem mntmClearMemory = new MenuItem(menu_2, SWT.NONE);
mntmClearMemory.setText("Clear Memory");
Canvas canvas = new Canvas(shell, SWT.NONE);
canvas.setBackground(SWTResourceManager.getColor(SWT.COLOR_DARK_GRAY));
canvas.setBounds(382, 27, 200, 200);
Group grpSerialPortSelect = new Group(shell, SWT.NONE);
grpSerialPortSelect.setForeground(SWTResourceManager.getColor(SWT.COLOR_TITLE_BACKGROUND));
grpSerialPortSelect.setFont(SWTResourceManager.getFont("Lucida Grande", 11, SWT.NORMAL));
grpSerialPortSelect.setText("Serial Port Select");
grpSerialPortSelect.setBounds(10, 10, 348, 52);
final Combo comboPorts = new Combo(grpSerialPortSelect, SWT.NONE);
comboPorts.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
portName = comboPorts.getText(); //set variable to selected port name.
}
});
comboPorts.setBounds(84, 18, 248, 22);
Label lblPort = new Label(grpSerialPortSelect, SWT.NONE);
lblPort.setText("Port:");
lblPort.setBounds(8, 22, 59, 14);
Group grpImageFileSettings = new Group(shell, SWT.NONE);
grpImageFileSettings.setForeground(SWTResourceManager.getColor(SWT.COLOR_TITLE_BACKGROUND));
grpImageFileSettings.setFont(SWTResourceManager.getFont("Lucida Grande", 11, SWT.NORMAL));
grpImageFileSettings.setText("Image File Settings");
grpImageFileSettings.setBounds(10, 68, 348, 254);
Label lblCharsPerPage = new Label(grpImageFileSettings, SWT.NONE);
lblCharsPerPage.setBounds(20, 224, 87, 18);
lblCharsPerPage.setText("Bytes Per Page:");
textCharsPerPage = new Text(grpImageFileSettings, SWT.BORDER);
textCharsPerPage.setBounds(113, 221, 64, 19);
textCharsPerPage.setText("128");
Label lblPenType = new Label(grpImageFileSettings, SWT.NONE);
lblPenType.setBounds(20, 191, 55, 15);
lblPenType.setText("Pen Type:");
Spinner spinnerPenType = new Spinner(grpImageFileSettings, SWT.BORDER);
spinnerPenType.setEnabled(false);
spinnerPenType.setBounds(111, 184, 47, 22);
Label lblDrawingDelay1 = new Label(grpImageFileSettings, SWT.NONE);
lblDrawingDelay1.setBounds(20, 146, 88, 14);
lblDrawingDelay1.setText("Drawing Delay:");
Scale scaleDrawingDelay = new Scale(grpImageFileSettings, SWT.NONE);
scaleDrawingDelay.setEnabled(false);
scaleDrawingDelay.setBounds(113, 135, 192, 42);
scaleDrawingDelay.setMaximum(127);
scaleDrawingDelay.setMinimum(1);
scaleDrawingDelay.setSelection(64);
Label lblDrawingDelay = new Label(grpImageFileSettings, SWT.NONE);
lblDrawingDelay.setEnabled(false);
lblDrawingDelay.setBounds(305, 144, 33, 19);
lblDrawingDelay.setText("64");
lblDrawingDelay.setFont(SWTResourceManager.getFont("Lucida Grande", 12, SWT.NORMAL));
final Label lblDrawingSpeed = new Label(grpImageFileSettings, SWT.NONE);
lblDrawingSpeed.setBounds(305, 96, 33, 19);
lblDrawingSpeed.setFont(SWTResourceManager.getFont("Lucida Grande", 12, SWT.NORMAL));
lblDrawingSpeed.setText("64");
final Scale scaleDrawingSpeed = new Scale(grpImageFileSettings, SWT.NONE);
scaleDrawingSpeed.setBounds(113, 87, 192, 42);
scaleDrawingSpeed.addMouseMoveListener(new MouseMoveListener() {
@Override
public void mouseMove(MouseEvent arg0) {
lblDrawingSpeed.setText(Integer.toString(scaleDrawingSpeed.getSelection()));
}
});
scaleDrawingSpeed.setMaximum(127);
scaleDrawingSpeed.setMinimum(1);
scaleDrawingSpeed.setSelection(64);
Label lblCaddySpeed = new Label(grpImageFileSettings, SWT.NONE);
lblCaddySpeed.setBounds(20, 98, 88, 14);
lblCaddySpeed.setText("Drawing Speed:");
Button btnCaddySet = new Button(grpImageFileSettings, SWT.NONE);
btnCaddySet.setBounds(277, 217, 61, 28);
btnCaddySet.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
String scaleAmount = String.valueOf((char)scaleDrawingSpeed.getSelection());
sendCommand("]" + scaleAmount);
System.out.println(scaleAmount);
}
});
btnCaddySet.setText("Set");
Label lblPaperWidth = new Label(grpImageFileSettings, SWT.NONE);
lblPaperWidth.setText("Paper Width:");
lblPaperWidth.setBounds(20, 30, 87, 18);
text_1 = new Text(grpImageFileSettings, SWT.BORDER);
text_1.setEnabled(false);
text_1.setText("18");
text_1.setBounds(113, 27, 64, 19);
Label lblPaperHeight = new Label(grpImageFileSettings, SWT.NONE);
lblPaperHeight.setText("Paper Height:");
lblPaperHeight.setBounds(20, 57, 87, 18);
textPaperHeight = new Text(grpImageFileSettings, SWT.BORDER);
textPaperHeight.setEnabled(false);
textPaperHeight.setText("24");
textPaperHeight.setBounds(113, 54, 64, 19);
Group grpTrimStepper = new Group(shell, SWT.NONE);
grpTrimStepper.setForeground(SWTResourceManager.getColor(SWT.COLOR_TITLE_BACKGROUND));
grpTrimStepper.setFont(SWTResourceManager.getFont("Lucida Grande", 11, SWT.NORMAL));
grpTrimStepper.setText("Trim");
grpTrimStepper.setBounds(8, 328, 348, 333);
TabFolder tabFolder_1 = new TabFolder(grpTrimStepper, SWT.NONE);
tabFolder_1.setBounds(10, 24, 328, 299);
TabItem tbtmSteppersTab = new TabItem(tabFolder_1, SWT.NONE);
tbtmSteppersTab.setText("Steppers");
Composite composite_2 = new Composite(tabFolder_1, SWT.NONE);
composite_2.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_BACKGROUND));
tbtmSteppersTab.setControl(composite_2);
Label lblLeftStepper = new Label(composite_2, SWT.NONE);
lblLeftStepper.setBounds(76, 15, 190, 14);
lblLeftStepper.setAlignment(SWT.CENTER);
lblLeftStepper.setText("Left Stepper");
Label lblFine = new Label(composite_2, SWT.NONE);
lblFine.setBounds(9, 60, 58, 14);
lblFine.setText("Fine:");
Button btnLeftUpFine = new Button(composite_2, SWT.NONE);
btnLeftUpFine.setBounds(76, 43, 94, 28);
btnLeftUpFine.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("a"); //Up Left Fine
}
});
btnLeftUpFine.setText("UP");
Button btnRightUpFine = new Button(composite_2, SWT.NONE);
btnRightUpFine.setBounds(76, 75, 94, 28);
btnRightUpFine.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("d");
}
});
btnRightUpFine.setText("UP");
Button btnLeftDownFine = new Button(composite_2, SWT.NONE);
btnLeftDownFine.setBounds(176, 43, 94, 28);
btnLeftDownFine.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("s");
}
});
btnLeftDownFine.setText("DOWN");
Button btnRightDownFine = new Button(composite_2, SWT.NONE);
btnRightDownFine.setBounds(176, 75, 94, 28);
btnRightDownFine.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("f");
}
});
btnRightDownFine.setText("DOWN");
Label lblRightStepper = new Label(composite_2, SWT.NONE);
lblRightStepper.setBounds(77, 117, 190, 14);
lblRightStepper.setText("Right Stepper");
lblRightStepper.setAlignment(SWT.CENTER);
Label label = new Label(composite_2, SWT.SEPARATOR | SWT.HORIZONTAL);
label.setBounds(0, 136, 330, 2);
Label label_1 = new Label(composite_2, SWT.NONE);
label_1.setBounds(75, 141, 190, 14);
label_1.setText("Left Stepper");
label_1.setAlignment(SWT.CENTER);
Label lblCoarse = new Label(composite_2, SWT.NONE);
lblCoarse.setBounds(10, 179, 47, 14);
lblCoarse.setText("Coarse:");
Button btnLeftUpCoarse = new Button(composite_2, SWT.NONE);
btnLeftUpCoarse.setBounds(75, 167, 94, 28);
btnLeftUpCoarse.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("q");
}
});
btnLeftUpCoarse.setText("UP");
Button btnRightUpCoarse = new Button(composite_2, SWT.NONE);
btnRightUpCoarse.setBounds(75, 198, 94, 28);
btnRightUpCoarse.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("e");
}
});
btnRightUpCoarse.setText("UP");
Button btnLeftDownCoarse = new Button(composite_2, SWT.NONE);
btnLeftDownCoarse.setBounds(175, 167, 94, 28);
btnLeftDownCoarse.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("w");
}
});
btnLeftDownCoarse.setText("DOWN");
Button btnRightDownCoarse = new Button(composite_2, SWT.NONE);
btnRightDownCoarse.setBounds(175, 198, 94, 28);
btnRightDownCoarse.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("r");
}
});
btnRightDownCoarse.setText("DOWN");
Label label_2 = new Label(composite_2, SWT.NONE);
label_2.setBounds(74, 238, 190, 14);
label_2.setText("Right Stepper");
label_2.setAlignment(SWT.CENTER);
TabItem tbtmCaddyTab = new TabItem(tabFolder_1, SWT.NONE);
tbtmCaddyTab.setText("Caddy");
Composite composite_3 = new Composite(tabFolder_1, SWT.NONE);
composite_3.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_BACKGROUND));
tbtmCaddyTab.setControl(composite_3);
Button btnUp = new Button(composite_3, SWT.NONE);
btnUp.setBounds(130, 85, 61, 28);
btnUp.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("g");
}
});
btnUp.setText("UP");
Button btnLeft = new Button(composite_3, SWT.NONE);
btnLeft.setBounds(44, 120, 61, 28);
btnLeft.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("j");
}
});
btnLeft.setText("LEFT");
Button btnDown = new Button(composite_3, SWT.NONE);
btnDown.setBounds(130, 154, 61, 28);
btnDown.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("h");
}
});
btnDown.setText("DOWN");
Button btnRight = new Button(composite_3, SWT.NONE);
btnRight.setBounds(211, 120, 61, 28);
btnRight.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("k");
}
});
btnRight.setText("RIGHT");
Button btnStart = new Button(shell, SWT.NONE);
btnStart.setBounds(376, 267, 68, 28);
btnStart.setText("Start");
Button btnPause = new Button(shell, SWT.NONE);
btnPause.setBounds(450, 267, 68, 28);
btnPause.setText("Pause");
Button btnResume = new Button(shell, SWT.NONE);
btnResume.setBounds(524, 267, 68, 28);
btnResume.setText("Resume");
Button btnUpload = new Button(shell, SWT.NONE);
btnUpload.setBounds(407, 233, 75, 25);
btnUpload.setText("Upload");
Button btnDownload = new Button(shell, SWT.NONE);
btnDownload.setEnabled(false);
btnDownload.setBounds(488, 233, 75, 25);
btnDownload.setText("Download");
Label lblPages = new Label(shell, SWT.NONE);
lblPages.setBounds(435, 634, 59, 14);
lblPages.setText("Pages:");
textPages = new Text(shell, SWT.BORDER);
textPages.setBounds(518, 631, 64, 19);
textPages.setText("128");
//Get available ports on system
@SuppressWarnings("unchecked")
java.util.Enumeration<CommPortIdentifier> portEnum = CommPortIdentifier.getPortIdentifiers();
while ( portEnum.hasMoreElements())
{
CommPortIdentifier portIdentifier = portEnum.nextElement();
if (portIdentifier.getPortType() == CommPortIdentifier.PORT_SERIAL) comboPorts.add(portIdentifier.getName());
}
}
| protected void createContents() {
shell = new Shell();
shell.setSize(623, 729);
shell.setText("Drawbot Control - v2.0");
shell.setLayout(null);
Menu menu = new Menu(shell, SWT.BAR);
shell.setMenuBar(menu);
MenuItem mntmFile = new MenuItem(menu, SWT.CASCADE);
mntmFile.setText("F&ile");
Menu menu_1 = new Menu(mntmFile);
mntmFile.setMenu(menu_1);
MenuItem mntmopenDrawing = new MenuItem(menu_1, SWT.NONE);
mntmopenDrawing.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
//Open Drawing menu item
FileDialog fd = new FileDialog(shell, SWT.OPEN);
fd.setText("Open Drawing File");
String[] filterExtensions = {"*.dbi"};
fd.setFilterExtensions(filterExtensions);
fileName = fd.open();
System.out.println(fileName);
}
});
mntmopenDrawing.setText("&Open Drawing");
new MenuItem(menu_1, SWT.SEPARATOR);
MenuItem mntmExit = new MenuItem(menu_1, SWT.NONE);
mntmExit.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
shell.dispose(); // exit the application
}
});
mntmExit.setText("E&xit");
MenuItem mntmTools = new MenuItem(menu, SWT.CASCADE);
mntmTools.setText("T&ools");
Menu menu_2 = new Menu(mntmTools);
mntmTools.setMenu(menu_2);
MenuItem mntmPort = new MenuItem(menu_2, SWT.CASCADE);
mntmPort.setText("Port");
Menu menu_3 = new Menu(mntmPort);
mntmPort.setMenu(menu_3);
MenuItem mntmBaudRate = new MenuItem(menu_2, SWT.CASCADE);
mntmBaudRate.setText("Baud Rate");
Menu menu_4 = new Menu(mntmBaudRate);
mntmBaudRate.setMenu(menu_4);
MenuItem baud9600 = new MenuItem(menu_4, SWT.CHECK);
baud9600.setSelection(true);
baud9600.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
portBaudRate = "9600";
}
});
baud9600.setText("9600");
MenuItem baud38400 = new MenuItem(menu_4, SWT.CHECK);
baud38400.setText("38400");
MenuItem baud115200 = new MenuItem(menu_4, SWT.CHECK);
baud115200.setText("115200");
new MenuItem(menu_2, SWT.SEPARATOR);
MenuItem mntmClearMemory = new MenuItem(menu_2, SWT.NONE);
mntmClearMemory.setText("Clear Memory");
Canvas canvas = new Canvas(shell, SWT.NONE);
canvas.setBackground(SWTResourceManager.getColor(SWT.COLOR_DARK_GRAY));
canvas.setBounds(382, 27, 200, 200);
Group grpSerialPortSelect = new Group(shell, SWT.NONE);
grpSerialPortSelect.setForeground(SWTResourceManager.getColor(SWT.COLOR_TITLE_BACKGROUND));
grpSerialPortSelect.setFont(SWTResourceManager.getFont("Lucida Grande", 11, SWT.NORMAL));
grpSerialPortSelect.setText("Serial Port Select");
grpSerialPortSelect.setBounds(10, 10, 348, 52);
final Combo comboPorts = new Combo(grpSerialPortSelect, SWT.NONE);
comboPorts.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
portName = comboPorts.getText(); //set variable to selected port name.
}
});
comboPorts.setBounds(84, 18, 248, 22);
Label lblPort = new Label(grpSerialPortSelect, SWT.NONE);
lblPort.setText("Port:");
lblPort.setBounds(8, 22, 59, 14);
Group grpImageFileSettings = new Group(shell, SWT.NONE);
grpImageFileSettings.setForeground(SWTResourceManager.getColor(SWT.COLOR_TITLE_BACKGROUND));
grpImageFileSettings.setFont(SWTResourceManager.getFont("Lucida Grande", 11, SWT.NORMAL));
grpImageFileSettings.setText("Image File Settings");
grpImageFileSettings.setBounds(10, 407, 348, 254);
Label lblCharsPerPage = new Label(grpImageFileSettings, SWT.NONE);
lblCharsPerPage.setBounds(20, 224, 87, 18);
lblCharsPerPage.setText("Bytes Per Page:");
textCharsPerPage = new Text(grpImageFileSettings, SWT.BORDER);
textCharsPerPage.setBounds(113, 221, 64, 19);
textCharsPerPage.setText("128");
Label lblPenType = new Label(grpImageFileSettings, SWT.NONE);
lblPenType.setBounds(20, 191, 55, 15);
lblPenType.setText("Pen Type:");
Spinner spinnerPenType = new Spinner(grpImageFileSettings, SWT.BORDER);
spinnerPenType.setEnabled(false);
spinnerPenType.setBounds(111, 184, 47, 22);
Label lblDrawingDelay1 = new Label(grpImageFileSettings, SWT.NONE);
lblDrawingDelay1.setBounds(20, 146, 88, 14);
lblDrawingDelay1.setText("Drawing Delay:");
Scale scaleDrawingDelay = new Scale(grpImageFileSettings, SWT.NONE);
scaleDrawingDelay.setEnabled(false);
scaleDrawingDelay.setBounds(113, 135, 192, 42);
scaleDrawingDelay.setMaximum(127);
scaleDrawingDelay.setMinimum(1);
scaleDrawingDelay.setSelection(64);
Label lblDrawingDelay = new Label(grpImageFileSettings, SWT.NONE);
lblDrawingDelay.setEnabled(false);
lblDrawingDelay.setBounds(305, 144, 33, 19);
lblDrawingDelay.setText("64");
lblDrawingDelay.setFont(SWTResourceManager.getFont("Lucida Grande", 12, SWT.NORMAL));
final Label lblDrawingSpeed = new Label(grpImageFileSettings, SWT.NONE);
lblDrawingSpeed.setBounds(305, 96, 33, 19);
lblDrawingSpeed.setFont(SWTResourceManager.getFont("Lucida Grande", 12, SWT.NORMAL));
lblDrawingSpeed.setText("64");
final Scale scaleDrawingSpeed = new Scale(grpImageFileSettings, SWT.NONE);
scaleDrawingSpeed.setBounds(113, 87, 192, 42);
scaleDrawingSpeed.addMouseMoveListener(new MouseMoveListener() {
@Override
public void mouseMove(MouseEvent arg0) {
lblDrawingSpeed.setText(Integer.toString(scaleDrawingSpeed.getSelection()));
}
});
scaleDrawingSpeed.setMaximum(127);
scaleDrawingSpeed.setMinimum(1);
scaleDrawingSpeed.setSelection(64);
Label lblCaddySpeed = new Label(grpImageFileSettings, SWT.NONE);
lblCaddySpeed.setBounds(20, 98, 88, 14);
lblCaddySpeed.setText("Drawing Speed:");
Button btnCaddySet = new Button(grpImageFileSettings, SWT.NONE);
btnCaddySet.setBounds(277, 217, 61, 28);
btnCaddySet.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
String scaleAmount = String.valueOf((char)scaleDrawingSpeed.getSelection());
sendCommand("]" + scaleAmount);
System.out.println(scaleAmount);
}
});
btnCaddySet.setText("Set");
Label lblPaperWidth = new Label(grpImageFileSettings, SWT.NONE);
lblPaperWidth.setText("Paper Width:");
lblPaperWidth.setBounds(20, 30, 87, 18);
text_1 = new Text(grpImageFileSettings, SWT.BORDER);
text_1.setEnabled(false);
text_1.setText("18");
text_1.setBounds(113, 27, 64, 19);
Label lblPaperHeight = new Label(grpImageFileSettings, SWT.NONE);
lblPaperHeight.setText("Paper Height:");
lblPaperHeight.setBounds(20, 57, 87, 18);
textPaperHeight = new Text(grpImageFileSettings, SWT.BORDER);
textPaperHeight.setEnabled(false);
textPaperHeight.setText("24");
textPaperHeight.setBounds(113, 54, 64, 19);
Group grpTrimStepper = new Group(shell, SWT.NONE);
grpTrimStepper.setForeground(SWTResourceManager.getColor(SWT.COLOR_TITLE_BACKGROUND));
grpTrimStepper.setFont(SWTResourceManager.getFont("Lucida Grande", 11, SWT.NORMAL));
grpTrimStepper.setText("Trim");
grpTrimStepper.setBounds(10, 68, 348, 333);
TabFolder tabFolder_1 = new TabFolder(grpTrimStepper, SWT.NONE);
tabFolder_1.setBounds(10, 24, 328, 299);
TabItem tbtmSteppersTab = new TabItem(tabFolder_1, SWT.NONE);
tbtmSteppersTab.setText("Steppers");
Composite composite_2 = new Composite(tabFolder_1, SWT.NONE);
composite_2.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_BACKGROUND));
tbtmSteppersTab.setControl(composite_2);
Label lblLeftStepper = new Label(composite_2, SWT.NONE);
lblLeftStepper.setBounds(76, 15, 190, 14);
lblLeftStepper.setAlignment(SWT.CENTER);
lblLeftStepper.setText("Left Stepper");
Label lblFine = new Label(composite_2, SWT.NONE);
lblFine.setBounds(9, 60, 58, 14);
lblFine.setText("Fine:");
Button btnLeftUpFine = new Button(composite_2, SWT.NONE);
btnLeftUpFine.setBounds(76, 43, 94, 28);
btnLeftUpFine.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("a"); //Up Left Fine
}
});
btnLeftUpFine.setText("UP");
Button btnRightUpFine = new Button(composite_2, SWT.NONE);
btnRightUpFine.setBounds(76, 75, 94, 28);
btnRightUpFine.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("d");
}
});
btnRightUpFine.setText("UP");
Button btnLeftDownFine = new Button(composite_2, SWT.NONE);
btnLeftDownFine.setBounds(176, 43, 94, 28);
btnLeftDownFine.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("s");
}
});
btnLeftDownFine.setText("DOWN");
Button btnRightDownFine = new Button(composite_2, SWT.NONE);
btnRightDownFine.setBounds(176, 75, 94, 28);
btnRightDownFine.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("f");
}
});
btnRightDownFine.setText("DOWN");
Label lblRightStepper = new Label(composite_2, SWT.NONE);
lblRightStepper.setBounds(77, 117, 190, 14);
lblRightStepper.setText("Right Stepper");
lblRightStepper.setAlignment(SWT.CENTER);
Label label = new Label(composite_2, SWT.SEPARATOR | SWT.HORIZONTAL);
label.setBounds(0, 136, 330, 2);
Label label_1 = new Label(composite_2, SWT.NONE);
label_1.setBounds(75, 141, 190, 14);
label_1.setText("Left Stepper");
label_1.setAlignment(SWT.CENTER);
Label lblCoarse = new Label(composite_2, SWT.NONE);
lblCoarse.setBounds(10, 179, 47, 14);
lblCoarse.setText("Coarse:");
Button btnLeftUpCoarse = new Button(composite_2, SWT.NONE);
btnLeftUpCoarse.setBounds(75, 167, 94, 28);
btnLeftUpCoarse.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("q");
}
});
btnLeftUpCoarse.setText("UP");
Button btnRightUpCoarse = new Button(composite_2, SWT.NONE);
btnRightUpCoarse.setBounds(75, 198, 94, 28);
btnRightUpCoarse.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("e");
}
});
btnRightUpCoarse.setText("UP");
Button btnLeftDownCoarse = new Button(composite_2, SWT.NONE);
btnLeftDownCoarse.setBounds(175, 167, 94, 28);
btnLeftDownCoarse.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("w");
}
});
btnLeftDownCoarse.setText("DOWN");
Button btnRightDownCoarse = new Button(composite_2, SWT.NONE);
btnRightDownCoarse.setBounds(175, 198, 94, 28);
btnRightDownCoarse.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("r");
}
});
btnRightDownCoarse.setText("DOWN");
Label label_2 = new Label(composite_2, SWT.NONE);
label_2.setBounds(74, 238, 190, 14);
label_2.setText("Right Stepper");
label_2.setAlignment(SWT.CENTER);
TabItem tbtmCaddyTab = new TabItem(tabFolder_1, SWT.NONE);
tbtmCaddyTab.setText("Caddy");
Composite composite_3 = new Composite(tabFolder_1, SWT.NONE);
composite_3.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_BACKGROUND));
tbtmCaddyTab.setControl(composite_3);
Button btnUp = new Button(composite_3, SWT.NONE);
btnUp.setBounds(130, 85, 61, 28);
btnUp.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("g");
}
});
btnUp.setText("UP");
Button btnLeft = new Button(composite_3, SWT.NONE);
btnLeft.setBounds(44, 120, 61, 28);
btnLeft.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("j");
}
});
btnLeft.setText("LEFT");
Button btnDown = new Button(composite_3, SWT.NONE);
btnDown.setBounds(130, 154, 61, 28);
btnDown.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("h");
}
});
btnDown.setText("DOWN");
Button btnRight = new Button(composite_3, SWT.NONE);
btnRight.setBounds(211, 120, 61, 28);
btnRight.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("k");
}
});
btnRight.setText("RIGHT");
Button btnStart = new Button(shell, SWT.NONE);
btnStart.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("p");
}
});
btnStart.setBounds(376, 267, 68, 28);
btnStart.setText("Start");
Button btnPause = new Button(shell, SWT.NONE);
btnPause.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("p");
}
});
btnPause.setBounds(450, 267, 68, 28);
btnPause.setText("Pause");
Button btnResume = new Button(shell, SWT.NONE);
btnResume.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sendCommand("a");
}
});
btnResume.setBounds(524, 267, 68, 28);
btnResume.setText("Resume");
Button btnUpload = new Button(shell, SWT.NONE);
btnUpload.setBounds(407, 233, 75, 25);
btnUpload.setText("Upload");
Button btnDownload = new Button(shell, SWT.NONE);
btnDownload.setEnabled(false);
btnDownload.setBounds(488, 233, 75, 25);
btnDownload.setText("Download");
Label lblPages = new Label(shell, SWT.NONE);
lblPages.setBounds(435, 634, 59, 14);
lblPages.setText("Pages:");
textPages = new Text(shell, SWT.BORDER);
textPages.setEnabled(false);
textPages.setBounds(518, 631, 64, 19);
textPages.setText("128");
//Get available ports on system
@SuppressWarnings("unchecked")
java.util.Enumeration<CommPortIdentifier> portEnum = CommPortIdentifier.getPortIdentifiers();
while ( portEnum.hasMoreElements())
{
CommPortIdentifier portIdentifier = portEnum.nextElement();
if (portIdentifier.getPortType() == CommPortIdentifier.PORT_SERIAL) comboPorts.add(portIdentifier.getName());
}
}
|
diff --git a/sslr-core/src/main/java/com/sonar/sslr/impl/analysis/GrammarAnalyserStream.java b/sslr-core/src/main/java/com/sonar/sslr/impl/analysis/GrammarAnalyserStream.java
index 1f6ae15b..9b19b271 100644
--- a/sslr-core/src/main/java/com/sonar/sslr/impl/analysis/GrammarAnalyserStream.java
+++ b/sslr-core/src/main/java/com/sonar/sslr/impl/analysis/GrammarAnalyserStream.java
@@ -1,68 +1,68 @@
/*
* Copyright (C) 2010 SonarSource SA
* All rights reserved
* mailto:contact AT sonarsource DOT com
*/
package com.sonar.sslr.impl.analysis;
import com.sonar.sslr.impl.matcher.MatcherTreePrinter;
import com.sonar.sslr.impl.matcher.OneToNMatcher;
import com.sonar.sslr.impl.matcher.RuleMatcher;
import java.io.PrintStream;
public class GrammarAnalyserStream {
private GrammarAnalyserStream() {
}
public static void print(GrammarAnalyser analyser, PrintStream stream) {
System.out.println("Issues by rule:");
System.out.println("---------------");
System.out.println();
for (RuleMatcher rule : analyser.getRules()) {
if (analyser.hasIssues(rule)) {
System.out.println(rule.getName() + ": *** NOK ***");
if (analyser.isSkipped(rule)) {
Exception e = analyser.getSkippedCause(rule);
System.out.println("\tSkipped because of exception: \"" + e.toString() + "\"");
} else if (analyser.isLeftRecursive(rule)) {
LeftRecursionException e = analyser.getLeftRecursionException(rule);
System.out.println("\tThis rule is left recursive!");
System.out.println("\tStack trace:");
System.out.println(e.getRulesStackTrace());
} else if (analyser.isDependingOnLeftRecursiveRule(rule)) {
LeftRecursionException e = analyser.getLeftRecursionException(rule);
System.out.println("\tThis rule depends on the left recursive rule \"" + e.getLeftRecursiveRule().getName() + "\"");
} else {
if (analyser.hasEmptyRepetitions(rule)) {
System.out.println("\tThis rule contains the following empty repetitions, which lead to infinite loops:");
for (OneToNMatcher matcher : analyser.getEmptyRepetitions(rule)) {
System.out.println("\t\t" + MatcherTreePrinter.print(matcher));
}
System.out.println();
}
- if (analyser.hasEmptyRepetitions(rule)) {
+ if (analyser.hasEmptyAlternatives(rule)) {
System.out.println("\tThis rule contains the following empty alternatives, which lead to dead grammar parts:");
for (EmptyAlternative emptyAlternative : analyser.getEmptyAlternatives(rule)) {
System.out.println("\t\tAlternative " + MatcherTreePrinter.print(emptyAlternative.getAlternative()) + " in "
+ MatcherTreePrinter.print(emptyAlternative.getOrMatcher()));
}
System.out.println();
}
}
}
}
System.out.println();
System.out.println("End of issues by rule");
System.out.println();
}
}
| true | true | public static void print(GrammarAnalyser analyser, PrintStream stream) {
System.out.println("Issues by rule:");
System.out.println("---------------");
System.out.println();
for (RuleMatcher rule : analyser.getRules()) {
if (analyser.hasIssues(rule)) {
System.out.println(rule.getName() + ": *** NOK ***");
if (analyser.isSkipped(rule)) {
Exception e = analyser.getSkippedCause(rule);
System.out.println("\tSkipped because of exception: \"" + e.toString() + "\"");
} else if (analyser.isLeftRecursive(rule)) {
LeftRecursionException e = analyser.getLeftRecursionException(rule);
System.out.println("\tThis rule is left recursive!");
System.out.println("\tStack trace:");
System.out.println(e.getRulesStackTrace());
} else if (analyser.isDependingOnLeftRecursiveRule(rule)) {
LeftRecursionException e = analyser.getLeftRecursionException(rule);
System.out.println("\tThis rule depends on the left recursive rule \"" + e.getLeftRecursiveRule().getName() + "\"");
} else {
if (analyser.hasEmptyRepetitions(rule)) {
System.out.println("\tThis rule contains the following empty repetitions, which lead to infinite loops:");
for (OneToNMatcher matcher : analyser.getEmptyRepetitions(rule)) {
System.out.println("\t\t" + MatcherTreePrinter.print(matcher));
}
System.out.println();
}
if (analyser.hasEmptyRepetitions(rule)) {
System.out.println("\tThis rule contains the following empty alternatives, which lead to dead grammar parts:");
for (EmptyAlternative emptyAlternative : analyser.getEmptyAlternatives(rule)) {
System.out.println("\t\tAlternative " + MatcherTreePrinter.print(emptyAlternative.getAlternative()) + " in "
+ MatcherTreePrinter.print(emptyAlternative.getOrMatcher()));
}
System.out.println();
}
}
}
}
System.out.println();
System.out.println("End of issues by rule");
System.out.println();
}
| public static void print(GrammarAnalyser analyser, PrintStream stream) {
System.out.println("Issues by rule:");
System.out.println("---------------");
System.out.println();
for (RuleMatcher rule : analyser.getRules()) {
if (analyser.hasIssues(rule)) {
System.out.println(rule.getName() + ": *** NOK ***");
if (analyser.isSkipped(rule)) {
Exception e = analyser.getSkippedCause(rule);
System.out.println("\tSkipped because of exception: \"" + e.toString() + "\"");
} else if (analyser.isLeftRecursive(rule)) {
LeftRecursionException e = analyser.getLeftRecursionException(rule);
System.out.println("\tThis rule is left recursive!");
System.out.println("\tStack trace:");
System.out.println(e.getRulesStackTrace());
} else if (analyser.isDependingOnLeftRecursiveRule(rule)) {
LeftRecursionException e = analyser.getLeftRecursionException(rule);
System.out.println("\tThis rule depends on the left recursive rule \"" + e.getLeftRecursiveRule().getName() + "\"");
} else {
if (analyser.hasEmptyRepetitions(rule)) {
System.out.println("\tThis rule contains the following empty repetitions, which lead to infinite loops:");
for (OneToNMatcher matcher : analyser.getEmptyRepetitions(rule)) {
System.out.println("\t\t" + MatcherTreePrinter.print(matcher));
}
System.out.println();
}
if (analyser.hasEmptyAlternatives(rule)) {
System.out.println("\tThis rule contains the following empty alternatives, which lead to dead grammar parts:");
for (EmptyAlternative emptyAlternative : analyser.getEmptyAlternatives(rule)) {
System.out.println("\t\tAlternative " + MatcherTreePrinter.print(emptyAlternative.getAlternative()) + " in "
+ MatcherTreePrinter.print(emptyAlternative.getOrMatcher()));
}
System.out.println();
}
}
}
}
System.out.println();
System.out.println("End of issues by rule");
System.out.println();
}
|
diff --git a/src/com/jpii/navalbattle/renderer/weather/WeatherManager.java b/src/com/jpii/navalbattle/renderer/weather/WeatherManager.java
index 8450a70e..4bada770 100644
--- a/src/com/jpii/navalbattle/renderer/weather/WeatherManager.java
+++ b/src/com/jpii/navalbattle/renderer/weather/WeatherManager.java
@@ -1,109 +1,110 @@
package com.jpii.navalbattle.renderer.weather;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import com.jpii.navalbattle.pavo.Game;
import com.jpii.navalbattle.pavo.PavoHelper;
public class WeatherManager {
WeatherMode wm;
BufferedImage buffer;
RainDrop[] rain;
public WeatherManager() {
wm = WeatherMode.Sunny;
repopulateRain();
}
public void setWeather(WeatherMode wm) {
this.wm = wm;
update();
}
public WeatherMode getWeather() {
return wm;
}
private void repopulateRain() {
rain = new RainDrop[Game.Settings.rand.nextInt(150,200)];
int dir = Game.Settings.rand.nextInt(-6,6);
for (int r = 0; r < rain.length; r++) {
rain[r] = new RainDrop(dir,Game.Settings.currentWidth,Game.Settings.currentHeight);
}
}
private int lightticks = 0;
private boolean lighting = false;
public void update() {
if (getWeather() == WeatherMode.Raining) {
buffer = new BufferedImage(Game.Settings.currentWidth,
Game.Settings.currentHeight,BufferedImage.TYPE_INT_ARGB);
Graphics2D g = PavoHelper.createGraphics(buffer);
g.setStroke(new BasicStroke(2.5f));
lightticks += 1;
if (lightticks > 9) {
lightticks = 0;
lighting = false;
}
if (lighting) {
g.setColor(new Color(237,234,222,lightticks*100/9));
g.fillOval(Game.Settings.currentWidth-125,-Game.Settings.currentHeight,500,Game.Settings.currentHeight*2);
}
if (Game.Settings.rand.nextInt(0,30) == 10 && !lighting) {
lighting = true;
lightticks = 0;
}
for (int r = 0; r < rain.length; r++) {
RainDrop rd = rain[r];
int inc = rd.length / 5;
int sws = rd.dir;
rd.y1 += inc;
rd.y2 += inc;
rd.x1 += sws;
rd.x2 += sws;
rd.x1 += prefixx;
rd.x2 += prefixx;
rd.y1 += prefixy;
rd.y2 += prefixy;
if (rd.y1 > Game.Settings.currentHeight) {
rd.y1 -= (Game.Settings.currentHeight + 60);
rd.y2 -= (Game.Settings.currentHeight + 60);
}
if (sws < 0 && rd.x2 < 0) {
rd.x1 += Game.Settings.currentWidth;
rd.x2 += Game.Settings.currentWidth;
}
if (sws > 0 && rd.x1 > Game.Settings.currentWidth) {
rd.x1 -= Game.Settings.currentWidth;
rd.x2 -= Game.Settings.currentWidth;
}
if (prefixx > 0 && rd.x1 > Game.Settings.currentWidth) {
rd.x1 -= Game.Settings.currentWidth;
rd.x2 -= Game.Settings.currentWidth;
}
if (prefixx < 0 && rd.x1 < 0) {
rd.x1 += Game.Settings.currentWidth;
rd.x2 += Game.Settings.currentWidth;
}
rain[r] = rd;
g.setColor(rd.colour);
g.drawLine(rd.x1,rd.y1,rd.x2,rd.y2);
}
prefixx = 0;
prefixy = 0;
+ g.dispose();
}
else
buffer = null;
}
public BufferedImage getBuffer() {
if (getWeather() == WeatherMode.Sunny)
return null;
else
return buffer;
}
int prefixx = 0;
int prefixy = 0;
public void applyFix(int x, int y) {
prefixx = x;
prefixy = y;
}
}
| true | true | public void update() {
if (getWeather() == WeatherMode.Raining) {
buffer = new BufferedImage(Game.Settings.currentWidth,
Game.Settings.currentHeight,BufferedImage.TYPE_INT_ARGB);
Graphics2D g = PavoHelper.createGraphics(buffer);
g.setStroke(new BasicStroke(2.5f));
lightticks += 1;
if (lightticks > 9) {
lightticks = 0;
lighting = false;
}
if (lighting) {
g.setColor(new Color(237,234,222,lightticks*100/9));
g.fillOval(Game.Settings.currentWidth-125,-Game.Settings.currentHeight,500,Game.Settings.currentHeight*2);
}
if (Game.Settings.rand.nextInt(0,30) == 10 && !lighting) {
lighting = true;
lightticks = 0;
}
for (int r = 0; r < rain.length; r++) {
RainDrop rd = rain[r];
int inc = rd.length / 5;
int sws = rd.dir;
rd.y1 += inc;
rd.y2 += inc;
rd.x1 += sws;
rd.x2 += sws;
rd.x1 += prefixx;
rd.x2 += prefixx;
rd.y1 += prefixy;
rd.y2 += prefixy;
if (rd.y1 > Game.Settings.currentHeight) {
rd.y1 -= (Game.Settings.currentHeight + 60);
rd.y2 -= (Game.Settings.currentHeight + 60);
}
if (sws < 0 && rd.x2 < 0) {
rd.x1 += Game.Settings.currentWidth;
rd.x2 += Game.Settings.currentWidth;
}
if (sws > 0 && rd.x1 > Game.Settings.currentWidth) {
rd.x1 -= Game.Settings.currentWidth;
rd.x2 -= Game.Settings.currentWidth;
}
if (prefixx > 0 && rd.x1 > Game.Settings.currentWidth) {
rd.x1 -= Game.Settings.currentWidth;
rd.x2 -= Game.Settings.currentWidth;
}
if (prefixx < 0 && rd.x1 < 0) {
rd.x1 += Game.Settings.currentWidth;
rd.x2 += Game.Settings.currentWidth;
}
rain[r] = rd;
g.setColor(rd.colour);
g.drawLine(rd.x1,rd.y1,rd.x2,rd.y2);
}
prefixx = 0;
prefixy = 0;
}
else
buffer = null;
}
| public void update() {
if (getWeather() == WeatherMode.Raining) {
buffer = new BufferedImage(Game.Settings.currentWidth,
Game.Settings.currentHeight,BufferedImage.TYPE_INT_ARGB);
Graphics2D g = PavoHelper.createGraphics(buffer);
g.setStroke(new BasicStroke(2.5f));
lightticks += 1;
if (lightticks > 9) {
lightticks = 0;
lighting = false;
}
if (lighting) {
g.setColor(new Color(237,234,222,lightticks*100/9));
g.fillOval(Game.Settings.currentWidth-125,-Game.Settings.currentHeight,500,Game.Settings.currentHeight*2);
}
if (Game.Settings.rand.nextInt(0,30) == 10 && !lighting) {
lighting = true;
lightticks = 0;
}
for (int r = 0; r < rain.length; r++) {
RainDrop rd = rain[r];
int inc = rd.length / 5;
int sws = rd.dir;
rd.y1 += inc;
rd.y2 += inc;
rd.x1 += sws;
rd.x2 += sws;
rd.x1 += prefixx;
rd.x2 += prefixx;
rd.y1 += prefixy;
rd.y2 += prefixy;
if (rd.y1 > Game.Settings.currentHeight) {
rd.y1 -= (Game.Settings.currentHeight + 60);
rd.y2 -= (Game.Settings.currentHeight + 60);
}
if (sws < 0 && rd.x2 < 0) {
rd.x1 += Game.Settings.currentWidth;
rd.x2 += Game.Settings.currentWidth;
}
if (sws > 0 && rd.x1 > Game.Settings.currentWidth) {
rd.x1 -= Game.Settings.currentWidth;
rd.x2 -= Game.Settings.currentWidth;
}
if (prefixx > 0 && rd.x1 > Game.Settings.currentWidth) {
rd.x1 -= Game.Settings.currentWidth;
rd.x2 -= Game.Settings.currentWidth;
}
if (prefixx < 0 && rd.x1 < 0) {
rd.x1 += Game.Settings.currentWidth;
rd.x2 += Game.Settings.currentWidth;
}
rain[r] = rd;
g.setColor(rd.colour);
g.drawLine(rd.x1,rd.y1,rd.x2,rd.y2);
}
prefixx = 0;
prefixy = 0;
g.dispose();
}
else
buffer = null;
}
|
diff --git a/core/src/main/java/org/apache/mahout/common/distance/WeightedDistanceMeasure.java b/core/src/main/java/org/apache/mahout/common/distance/WeightedDistanceMeasure.java
index b5dd6412..38ea75db 100644
--- a/core/src/main/java/org/apache/mahout/common/distance/WeightedDistanceMeasure.java
+++ b/core/src/main/java/org/apache/mahout/common/distance/WeightedDistanceMeasure.java
@@ -1,96 +1,96 @@
/**
* 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.mahout.common.distance;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapred.JobConf;
import org.apache.mahout.math.DenseVector;
import org.apache.mahout.math.Vector;
import org.apache.mahout.common.parameters.ClassParameter;
import org.apache.mahout.common.parameters.Parameter;
import org.apache.mahout.common.parameters.PathParameter;
import java.io.DataInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/** Abstract implementation of DistanceMeasure with support for weights. */
public abstract class WeightedDistanceMeasure implements DistanceMeasure {
private List<Parameter<?>> parameters;
private Parameter<Path> weightsFile;
private ClassParameter vectorClass;
private Vector weights;
@Override
public void createParameters(String prefix, JobConf jobConf) {
parameters = new ArrayList<Parameter<?>>();
weightsFile = new PathParameter(prefix, "weightsFile", jobConf, null, "Path on DFS to a file containing the weights.");
parameters.add(weightsFile);
vectorClass = new ClassParameter(prefix, "vectorClass", jobConf, DenseVector.class, "Class<Vector> file specified in parameter weightsFile has been serialized with.");
parameters.add(vectorClass);
}
@Override
public Collection<Parameter<?>> getParameters() {
return parameters;
}
@Override
public void configure(JobConf jobConf) {
if (parameters == null) {
ParameteredGeneralizations.configureParameters(this, jobConf);
}
try {
- FileSystem fs = FileSystem.get(weightsFile.get().toUri(), jobConf);
if (weightsFile.get() != null) {
+ FileSystem fs = FileSystem.get(weightsFile.get().toUri(), jobConf);
Vector weights = (Vector) vectorClass.get().newInstance();
if (!fs.exists(weightsFile.get())) {
throw new FileNotFoundException(weightsFile.get().toString());
}
DataInputStream in = fs.open(weightsFile.get());
try {
weights.readFields(in);
} finally {
in.close();
}
this.weights = weights;
}
} catch (IOException e) {
throw new IllegalStateException(e);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
} catch (InstantiationException e) {
throw new IllegalStateException(e);
}
}
public Vector getWeights() {
return weights;
}
public void setWeights(Vector weights) {
this.weights = weights;
}
}
| false | true | public void configure(JobConf jobConf) {
if (parameters == null) {
ParameteredGeneralizations.configureParameters(this, jobConf);
}
try {
FileSystem fs = FileSystem.get(weightsFile.get().toUri(), jobConf);
if (weightsFile.get() != null) {
Vector weights = (Vector) vectorClass.get().newInstance();
if (!fs.exists(weightsFile.get())) {
throw new FileNotFoundException(weightsFile.get().toString());
}
DataInputStream in = fs.open(weightsFile.get());
try {
weights.readFields(in);
} finally {
in.close();
}
this.weights = weights;
}
} catch (IOException e) {
throw new IllegalStateException(e);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
} catch (InstantiationException e) {
throw new IllegalStateException(e);
}
}
| public void configure(JobConf jobConf) {
if (parameters == null) {
ParameteredGeneralizations.configureParameters(this, jobConf);
}
try {
if (weightsFile.get() != null) {
FileSystem fs = FileSystem.get(weightsFile.get().toUri(), jobConf);
Vector weights = (Vector) vectorClass.get().newInstance();
if (!fs.exists(weightsFile.get())) {
throw new FileNotFoundException(weightsFile.get().toString());
}
DataInputStream in = fs.open(weightsFile.get());
try {
weights.readFields(in);
} finally {
in.close();
}
this.weights = weights;
}
} catch (IOException e) {
throw new IllegalStateException(e);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
} catch (InstantiationException e) {
throw new IllegalStateException(e);
}
}
|
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/actions/DeleteAction.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/actions/DeleteAction.java
index 912daae3e..0cba8fd0f 100644
--- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/actions/DeleteAction.java
+++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/actions/DeleteAction.java
@@ -1,131 +1,131 @@
/*******************************************************************************
* Copyright (c) 2004, 2007 Mylyn project committers 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
*******************************************************************************/
package org.eclipse.mylyn.internal.tasks.ui.actions;
import java.util.List;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.mylyn.context.core.ContextCorePlugin;
import org.eclipse.mylyn.internal.tasks.core.TaskCategory;
import org.eclipse.mylyn.internal.tasks.ui.views.TaskListView;
import org.eclipse.mylyn.tasks.core.AbstractRepositoryQuery;
import org.eclipse.mylyn.tasks.core.AbstractTask;
import org.eclipse.mylyn.tasks.core.AbstractTaskContainer;
import org.eclipse.mylyn.tasks.ui.TasksUiPlugin;
import org.eclipse.mylyn.tasks.ui.TasksUiUtil;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.WorkbenchImages;
/**
* @author Mik Kersten
*/
public class DeleteAction extends Action {
public static final String ID = "org.eclipse.mylyn.tasklist.actions.delete";
public DeleteAction() {
setText("Delete");
setId(ID);
setImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_DELETE));
}
@Override
public void run() {
ISelection selection = TaskListView.getFromActivePerspective().getViewer().getSelection();
List<?> toDelete = ((IStructuredSelection) selection).toList();
String elements = "";
int i = 0;
for (Object object : toDelete) {
i++;
if (i < 20) {
if (object instanceof AbstractTaskContainer) {
elements += " " + ((AbstractTaskContainer) object).getSummary() + "\n";
}
} else {
elements += "...";
break;
}
}
String message;
if (toDelete.size() == 1) {
Object object = toDelete.get(0);
if (object instanceof AbstractTask) {
if (((AbstractTask)object).isLocal()) {
message = "Permanently delete the task listed below?";
} else {
message = "Delete the planning information and context for the repository task? The server" +
" copy will not be deleted and the task will remain in queries that match it.";
}
} else if (object instanceof TaskCategory) {
- message = "Permanently delete the category? Contained tasks will still be available in the Archive";
+ message = "Permanently delete the category? Local tasks will be moved to the Uncategorized folder. Repository tasks will be moved to the Unmatched folder.";
} else if (object instanceof AbstractRepositoryQuery) {
- message = "Permanently delete the query? Matching tasks will still be available in the Archive";
+ message = "Permanently delete the query? Contained tasks will moved to the Unmatched folder.";
} else {
message = "Permanently delete the element listed below?";
}
} else {
message = "Delete the elements listed below? If categories or queries are selected contained tasks"
+ " will not be deleted. Contexts will be deleted for selected tasks.";
}
message += "\n\n" + elements;
boolean deleteConfirmed = MessageDialog.openQuestion(PlatformUI.getWorkbench()
.getActiveWorkbenchWindow()
.getShell(), "Confirm Delete", message);
if (!deleteConfirmed) {
return;
}
for (Object selectedObject : toDelete) {
if (selectedObject instanceof AbstractTask) {
AbstractTask task = null;
task = (AbstractTask) selectedObject;
TasksUiPlugin.getTaskListManager().deactivateTask(task);
TasksUiPlugin.getTaskListManager().getTaskList().deleteTask(task);
ContextCorePlugin.getContextManager().deleteContext(task.getHandleIdentifier());
TasksUiUtil.closeEditorInActivePage(task, false);
} else if (selectedObject instanceof AbstractRepositoryQuery) {
// boolean deleteConfirmed =
// MessageDialog.openQuestion(PlatformUI.getWorkbench()
// .getActiveWorkbenchWindow().getShell(), "Confirm delete",
// "Delete the selected query? Task data will not be deleted.");
// if (deleteConfirmed) {
TasksUiPlugin.getTaskListManager().getTaskList().deleteQuery((AbstractRepositoryQuery) selectedObject);
// }
} else if (selectedObject instanceof TaskCategory) {
// boolean deleteConfirmed =
// MessageDialog.openQuestion(PlatformUI.getWorkbench()
// .getActiveWorkbenchWindow().getShell(), "Confirm Delete",
// "Delete the selected category? Contained tasks will be moved
// to the root.");
// if (!deleteConfirmed)
// return;
TaskCategory cat = (TaskCategory) selectedObject;
for (AbstractTask task : cat.getChildren()) {
ContextCorePlugin.getContextManager().deleteContext(task.getHandleIdentifier());
TasksUiUtil.closeEditorInActivePage(task, false);
}
TasksUiPlugin.getTaskListManager().getTaskList().deleteCategory(cat);
} else {
MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
"Delete failed", "Nothing selected.");
return;
}
}
}
}
| false | true | public void run() {
ISelection selection = TaskListView.getFromActivePerspective().getViewer().getSelection();
List<?> toDelete = ((IStructuredSelection) selection).toList();
String elements = "";
int i = 0;
for (Object object : toDelete) {
i++;
if (i < 20) {
if (object instanceof AbstractTaskContainer) {
elements += " " + ((AbstractTaskContainer) object).getSummary() + "\n";
}
} else {
elements += "...";
break;
}
}
String message;
if (toDelete.size() == 1) {
Object object = toDelete.get(0);
if (object instanceof AbstractTask) {
if (((AbstractTask)object).isLocal()) {
message = "Permanently delete the task listed below?";
} else {
message = "Delete the planning information and context for the repository task? The server" +
" copy will not be deleted and the task will remain in queries that match it.";
}
} else if (object instanceof TaskCategory) {
message = "Permanently delete the category? Contained tasks will still be available in the Archive";
} else if (object instanceof AbstractRepositoryQuery) {
message = "Permanently delete the query? Matching tasks will still be available in the Archive";
} else {
message = "Permanently delete the element listed below?";
}
} else {
message = "Delete the elements listed below? If categories or queries are selected contained tasks"
+ " will not be deleted. Contexts will be deleted for selected tasks.";
}
message += "\n\n" + elements;
boolean deleteConfirmed = MessageDialog.openQuestion(PlatformUI.getWorkbench()
.getActiveWorkbenchWindow()
.getShell(), "Confirm Delete", message);
if (!deleteConfirmed) {
return;
}
for (Object selectedObject : toDelete) {
if (selectedObject instanceof AbstractTask) {
AbstractTask task = null;
task = (AbstractTask) selectedObject;
TasksUiPlugin.getTaskListManager().deactivateTask(task);
TasksUiPlugin.getTaskListManager().getTaskList().deleteTask(task);
ContextCorePlugin.getContextManager().deleteContext(task.getHandleIdentifier());
TasksUiUtil.closeEditorInActivePage(task, false);
} else if (selectedObject instanceof AbstractRepositoryQuery) {
// boolean deleteConfirmed =
// MessageDialog.openQuestion(PlatformUI.getWorkbench()
// .getActiveWorkbenchWindow().getShell(), "Confirm delete",
// "Delete the selected query? Task data will not be deleted.");
// if (deleteConfirmed) {
TasksUiPlugin.getTaskListManager().getTaskList().deleteQuery((AbstractRepositoryQuery) selectedObject);
// }
} else if (selectedObject instanceof TaskCategory) {
// boolean deleteConfirmed =
// MessageDialog.openQuestion(PlatformUI.getWorkbench()
// .getActiveWorkbenchWindow().getShell(), "Confirm Delete",
// "Delete the selected category? Contained tasks will be moved
// to the root.");
// if (!deleteConfirmed)
// return;
TaskCategory cat = (TaskCategory) selectedObject;
for (AbstractTask task : cat.getChildren()) {
ContextCorePlugin.getContextManager().deleteContext(task.getHandleIdentifier());
TasksUiUtil.closeEditorInActivePage(task, false);
}
TasksUiPlugin.getTaskListManager().getTaskList().deleteCategory(cat);
} else {
MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
"Delete failed", "Nothing selected.");
return;
}
}
}
| public void run() {
ISelection selection = TaskListView.getFromActivePerspective().getViewer().getSelection();
List<?> toDelete = ((IStructuredSelection) selection).toList();
String elements = "";
int i = 0;
for (Object object : toDelete) {
i++;
if (i < 20) {
if (object instanceof AbstractTaskContainer) {
elements += " " + ((AbstractTaskContainer) object).getSummary() + "\n";
}
} else {
elements += "...";
break;
}
}
String message;
if (toDelete.size() == 1) {
Object object = toDelete.get(0);
if (object instanceof AbstractTask) {
if (((AbstractTask)object).isLocal()) {
message = "Permanently delete the task listed below?";
} else {
message = "Delete the planning information and context for the repository task? The server" +
" copy will not be deleted and the task will remain in queries that match it.";
}
} else if (object instanceof TaskCategory) {
message = "Permanently delete the category? Local tasks will be moved to the Uncategorized folder. Repository tasks will be moved to the Unmatched folder.";
} else if (object instanceof AbstractRepositoryQuery) {
message = "Permanently delete the query? Contained tasks will moved to the Unmatched folder.";
} else {
message = "Permanently delete the element listed below?";
}
} else {
message = "Delete the elements listed below? If categories or queries are selected contained tasks"
+ " will not be deleted. Contexts will be deleted for selected tasks.";
}
message += "\n\n" + elements;
boolean deleteConfirmed = MessageDialog.openQuestion(PlatformUI.getWorkbench()
.getActiveWorkbenchWindow()
.getShell(), "Confirm Delete", message);
if (!deleteConfirmed) {
return;
}
for (Object selectedObject : toDelete) {
if (selectedObject instanceof AbstractTask) {
AbstractTask task = null;
task = (AbstractTask) selectedObject;
TasksUiPlugin.getTaskListManager().deactivateTask(task);
TasksUiPlugin.getTaskListManager().getTaskList().deleteTask(task);
ContextCorePlugin.getContextManager().deleteContext(task.getHandleIdentifier());
TasksUiUtil.closeEditorInActivePage(task, false);
} else if (selectedObject instanceof AbstractRepositoryQuery) {
// boolean deleteConfirmed =
// MessageDialog.openQuestion(PlatformUI.getWorkbench()
// .getActiveWorkbenchWindow().getShell(), "Confirm delete",
// "Delete the selected query? Task data will not be deleted.");
// if (deleteConfirmed) {
TasksUiPlugin.getTaskListManager().getTaskList().deleteQuery((AbstractRepositoryQuery) selectedObject);
// }
} else if (selectedObject instanceof TaskCategory) {
// boolean deleteConfirmed =
// MessageDialog.openQuestion(PlatformUI.getWorkbench()
// .getActiveWorkbenchWindow().getShell(), "Confirm Delete",
// "Delete the selected category? Contained tasks will be moved
// to the root.");
// if (!deleteConfirmed)
// return;
TaskCategory cat = (TaskCategory) selectedObject;
for (AbstractTask task : cat.getChildren()) {
ContextCorePlugin.getContextManager().deleteContext(task.getHandleIdentifier());
TasksUiUtil.closeEditorInActivePage(task, false);
}
TasksUiPlugin.getTaskListManager().getTaskList().deleteCategory(cat);
} else {
MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
"Delete failed", "Nothing selected.");
return;
}
}
}
|
diff --git a/src/main/java/org/ineto/niosocks/Socks4Protocol.java b/src/main/java/org/ineto/niosocks/Socks4Protocol.java
index bf827f0..b6ee2f2 100644
--- a/src/main/java/org/ineto/niosocks/Socks4Protocol.java
+++ b/src/main/java/org/ineto/niosocks/Socks4Protocol.java
@@ -1,64 +1,67 @@
package org.ineto.niosocks;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ProtocolException;
import java.net.UnknownHostException;
import org.jboss.netty.buffer.ChannelBuffer;
public class Socks4Protocol implements SocksProtocol {
private static final byte[] RESPONSE_OK = new byte[] { 0x00, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
private static final byte[] RESPONSE_FAIL = new byte[] { 0x00, 0x5b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
private InetSocketAddress address = null;
private byte[] response = null;
@Override
public void processMessage(ChannelBuffer msg) throws ProtocolException {
response = null;
if (msg.capacity() >= 8 && msg.getByte(0) == 4 && msg.getByte(1) == 1) {
- byte[] addr = new byte[] { msg.getByte(4), msg.getByte(5), msg.getByte(6), msg.getByte(7) };
+ byte[] addr = new byte[4];
+ msg.getBytes(4, addr);
int port = (((0xFF & msg.getByte(2)) << 8) + (0xFF & msg.getByte(3)));
try {
address = new InetSocketAddress(InetAddress.getByAddress(addr), port);
}
catch(UnknownHostException e) {
throw new ProtocolException("invalid ip address " + addr);
}
- }
- throw new ProtocolException("invalid request type");
+ }
+ else {
+ throw new ProtocolException("invalid request type");
+ }
}
@Override
public void setConnected(boolean connected) {
response = connected ? RESPONSE_OK : RESPONSE_FAIL;
}
@Override
public boolean hasResponse() {
return response != null;
}
@Override
public byte[] getResponse() {
return response;
}
@Override
public boolean isReady() {
return address != null;
}
@Override
public InetSocketAddress getOutboundAddress() {
return address;
}
@Override
public String toString() {
return "Socks4Protocol";
}
}
| false | true | public void processMessage(ChannelBuffer msg) throws ProtocolException {
response = null;
if (msg.capacity() >= 8 && msg.getByte(0) == 4 && msg.getByte(1) == 1) {
byte[] addr = new byte[] { msg.getByte(4), msg.getByte(5), msg.getByte(6), msg.getByte(7) };
int port = (((0xFF & msg.getByte(2)) << 8) + (0xFF & msg.getByte(3)));
try {
address = new InetSocketAddress(InetAddress.getByAddress(addr), port);
}
catch(UnknownHostException e) {
throw new ProtocolException("invalid ip address " + addr);
}
}
throw new ProtocolException("invalid request type");
}
| public void processMessage(ChannelBuffer msg) throws ProtocolException {
response = null;
if (msg.capacity() >= 8 && msg.getByte(0) == 4 && msg.getByte(1) == 1) {
byte[] addr = new byte[4];
msg.getBytes(4, addr);
int port = (((0xFF & msg.getByte(2)) << 8) + (0xFF & msg.getByte(3)));
try {
address = new InetSocketAddress(InetAddress.getByAddress(addr), port);
}
catch(UnknownHostException e) {
throw new ProtocolException("invalid ip address " + addr);
}
}
else {
throw new ProtocolException("invalid request type");
}
}
|
diff --git a/src/com/jmeyer/bukkit/jlevel/DatabaseManager.java b/src/com/jmeyer/bukkit/jlevel/DatabaseManager.java
index a1eecea..dc6c5e4 100644
--- a/src/com/jmeyer/bukkit/jlevel/DatabaseManager.java
+++ b/src/com/jmeyer/bukkit/jlevel/DatabaseManager.java
@@ -1,626 +1,626 @@
package com.jmeyer.bukkit.jlevel;
import java.io.File;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.filechooser.FileFilter;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
/**
* Handle calls to SQLite Database
* @author JMEYER
*
* Special Thanks:
* - tkelly: suggesting SQLite, offering IRC assistance, providing sample source
* - thegleek: suggesting SQLite, offering IRC assistance
*/
public class DatabaseManager {
public static final Logger LOG = Logger.getLogger("Minecraft");
public static final String ROOT_DIRECTORY = "JLevel-Data";
public static final String PLAYER_DIRECTORY = ROOT_DIRECTORY + File.separator + "Players" + File.separator;
public static final String SKILL_DIRECTORY = ROOT_DIRECTORY + File.separator + "Skills" + File.separator;
public static final String PLAYER_DB_DIRECTORY = "jdbc:sqlite:" + PLAYER_DIRECTORY;
public static final String SKILL_DB_DIRECTORY = "jdbc:sqlite:" + SKILL_DIRECTORY;
// TODO: getQueryResult(databasePath, get _, where _, equals_);
// TODO: getQueryResult(databasePath, query); have 1 return String and others that cast afterwards
// TODO: runUpdate(databasePath, update);
// TODO: make ignore null fields
// TODO: implement clearCurrent, which removes original tables if true
// TODO: implement clearCurrent with createSkillDatabaseIfNotExists
// Updates, or creates skill if not already created
public static void updateSkill(String skill, String[] itemRules, String[] expRules, String[] expTable, boolean clearCurrent) {
createSkillDatabaseIfNotExists(skill);
// TODO: remove test values and actually parse
Connection conn = null;
Statement st = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(skillDatabasePath(skill));
st = conn.createStatement();
// TODO: make addRow() and addItemRulesRow(Skill, _, _);
if (itemRules != null) {
for (String itemRule : itemRules) {
String[] split = itemRule.split(":", 2);
String itemRulesUpdate = "INSERT INTO `itemRules` (`itemId`,`level`) VALUES(" + split[0] + "," + split[1] + ");";
st.executeUpdate(itemRulesUpdate);
}
}
if (expRules != null) {
for (String expRule : expRules) {
String[] split = expRule.split(":", 4);
String expRulesUpdate = "INSERT INTO `expRules` (`action`,`receiver`,`receiverState`,`exp`) VALUES('" + split[0] + "', '" + split[1] + "', '" + split[2] + "', " + split[3] + ");";
st.executeUpdate(expRulesUpdate);
}
}
if (expTable != null) {
for (String expRow : expTable) {
String[] split = expRow.split(":", 2);
String expLevelsUpdate = "INSERT INTO `expLevels` (`level`, `expNeeded`) VALUES(" + split[0] + ", " + split[1] + ");";
st.executeUpdate(expLevelsUpdate);
}
}
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Update Table Exception (Skill: " + skill + ")", e);
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Error loading org.sqlite.JDBC");
} finally {
try {
if (conn != null)
conn.close();
if (st != null)
st.close();
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Could not update the table (on close) (Skill: " + skill + ")");
}
}
}
// ======================================================
// Creation methods (Tables, Directories, etc.)
// ======================================================
public static void createDirectoriesIfNotExists() {
File rootDirectory = new File("JLevel-Data");
File playerDirectory = new File("JLevel-Data/Players");
File skillDirectory = new File("JLevel-Data/Skills");
if (!rootDirectory.exists()) {
rootDirectory.mkdir();
}
if (!playerDirectory.exists()) {
playerDirectory.mkdir();
}
if (!skillDirectory.exists()) {
skillDirectory.mkdir();
}
}
public static void createPlayerDatabaseIfNotExists(Player player) {
if (!playerTableExists(player, false)) {
Connection conn = null;
Statement st = null;
String name = player.getName();
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(playerDatabasePath(player));
st = conn.createStatement();
String update = "CREATE TABLE `" + name + "` (" +
"`id` INTEGER PRIMARY KEY," +
"`skillName` varchar(32)," +
"`skillLevel` INTEGER," +
"`levelExp` INTEGER," +
"`nextLevelExp` INTEGER," +
"`totalExp` INTEGER" + ");";
st.executeUpdate(update);
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Create Table Exception (Player: " + name + ")", e);
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Error loading org.sqlite.JDBC");
} finally {
try {
if (conn != null)
conn.close();
if (st != null)
st.close();
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Could not create the table (on close) (Player: " + name + ")");
}
}
}
}
public static void createSkillDatabaseIfNotExists(String skill) { // , String[] itemRules, String[] expRules, String[] expTable) {
Connection conn = null;
Statement st = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(skillDatabasePath(skill));
st = conn.createStatement();
if (!itemRulesTableExistsForSkill(skill, false)) {
String itemRulesUpdate = "CREATE TABLE `itemRules` (" +
"`id` INTEGER PRIMARY KEY," +
"`itemId` INTEGER," +
"`level` INTEGER" + ");";
st.executeUpdate(itemRulesUpdate);
}
if (!expRulesTableExistsForSkill(skill, false)) {
String expRulesUpdate = "CREATE TABLE `expRules` (" +
"`id` INTEGER PRIMARY KEY," +
"`action` varchar(32)," +
"`receiver` varchar(32)," +
"`receiverState` varchar(32)," +
"`exp` INTEGER" + ");";
st.executeUpdate(expRulesUpdate);
}
if (!expLevelsTableExistsForSkill(skill, false)) {
String expLevelsUpdate = "CREATE TABLE `expLevels` (" +
"`id` INTEGER PRIMARY KEY," +
"`level` INTEGER," +
"`expNeeded` INTEGER" + ");";
st.executeUpdate(expLevelsUpdate);
}
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Create Table Exception (Skill: " + skill + ")", e);
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Error loading org.sqlite.JDBC");
} finally {
try {
if (conn != null)
conn.close();
if (st != null)
st.close();
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Could not create the table (on close) (Skill: " + skill + ")");
}
}
}
// ======================================================
// Data check methods (Tables)
// ======================================================
public static boolean playerCanUseItem(Player player, int itemId) {
File root = new File(SKILL_DIRECTORY);
File[] skillFiles = root.listFiles();
boolean canUse = true;
for (File file : skillFiles) {
String fileName = file.getName();
String skill = fileName.substring(0, fileName.indexOf('.'));
int reqLevel = requiredLevelForItem(skill, itemId);
if (playerSkillLevel(player, skill) < reqLevel) {
player.sendMessage("You must be at least level " + reqLevel + " of the " + ChatColor.YELLOW + skill + ChatColor.WHITE + " skill to use this.");
canUse = false;
}
}
return canUse;
}
public static int playerSkillLevel(Player player, String skill) {
if (playerTableExists(player, true)) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
String name = player.getName();
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(playerDatabasePath(player));
st = conn.createStatement();
String query = "SELECT * FROM " + name + " WHERE skillName='" + skill + "' LIMIT 1;";
rs = st.executeQuery(query);
if (rs.next())
return rs.getInt("skillLevel");
else
return 1;
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Table Read Exception (Player: " + name + ", Skill: " + skill + ")", e);
return 1;
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Error loading org.sqlite.JDBC");
return 1;
} finally {
try {
if (conn != null)
conn.close();
if (st != null)
st.close();
if (rs != null)
rs.close();
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Could not read the table (on close) (Player: " + player.getName() + ", Skill: " + skill + ")");
}
}
} else {
return 1;
}
}
public static ArrayList<String> relatedSkillsForItem(int itemId) {
ArrayList<String> relatedSkills = new ArrayList<String>();
File root = new File(SKILL_DIRECTORY);
File[] skillFiles = root.listFiles();
for (File file : skillFiles) {
String fileName = file.getName();
String skill = fileName.substring(0, fileName.indexOf('.'));
if (itemRelatesToSkill(skill, itemId)) {
relatedSkills.add(skill);
}
}
return relatedSkills;
}
private static int requiredLevelForItem(String skill, int itemId) {
if (itemRulesTableExistsForSkill(skill, true)) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(skillDatabasePath(skill));
st = conn.createStatement();
String query = "SELECT * FROM itemRules WHERE itemId=" + itemId + " LIMIT 1;";
rs = st.executeQuery(query);
if (rs.next())
return rs.getInt("level");
else
return -1;
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Table Read Exception (Skill: " + skill + ")", e);
return -1;
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Error loading org.sqlite.JDBC");
return -1;
} finally {
try {
if (conn != null)
conn.close();
if (st != null)
st.close();
if (rs != null)
rs.close();
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Could not read the table (on close) (Skill: " + skill + ")");
}
}
}
return -1;
}
private static boolean itemRelatesToSkill(String skill, int itemId) {
if (itemRulesTableExistsForSkill(skill, true)) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(skillDatabasePath(skill));
st = conn.createStatement();
String query = "SELECT * FROM itemRules WHERE itemId=" + itemId + ";";
rs = st.executeQuery(query);
if (!rs.next())
return false;
else
return true;
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Table Read Exception (Skill: " + skill + ")", e);
return false;
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Error loading org.sqlite.JDBC");
return false;
} finally {
try {
if (conn != null)
conn.close();
if (st != null)
st.close();
if (rs != null)
rs.close();
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Could not read the table (on close) (Skill: " + skill + ")");
}
}
}
return false;
}
public static void addExperience(Player player, String skill, int amount) {
String name = player.getName();
String dbPath = playerDatabasePath(player);
String condition = "skillName='" + skill + "'";
String result = getQueryResult(dbPath, name, "skillName", condition);
// Add skill if not yet learned
if (result == null) {
// newLines.add("skill:" + skill + ":1:0:" + getSkillExperienceNeededForLevel(skill, 1) + ":0");
String update = "INSERT INTO `" + name + "` (`skillName`,`skillLevel`,`levelExp`,`nextLevelExp`,`totalExp`) " +
"VALUES('" + skill + "', 1, 0, " + skillExperienceNeededForLevel(skill, 1) + ", 0);";
runUpdate(dbPath, update);
player.sendMessage("You learned the " + ChatColor.YELLOW + skill + ChatColor.WHITE + " skill!");
return;
}
// TODO: make more efficient (grab string[] of row values from query)
int skillLevel = Integer.parseInt(getQueryResult(dbPath, player.getName(), "skillLevel", condition));
int levelExp = Integer.parseInt(getQueryResult(dbPath, player.getName(), "levelExp", condition));
int nextLevelExp = Integer.parseInt(getQueryResult(dbPath, player.getName(), "nextLevelExp", condition));
int totalExp = Integer.parseInt(getQueryResult(dbPath, player.getName(), "nextLevelExp", condition));
// Add exp if not max level
if (nextLevelExp > 0) {
levelExp += amount;
totalExp += amount;
player.sendMessage("+(" + amount + ") " + skill);
}
// Level up if nextLevelExp reached and not max lvl
while (levelExp > nextLevelExp && nextLevelExp > 0) {
levelExp -= nextLevelExp;
skillLevel++;
nextLevelExp = skillExperienceNeededForLevel(skill, skillLevel);
player.sendMessage("Level up! You are now level " + skillLevel + " of the " + ChatColor.YELLOW + skill + ChatColor.WHITE + " skill.");
}
- String update = "UPDATE `" + name + "` SET `skillLevel`=" + levelExp + ", `levelExp`=" + levelExp + ", `nextLevelExp`=" +
+ String update = "UPDATE `" + name + "` SET `skillLevel`=" + skillLevel + ", `levelExp`=" + levelExp + ", `nextLevelExp`=" +
nextLevelExp + ", `totalExp`=" + totalExp + " WHERE `skillName`='" + skill + "';";
runUpdate(dbPath, update);
}
public static int getExperienceGainedFromAction(String skill, String action, String receiver, String receiverState) {
String condition = null;
String result = null;
if (action.equals("blockbreak")) {
condition = "action='blockbreak' AND receiver='" + receiver + "'";
if (Integer.parseInt(receiverState) >= 0) {
condition += " AND (receiverState='" + receiverState + "' OR receiverState='-1')";
}
System.out.println(condition);
} else if (action.equals("monsterkill")) {
condition = "action='monsterkill' AND receiver='" + receiver + "'";
} else {
return 0;
}
result = getQueryResult(skillDatabasePath(skill), "expRules", "exp", condition);
if (result != null)
return Integer.parseInt(result);
else
return 0;
}
public static int skillExperienceNeededForLevel(String skill, int level) {
String condition = "level=" + level;
String result = getQueryResult(skillDatabasePath(skill), "expLevels", "expNeeded", condition);
if (result != null)
return Integer.parseInt(result);
else
return -1;
}
// ======================================================
// Data script methods
// ======================================================
// getQueryResult(databasePath, from _, get _, where _, equals_);
// EX Condition: "level=1"
public static String getQueryResult(String dbPath, String tableFrom, String itemToGet, String condition) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
String query = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(dbPath);
st = conn.createStatement();
query = "SELECT * FROM " + tableFrom + " WHERE " + condition + " LIMIT 1;";
rs = st.executeQuery(query);
if (rs.next())
return rs.getString(itemToGet);
else
return null;
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Table Read Exception (getResult) \n" + query, e);
return null;
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Error loading org.sqlite.JDBC");
return null;
} finally {
try {
if (conn != null)
conn.close();
if (st != null)
st.close();
if (rs != null)
rs.close();
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Could not read the table (on close) (getResult) \n" + query);
}
}
}
public static void runUpdate(String dbPath, String update) {
Connection conn = null;
Statement st = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(dbPath);
st = conn.createStatement();
st.executeUpdate(update);
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Run Update Exception \n" + update, e);
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Error loading org.sqlite.JDBC");
} finally {
try {
if (conn != null)
conn.close();
if (st != null)
st.close();
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Could not run update \n" + update);
}
}
}
// ======================================================
// File check methods (Tables, Directories, etc.)
// ======================================================
public static boolean playerTableExists(Player player, boolean showError) {
if(tableExists(playerDatabasePath(player), player.getName())) {
return true;
} else {
if (showError) {
LOG.log(Level.WARNING, "[JLEVEL]: Missing player table for " + player.getName() + ".");
}
return false;
}
}
public static boolean allTablesExistForSkill(String skill, boolean showError) {
return itemRulesTableExistsForSkill(skill, showError) &&
expRulesTableExistsForSkill(skill, showError) &&
expLevelsTableExistsForSkill(skill, showError);
}
public static boolean itemRulesTableExistsForSkill(String skill, boolean showError) {
if (tableExists(skillDatabasePath(skill), "itemRules")) {
return true;
} else {
if (showError) {
LOG.log(Level.WARNING, "[JLEVEL]: Missing itemRules table for " + skill + " skill.");
}
return false;
}
}
public static boolean expRulesTableExistsForSkill(String skill, boolean showError) {
if (tableExists(skillDatabasePath(skill), "expRules")) {
return true;
} else {
if (showError) {
LOG.log(Level.WARNING, "[JLEVEL]: Missing expRules table for " + skill + " skill.");
}
return false;
}
}
public static boolean expLevelsTableExistsForSkill(String skill, boolean showError) {
if (tableExists(skillDatabasePath(skill), "expLevels")) {
return true;
} else {
if (showError) {
LOG.log(Level.WARNING, "[JLEVEL]: Missing expLevels table for " + skill + " skill.");
}
return false;
}
}
public static boolean tableExists(String connectionPath, String tableName) {
Connection conn = null;
ResultSet rs = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(connectionPath);
DatabaseMetaData dbm = conn.getMetaData();
rs = dbm.getTables(null, null, tableName, null);
if (!rs.next())
return false;
return true;
} catch (SQLException ex) {
LOG.log(Level.SEVERE, "[JLEVEL]: Table Check Exception", ex);
return false;
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Error loading org.sqlite.JDBC");
return false;
} finally {
try {
if (rs != null)
rs.close();
if (conn != null)
conn.close();
} catch (SQLException ex) {
LOG.log(Level.SEVERE, "[JLEVEL]: Table Check SQL Exception (on closing)");
}
}
}
// ======================================================
// Private path methods
// ======================================================
private static String playerDatabasePath(Player player) {
return PLAYER_DB_DIRECTORY + player.getName() + ".db";
}
private static String skillDatabasePath(String skill) {
return SKILL_DB_DIRECTORY + skill + ".db";
}
}
| true | true | public static void createSkillDatabaseIfNotExists(String skill) { // , String[] itemRules, String[] expRules, String[] expTable) {
Connection conn = null;
Statement st = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(skillDatabasePath(skill));
st = conn.createStatement();
if (!itemRulesTableExistsForSkill(skill, false)) {
String itemRulesUpdate = "CREATE TABLE `itemRules` (" +
"`id` INTEGER PRIMARY KEY," +
"`itemId` INTEGER," +
"`level` INTEGER" + ");";
st.executeUpdate(itemRulesUpdate);
}
if (!expRulesTableExistsForSkill(skill, false)) {
String expRulesUpdate = "CREATE TABLE `expRules` (" +
"`id` INTEGER PRIMARY KEY," +
"`action` varchar(32)," +
"`receiver` varchar(32)," +
"`receiverState` varchar(32)," +
"`exp` INTEGER" + ");";
st.executeUpdate(expRulesUpdate);
}
if (!expLevelsTableExistsForSkill(skill, false)) {
String expLevelsUpdate = "CREATE TABLE `expLevels` (" +
"`id` INTEGER PRIMARY KEY," +
"`level` INTEGER," +
"`expNeeded` INTEGER" + ");";
st.executeUpdate(expLevelsUpdate);
}
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Create Table Exception (Skill: " + skill + ")", e);
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Error loading org.sqlite.JDBC");
} finally {
try {
if (conn != null)
conn.close();
if (st != null)
st.close();
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Could not create the table (on close) (Skill: " + skill + ")");
}
}
}
// ======================================================
// Data check methods (Tables)
// ======================================================
public static boolean playerCanUseItem(Player player, int itemId) {
File root = new File(SKILL_DIRECTORY);
File[] skillFiles = root.listFiles();
boolean canUse = true;
for (File file : skillFiles) {
String fileName = file.getName();
String skill = fileName.substring(0, fileName.indexOf('.'));
int reqLevel = requiredLevelForItem(skill, itemId);
if (playerSkillLevel(player, skill) < reqLevel) {
player.sendMessage("You must be at least level " + reqLevel + " of the " + ChatColor.YELLOW + skill + ChatColor.WHITE + " skill to use this.");
canUse = false;
}
}
return canUse;
}
public static int playerSkillLevel(Player player, String skill) {
if (playerTableExists(player, true)) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
String name = player.getName();
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(playerDatabasePath(player));
st = conn.createStatement();
String query = "SELECT * FROM " + name + " WHERE skillName='" + skill + "' LIMIT 1;";
rs = st.executeQuery(query);
if (rs.next())
return rs.getInt("skillLevel");
else
return 1;
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Table Read Exception (Player: " + name + ", Skill: " + skill + ")", e);
return 1;
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Error loading org.sqlite.JDBC");
return 1;
} finally {
try {
if (conn != null)
conn.close();
if (st != null)
st.close();
if (rs != null)
rs.close();
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Could not read the table (on close) (Player: " + player.getName() + ", Skill: " + skill + ")");
}
}
} else {
return 1;
}
}
public static ArrayList<String> relatedSkillsForItem(int itemId) {
ArrayList<String> relatedSkills = new ArrayList<String>();
File root = new File(SKILL_DIRECTORY);
File[] skillFiles = root.listFiles();
for (File file : skillFiles) {
String fileName = file.getName();
String skill = fileName.substring(0, fileName.indexOf('.'));
if (itemRelatesToSkill(skill, itemId)) {
relatedSkills.add(skill);
}
}
return relatedSkills;
}
private static int requiredLevelForItem(String skill, int itemId) {
if (itemRulesTableExistsForSkill(skill, true)) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(skillDatabasePath(skill));
st = conn.createStatement();
String query = "SELECT * FROM itemRules WHERE itemId=" + itemId + " LIMIT 1;";
rs = st.executeQuery(query);
if (rs.next())
return rs.getInt("level");
else
return -1;
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Table Read Exception (Skill: " + skill + ")", e);
return -1;
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Error loading org.sqlite.JDBC");
return -1;
} finally {
try {
if (conn != null)
conn.close();
if (st != null)
st.close();
if (rs != null)
rs.close();
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Could not read the table (on close) (Skill: " + skill + ")");
}
}
}
return -1;
}
private static boolean itemRelatesToSkill(String skill, int itemId) {
if (itemRulesTableExistsForSkill(skill, true)) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(skillDatabasePath(skill));
st = conn.createStatement();
String query = "SELECT * FROM itemRules WHERE itemId=" + itemId + ";";
rs = st.executeQuery(query);
if (!rs.next())
return false;
else
return true;
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Table Read Exception (Skill: " + skill + ")", e);
return false;
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Error loading org.sqlite.JDBC");
return false;
} finally {
try {
if (conn != null)
conn.close();
if (st != null)
st.close();
if (rs != null)
rs.close();
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Could not read the table (on close) (Skill: " + skill + ")");
}
}
}
return false;
}
public static void addExperience(Player player, String skill, int amount) {
String name = player.getName();
String dbPath = playerDatabasePath(player);
String condition = "skillName='" + skill + "'";
String result = getQueryResult(dbPath, name, "skillName", condition);
// Add skill if not yet learned
if (result == null) {
// newLines.add("skill:" + skill + ":1:0:" + getSkillExperienceNeededForLevel(skill, 1) + ":0");
String update = "INSERT INTO `" + name + "` (`skillName`,`skillLevel`,`levelExp`,`nextLevelExp`,`totalExp`) " +
"VALUES('" + skill + "', 1, 0, " + skillExperienceNeededForLevel(skill, 1) + ", 0);";
runUpdate(dbPath, update);
player.sendMessage("You learned the " + ChatColor.YELLOW + skill + ChatColor.WHITE + " skill!");
return;
}
// TODO: make more efficient (grab string[] of row values from query)
int skillLevel = Integer.parseInt(getQueryResult(dbPath, player.getName(), "skillLevel", condition));
int levelExp = Integer.parseInt(getQueryResult(dbPath, player.getName(), "levelExp", condition));
int nextLevelExp = Integer.parseInt(getQueryResult(dbPath, player.getName(), "nextLevelExp", condition));
int totalExp = Integer.parseInt(getQueryResult(dbPath, player.getName(), "nextLevelExp", condition));
// Add exp if not max level
if (nextLevelExp > 0) {
levelExp += amount;
totalExp += amount;
player.sendMessage("+(" + amount + ") " + skill);
}
// Level up if nextLevelExp reached and not max lvl
while (levelExp > nextLevelExp && nextLevelExp > 0) {
levelExp -= nextLevelExp;
skillLevel++;
nextLevelExp = skillExperienceNeededForLevel(skill, skillLevel);
player.sendMessage("Level up! You are now level " + skillLevel + " of the " + ChatColor.YELLOW + skill + ChatColor.WHITE + " skill.");
}
String update = "UPDATE `" + name + "` SET `skillLevel`=" + levelExp + ", `levelExp`=" + levelExp + ", `nextLevelExp`=" +
nextLevelExp + ", `totalExp`=" + totalExp + " WHERE `skillName`='" + skill + "';";
runUpdate(dbPath, update);
}
public static int getExperienceGainedFromAction(String skill, String action, String receiver, String receiverState) {
String condition = null;
String result = null;
if (action.equals("blockbreak")) {
condition = "action='blockbreak' AND receiver='" + receiver + "'";
if (Integer.parseInt(receiverState) >= 0) {
condition += " AND (receiverState='" + receiverState + "' OR receiverState='-1')";
}
System.out.println(condition);
} else if (action.equals("monsterkill")) {
condition = "action='monsterkill' AND receiver='" + receiver + "'";
} else {
return 0;
}
result = getQueryResult(skillDatabasePath(skill), "expRules", "exp", condition);
if (result != null)
return Integer.parseInt(result);
else
return 0;
}
public static int skillExperienceNeededForLevel(String skill, int level) {
String condition = "level=" + level;
String result = getQueryResult(skillDatabasePath(skill), "expLevels", "expNeeded", condition);
if (result != null)
return Integer.parseInt(result);
else
return -1;
}
// ======================================================
// Data script methods
// ======================================================
// getQueryResult(databasePath, from _, get _, where _, equals_);
// EX Condition: "level=1"
public static String getQueryResult(String dbPath, String tableFrom, String itemToGet, String condition) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
String query = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(dbPath);
st = conn.createStatement();
query = "SELECT * FROM " + tableFrom + " WHERE " + condition + " LIMIT 1;";
rs = st.executeQuery(query);
if (rs.next())
return rs.getString(itemToGet);
else
return null;
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Table Read Exception (getResult) \n" + query, e);
return null;
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Error loading org.sqlite.JDBC");
return null;
} finally {
try {
if (conn != null)
conn.close();
if (st != null)
st.close();
if (rs != null)
rs.close();
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Could not read the table (on close) (getResult) \n" + query);
}
}
}
public static void runUpdate(String dbPath, String update) {
Connection conn = null;
Statement st = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(dbPath);
st = conn.createStatement();
st.executeUpdate(update);
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Run Update Exception \n" + update, e);
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Error loading org.sqlite.JDBC");
} finally {
try {
if (conn != null)
conn.close();
if (st != null)
st.close();
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Could not run update \n" + update);
}
}
}
// ======================================================
// File check methods (Tables, Directories, etc.)
// ======================================================
public static boolean playerTableExists(Player player, boolean showError) {
if(tableExists(playerDatabasePath(player), player.getName())) {
return true;
} else {
if (showError) {
LOG.log(Level.WARNING, "[JLEVEL]: Missing player table for " + player.getName() + ".");
}
return false;
}
}
public static boolean allTablesExistForSkill(String skill, boolean showError) {
return itemRulesTableExistsForSkill(skill, showError) &&
expRulesTableExistsForSkill(skill, showError) &&
expLevelsTableExistsForSkill(skill, showError);
}
public static boolean itemRulesTableExistsForSkill(String skill, boolean showError) {
if (tableExists(skillDatabasePath(skill), "itemRules")) {
return true;
} else {
if (showError) {
LOG.log(Level.WARNING, "[JLEVEL]: Missing itemRules table for " + skill + " skill.");
}
return false;
}
}
public static boolean expRulesTableExistsForSkill(String skill, boolean showError) {
if (tableExists(skillDatabasePath(skill), "expRules")) {
return true;
} else {
if (showError) {
LOG.log(Level.WARNING, "[JLEVEL]: Missing expRules table for " + skill + " skill.");
}
return false;
}
}
public static boolean expLevelsTableExistsForSkill(String skill, boolean showError) {
if (tableExists(skillDatabasePath(skill), "expLevels")) {
return true;
} else {
if (showError) {
LOG.log(Level.WARNING, "[JLEVEL]: Missing expLevels table for " + skill + " skill.");
}
return false;
}
}
public static boolean tableExists(String connectionPath, String tableName) {
Connection conn = null;
ResultSet rs = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(connectionPath);
DatabaseMetaData dbm = conn.getMetaData();
rs = dbm.getTables(null, null, tableName, null);
if (!rs.next())
return false;
return true;
} catch (SQLException ex) {
LOG.log(Level.SEVERE, "[JLEVEL]: Table Check Exception", ex);
return false;
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Error loading org.sqlite.JDBC");
return false;
} finally {
try {
if (rs != null)
rs.close();
if (conn != null)
conn.close();
} catch (SQLException ex) {
LOG.log(Level.SEVERE, "[JLEVEL]: Table Check SQL Exception (on closing)");
}
}
}
// ======================================================
// Private path methods
// ======================================================
private static String playerDatabasePath(Player player) {
return PLAYER_DB_DIRECTORY + player.getName() + ".db";
}
private static String skillDatabasePath(String skill) {
return SKILL_DB_DIRECTORY + skill + ".db";
}
}
| public static void createSkillDatabaseIfNotExists(String skill) { // , String[] itemRules, String[] expRules, String[] expTable) {
Connection conn = null;
Statement st = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(skillDatabasePath(skill));
st = conn.createStatement();
if (!itemRulesTableExistsForSkill(skill, false)) {
String itemRulesUpdate = "CREATE TABLE `itemRules` (" +
"`id` INTEGER PRIMARY KEY," +
"`itemId` INTEGER," +
"`level` INTEGER" + ");";
st.executeUpdate(itemRulesUpdate);
}
if (!expRulesTableExistsForSkill(skill, false)) {
String expRulesUpdate = "CREATE TABLE `expRules` (" +
"`id` INTEGER PRIMARY KEY," +
"`action` varchar(32)," +
"`receiver` varchar(32)," +
"`receiverState` varchar(32)," +
"`exp` INTEGER" + ");";
st.executeUpdate(expRulesUpdate);
}
if (!expLevelsTableExistsForSkill(skill, false)) {
String expLevelsUpdate = "CREATE TABLE `expLevels` (" +
"`id` INTEGER PRIMARY KEY," +
"`level` INTEGER," +
"`expNeeded` INTEGER" + ");";
st.executeUpdate(expLevelsUpdate);
}
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Create Table Exception (Skill: " + skill + ")", e);
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Error loading org.sqlite.JDBC");
} finally {
try {
if (conn != null)
conn.close();
if (st != null)
st.close();
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Could not create the table (on close) (Skill: " + skill + ")");
}
}
}
// ======================================================
// Data check methods (Tables)
// ======================================================
public static boolean playerCanUseItem(Player player, int itemId) {
File root = new File(SKILL_DIRECTORY);
File[] skillFiles = root.listFiles();
boolean canUse = true;
for (File file : skillFiles) {
String fileName = file.getName();
String skill = fileName.substring(0, fileName.indexOf('.'));
int reqLevel = requiredLevelForItem(skill, itemId);
if (playerSkillLevel(player, skill) < reqLevel) {
player.sendMessage("You must be at least level " + reqLevel + " of the " + ChatColor.YELLOW + skill + ChatColor.WHITE + " skill to use this.");
canUse = false;
}
}
return canUse;
}
public static int playerSkillLevel(Player player, String skill) {
if (playerTableExists(player, true)) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
String name = player.getName();
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(playerDatabasePath(player));
st = conn.createStatement();
String query = "SELECT * FROM " + name + " WHERE skillName='" + skill + "' LIMIT 1;";
rs = st.executeQuery(query);
if (rs.next())
return rs.getInt("skillLevel");
else
return 1;
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Table Read Exception (Player: " + name + ", Skill: " + skill + ")", e);
return 1;
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Error loading org.sqlite.JDBC");
return 1;
} finally {
try {
if (conn != null)
conn.close();
if (st != null)
st.close();
if (rs != null)
rs.close();
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Could not read the table (on close) (Player: " + player.getName() + ", Skill: " + skill + ")");
}
}
} else {
return 1;
}
}
public static ArrayList<String> relatedSkillsForItem(int itemId) {
ArrayList<String> relatedSkills = new ArrayList<String>();
File root = new File(SKILL_DIRECTORY);
File[] skillFiles = root.listFiles();
for (File file : skillFiles) {
String fileName = file.getName();
String skill = fileName.substring(0, fileName.indexOf('.'));
if (itemRelatesToSkill(skill, itemId)) {
relatedSkills.add(skill);
}
}
return relatedSkills;
}
private static int requiredLevelForItem(String skill, int itemId) {
if (itemRulesTableExistsForSkill(skill, true)) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(skillDatabasePath(skill));
st = conn.createStatement();
String query = "SELECT * FROM itemRules WHERE itemId=" + itemId + " LIMIT 1;";
rs = st.executeQuery(query);
if (rs.next())
return rs.getInt("level");
else
return -1;
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Table Read Exception (Skill: " + skill + ")", e);
return -1;
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Error loading org.sqlite.JDBC");
return -1;
} finally {
try {
if (conn != null)
conn.close();
if (st != null)
st.close();
if (rs != null)
rs.close();
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Could not read the table (on close) (Skill: " + skill + ")");
}
}
}
return -1;
}
private static boolean itemRelatesToSkill(String skill, int itemId) {
if (itemRulesTableExistsForSkill(skill, true)) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(skillDatabasePath(skill));
st = conn.createStatement();
String query = "SELECT * FROM itemRules WHERE itemId=" + itemId + ";";
rs = st.executeQuery(query);
if (!rs.next())
return false;
else
return true;
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Table Read Exception (Skill: " + skill + ")", e);
return false;
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Error loading org.sqlite.JDBC");
return false;
} finally {
try {
if (conn != null)
conn.close();
if (st != null)
st.close();
if (rs != null)
rs.close();
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Could not read the table (on close) (Skill: " + skill + ")");
}
}
}
return false;
}
public static void addExperience(Player player, String skill, int amount) {
String name = player.getName();
String dbPath = playerDatabasePath(player);
String condition = "skillName='" + skill + "'";
String result = getQueryResult(dbPath, name, "skillName", condition);
// Add skill if not yet learned
if (result == null) {
// newLines.add("skill:" + skill + ":1:0:" + getSkillExperienceNeededForLevel(skill, 1) + ":0");
String update = "INSERT INTO `" + name + "` (`skillName`,`skillLevel`,`levelExp`,`nextLevelExp`,`totalExp`) " +
"VALUES('" + skill + "', 1, 0, " + skillExperienceNeededForLevel(skill, 1) + ", 0);";
runUpdate(dbPath, update);
player.sendMessage("You learned the " + ChatColor.YELLOW + skill + ChatColor.WHITE + " skill!");
return;
}
// TODO: make more efficient (grab string[] of row values from query)
int skillLevel = Integer.parseInt(getQueryResult(dbPath, player.getName(), "skillLevel", condition));
int levelExp = Integer.parseInt(getQueryResult(dbPath, player.getName(), "levelExp", condition));
int nextLevelExp = Integer.parseInt(getQueryResult(dbPath, player.getName(), "nextLevelExp", condition));
int totalExp = Integer.parseInt(getQueryResult(dbPath, player.getName(), "nextLevelExp", condition));
// Add exp if not max level
if (nextLevelExp > 0) {
levelExp += amount;
totalExp += amount;
player.sendMessage("+(" + amount + ") " + skill);
}
// Level up if nextLevelExp reached and not max lvl
while (levelExp > nextLevelExp && nextLevelExp > 0) {
levelExp -= nextLevelExp;
skillLevel++;
nextLevelExp = skillExperienceNeededForLevel(skill, skillLevel);
player.sendMessage("Level up! You are now level " + skillLevel + " of the " + ChatColor.YELLOW + skill + ChatColor.WHITE + " skill.");
}
String update = "UPDATE `" + name + "` SET `skillLevel`=" + skillLevel + ", `levelExp`=" + levelExp + ", `nextLevelExp`=" +
nextLevelExp + ", `totalExp`=" + totalExp + " WHERE `skillName`='" + skill + "';";
runUpdate(dbPath, update);
}
public static int getExperienceGainedFromAction(String skill, String action, String receiver, String receiverState) {
String condition = null;
String result = null;
if (action.equals("blockbreak")) {
condition = "action='blockbreak' AND receiver='" + receiver + "'";
if (Integer.parseInt(receiverState) >= 0) {
condition += " AND (receiverState='" + receiverState + "' OR receiverState='-1')";
}
System.out.println(condition);
} else if (action.equals("monsterkill")) {
condition = "action='monsterkill' AND receiver='" + receiver + "'";
} else {
return 0;
}
result = getQueryResult(skillDatabasePath(skill), "expRules", "exp", condition);
if (result != null)
return Integer.parseInt(result);
else
return 0;
}
public static int skillExperienceNeededForLevel(String skill, int level) {
String condition = "level=" + level;
String result = getQueryResult(skillDatabasePath(skill), "expLevels", "expNeeded", condition);
if (result != null)
return Integer.parseInt(result);
else
return -1;
}
// ======================================================
// Data script methods
// ======================================================
// getQueryResult(databasePath, from _, get _, where _, equals_);
// EX Condition: "level=1"
public static String getQueryResult(String dbPath, String tableFrom, String itemToGet, String condition) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
String query = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(dbPath);
st = conn.createStatement();
query = "SELECT * FROM " + tableFrom + " WHERE " + condition + " LIMIT 1;";
rs = st.executeQuery(query);
if (rs.next())
return rs.getString(itemToGet);
else
return null;
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Table Read Exception (getResult) \n" + query, e);
return null;
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Error loading org.sqlite.JDBC");
return null;
} finally {
try {
if (conn != null)
conn.close();
if (st != null)
st.close();
if (rs != null)
rs.close();
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Could not read the table (on close) (getResult) \n" + query);
}
}
}
public static void runUpdate(String dbPath, String update) {
Connection conn = null;
Statement st = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(dbPath);
st = conn.createStatement();
st.executeUpdate(update);
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Run Update Exception \n" + update, e);
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Error loading org.sqlite.JDBC");
} finally {
try {
if (conn != null)
conn.close();
if (st != null)
st.close();
} catch (SQLException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Could not run update \n" + update);
}
}
}
// ======================================================
// File check methods (Tables, Directories, etc.)
// ======================================================
public static boolean playerTableExists(Player player, boolean showError) {
if(tableExists(playerDatabasePath(player), player.getName())) {
return true;
} else {
if (showError) {
LOG.log(Level.WARNING, "[JLEVEL]: Missing player table for " + player.getName() + ".");
}
return false;
}
}
public static boolean allTablesExistForSkill(String skill, boolean showError) {
return itemRulesTableExistsForSkill(skill, showError) &&
expRulesTableExistsForSkill(skill, showError) &&
expLevelsTableExistsForSkill(skill, showError);
}
public static boolean itemRulesTableExistsForSkill(String skill, boolean showError) {
if (tableExists(skillDatabasePath(skill), "itemRules")) {
return true;
} else {
if (showError) {
LOG.log(Level.WARNING, "[JLEVEL]: Missing itemRules table for " + skill + " skill.");
}
return false;
}
}
public static boolean expRulesTableExistsForSkill(String skill, boolean showError) {
if (tableExists(skillDatabasePath(skill), "expRules")) {
return true;
} else {
if (showError) {
LOG.log(Level.WARNING, "[JLEVEL]: Missing expRules table for " + skill + " skill.");
}
return false;
}
}
public static boolean expLevelsTableExistsForSkill(String skill, boolean showError) {
if (tableExists(skillDatabasePath(skill), "expLevels")) {
return true;
} else {
if (showError) {
LOG.log(Level.WARNING, "[JLEVEL]: Missing expLevels table for " + skill + " skill.");
}
return false;
}
}
public static boolean tableExists(String connectionPath, String tableName) {
Connection conn = null;
ResultSet rs = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection(connectionPath);
DatabaseMetaData dbm = conn.getMetaData();
rs = dbm.getTables(null, null, tableName, null);
if (!rs.next())
return false;
return true;
} catch (SQLException ex) {
LOG.log(Level.SEVERE, "[JLEVEL]: Table Check Exception", ex);
return false;
} catch (ClassNotFoundException e) {
LOG.log(Level.SEVERE, "[JLEVEL]: Error loading org.sqlite.JDBC");
return false;
} finally {
try {
if (rs != null)
rs.close();
if (conn != null)
conn.close();
} catch (SQLException ex) {
LOG.log(Level.SEVERE, "[JLEVEL]: Table Check SQL Exception (on closing)");
}
}
}
// ======================================================
// Private path methods
// ======================================================
private static String playerDatabasePath(Player player) {
return PLAYER_DB_DIRECTORY + player.getName() + ".db";
}
private static String skillDatabasePath(String skill) {
return SKILL_DB_DIRECTORY + skill + ".db";
}
}
|
diff --git a/src/main/java/org/jboss/pressgang/ccms/filter/base/BaseFilterQueryBuilderWithProperties.java b/src/main/java/org/jboss/pressgang/ccms/filter/base/BaseFilterQueryBuilderWithProperties.java
index 0d22b5b..508bfb6 100644
--- a/src/main/java/org/jboss/pressgang/ccms/filter/base/BaseFilterQueryBuilderWithProperties.java
+++ b/src/main/java/org/jboss/pressgang/ccms/filter/base/BaseFilterQueryBuilderWithProperties.java
@@ -1,80 +1,80 @@
package org.jboss.pressgang.ccms.filter.base;
import javax.persistence.EntityManager;
import javax.persistence.criteria.Subquery;
import java.util.Map;
import org.jboss.pressgang.ccms.filter.structures.FilterFieldBooleanMapData;
import org.jboss.pressgang.ccms.filter.structures.FilterFieldDataBase;
import org.jboss.pressgang.ccms.filter.structures.FilterFieldStringMapData;
import org.jboss.pressgang.ccms.model.base.ToPropertyTag;
import org.jboss.pressgang.ccms.utils.constants.CommonFilterConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Provides the query elements required by Filter.buildQuery() to get a list of Entities that have extended properties.
*
* @param <T> The Type of entity that should be returned by the query builder.
* @param <U> The Type of the entity to PropertyTag mapping.
*/
public abstract class BaseFilterQueryBuilderWithProperties<T, U extends ToPropertyTag<U>> extends BaseFilterQueryBuilder<T> {
private static final Logger LOG = LoggerFactory.getLogger(BaseFilterQueryBuilderWithProperties.class);
protected BaseFilterQueryBuilderWithProperties(final Class<T> clazz, final BaseFieldFilter fieldFilter, final EntityManager entityManager) {
super(clazz, fieldFilter, entityManager);
}
@Override
public void processField(final FilterFieldDataBase<?> field) {
final String fieldName = field.getBaseName();
if (fieldName.equals(CommonFilterConstants.PROPERTY_TAG_EXISTS)) {
final FilterFieldBooleanMapData mapField = (FilterFieldBooleanMapData) field;
for (final Map.Entry<Integer, Boolean> entry : mapField.getData().entrySet()) {
final Integer propertyTagId = entry.getKey();
final Boolean fieldValueBoolean = entry.getValue();
if (propertyTagId != null && fieldValueBoolean) {
addFieldCondition(getCriteriaBuilder().exists(getPropertyTagExistsSubquery(propertyTagId)));
}
}
} else if (fieldName.startsWith(CommonFilterConstants.PROPERTY_TAG_NOT_EXISTS)) {
final FilterFieldBooleanMapData mapField = (FilterFieldBooleanMapData) field;
for (final Map.Entry<Integer, Boolean> entry : mapField.getData().entrySet()) {
final Integer propertyTagId = entry.getKey();
final Boolean fieldValueBoolean = entry.getValue();
if (propertyTagId != null && fieldValueBoolean) {
addFieldCondition(getCriteriaBuilder().not(getCriteriaBuilder().exists(getPropertyTagExistsSubquery(propertyTagId))));
}
}
} else if (fieldName.startsWith(CommonFilterConstants.PROPERTY_TAG)) {
final FilterFieldStringMapData mapField = (FilterFieldStringMapData) field;
for (final Map.Entry<Integer, String> entry : mapField.getData().entrySet()) {
final Integer propertyTagId = entry.getKey();
final String fieldValue = entry.getValue();
if (propertyTagId != null && fieldValue != null) {
- addExistsCondition(getPropertyTagSubquery(propertyTagId, (String) field.getData()));
+ addExistsCondition(getPropertyTagSubquery(propertyTagId, fieldValue));
}
}
} else {
super.processField(field);
}
}
/**
* Create a Subquery to check if a topic has a property tag with a specific value.
*
* @param propertyTagId The ID of the property tag to be checked.
* @param propertyTagValue The Value that the property tag should have.
* @return A subquery that can be used in an exists statement to see if a topic has a property tag with the specified value.
*/
protected abstract Subquery<U> getPropertyTagSubquery(final Integer propertyTagId, final String propertyTagValue);
/**
* Create a Subquery to check if a entity has a property tag exists.
*
* @param propertyTagId The ID of the property tag to be checked.
* @return A subquery that can be used in an exists statement to see if a topic has a property tag.
*/
protected abstract Subquery<U> getPropertyTagExistsSubquery(final Integer propertyTagId);
}
| true | true | public void processField(final FilterFieldDataBase<?> field) {
final String fieldName = field.getBaseName();
if (fieldName.equals(CommonFilterConstants.PROPERTY_TAG_EXISTS)) {
final FilterFieldBooleanMapData mapField = (FilterFieldBooleanMapData) field;
for (final Map.Entry<Integer, Boolean> entry : mapField.getData().entrySet()) {
final Integer propertyTagId = entry.getKey();
final Boolean fieldValueBoolean = entry.getValue();
if (propertyTagId != null && fieldValueBoolean) {
addFieldCondition(getCriteriaBuilder().exists(getPropertyTagExistsSubquery(propertyTagId)));
}
}
} else if (fieldName.startsWith(CommonFilterConstants.PROPERTY_TAG_NOT_EXISTS)) {
final FilterFieldBooleanMapData mapField = (FilterFieldBooleanMapData) field;
for (final Map.Entry<Integer, Boolean> entry : mapField.getData().entrySet()) {
final Integer propertyTagId = entry.getKey();
final Boolean fieldValueBoolean = entry.getValue();
if (propertyTagId != null && fieldValueBoolean) {
addFieldCondition(getCriteriaBuilder().not(getCriteriaBuilder().exists(getPropertyTagExistsSubquery(propertyTagId))));
}
}
} else if (fieldName.startsWith(CommonFilterConstants.PROPERTY_TAG)) {
final FilterFieldStringMapData mapField = (FilterFieldStringMapData) field;
for (final Map.Entry<Integer, String> entry : mapField.getData().entrySet()) {
final Integer propertyTagId = entry.getKey();
final String fieldValue = entry.getValue();
if (propertyTagId != null && fieldValue != null) {
addExistsCondition(getPropertyTagSubquery(propertyTagId, (String) field.getData()));
}
}
} else {
super.processField(field);
}
}
| public void processField(final FilterFieldDataBase<?> field) {
final String fieldName = field.getBaseName();
if (fieldName.equals(CommonFilterConstants.PROPERTY_TAG_EXISTS)) {
final FilterFieldBooleanMapData mapField = (FilterFieldBooleanMapData) field;
for (final Map.Entry<Integer, Boolean> entry : mapField.getData().entrySet()) {
final Integer propertyTagId = entry.getKey();
final Boolean fieldValueBoolean = entry.getValue();
if (propertyTagId != null && fieldValueBoolean) {
addFieldCondition(getCriteriaBuilder().exists(getPropertyTagExistsSubquery(propertyTagId)));
}
}
} else if (fieldName.startsWith(CommonFilterConstants.PROPERTY_TAG_NOT_EXISTS)) {
final FilterFieldBooleanMapData mapField = (FilterFieldBooleanMapData) field;
for (final Map.Entry<Integer, Boolean> entry : mapField.getData().entrySet()) {
final Integer propertyTagId = entry.getKey();
final Boolean fieldValueBoolean = entry.getValue();
if (propertyTagId != null && fieldValueBoolean) {
addFieldCondition(getCriteriaBuilder().not(getCriteriaBuilder().exists(getPropertyTagExistsSubquery(propertyTagId))));
}
}
} else if (fieldName.startsWith(CommonFilterConstants.PROPERTY_TAG)) {
final FilterFieldStringMapData mapField = (FilterFieldStringMapData) field;
for (final Map.Entry<Integer, String> entry : mapField.getData().entrySet()) {
final Integer propertyTagId = entry.getKey();
final String fieldValue = entry.getValue();
if (propertyTagId != null && fieldValue != null) {
addExistsCondition(getPropertyTagSubquery(propertyTagId, fieldValue));
}
}
} else {
super.processField(field);
}
}
|
diff --git a/app/controllers/NewsFeedController.java b/app/controllers/NewsFeedController.java
index 4f65d35..6cec56f 100644
--- a/app/controllers/NewsFeedController.java
+++ b/app/controllers/NewsFeedController.java
@@ -1,432 +1,432 @@
package controllers;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import net.htmlparser.jericho.Attribute;
import net.htmlparser.jericho.Attributes;
import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.MasonTagTypes;
import net.htmlparser.jericho.MicrosoftConditionalCommentTagTypes;
import net.htmlparser.jericho.PHPTagTypes;
import net.htmlparser.jericho.Segment;
import net.htmlparser.jericho.Source;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ObjectNode;
import play.Logger;
import play.libs.F.Callback;
import play.libs.F.Callback0;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.WebSocket;
import play.mvc.WebSocket.Out;
/**
* @author romanelm
*/
public class NewsFeedController extends Controller {
public static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
final static Runnable beeper = new Runnable() {
public void run() {
updatePools();
Logger.info("\n ---------------------- \n"+
"HOT: " + HOT_POOL.size() + "\n" +
"TECH: " + TECH_POOL.size() + "\n" +
"SPORT: " + SPORT_POOL.size() + "\n" +
"CULTURE: " + CULTURE_POOL.size() + "\n ----------------------");
}
};
/**
* Hashmap that given an ID of a Display, returns
* a Sockets object containing 2 websockets: one for the small view
* and one for the big one.
*/
public static HashMap<String, Sockets> sockets = new HashMap<String, Sockets>();
public static HashMap<String, Status> statuses = new HashMap<String, NewsFeedController.Status>();
/**
* POOLS: hot, tech, sport, culture
* ONE TO ONE CORRESPONDANCE WITH IMGS ARRAY
*/
public static Integer HOT_ID = 0;
public static String[] HOT_SRC = {"http://ansa.feedsportal.com/c/34225/f/621689/index.rss"};
public static String[] HOT_SRC_IMGS = {"http://www.siamotuttialdopecora.org/wp-content/uploads/2012/03/ANSA_logo-618x618.png"};
public static ArrayList<ObjectNode> HOT_POOL = new ArrayList<ObjectNode>();
public static Integer TECH_ID = 0;
public static String[] TECH_SRC = {"http://www.engadget.com/rss.xml", "http://feeds.feedburner.com/ispazio", "http://feeds.wired.com/wired/index?format=xml"};
public static String[] TECH_SRC_IMGS = {"http://img.engadget.com/common/images/2768755886686308.JPG?0.6202710638260707", "http://userserve-ak.last.fm/serve/_/13831463/Wiredcom+wired_logo.gif"};
public static ArrayList<ObjectNode> TECH_POOL = new ArrayList<ObjectNode>();
public static Integer SPORT_ID = 0;
public static String[] SPORT_SRC = {"http://www.gazzetta.it/rss/Home.xml", "http://sports.espn.go.com/espn/rss/news"};
public static String[] SPORT_SRC_IMGS = {"http://forzaitalianfootball.com/wp-content/uploads/2011/07/gazzetta-dello-sport-logo.png", "http://960kgkl.com/files/2012/05/espn_logo11.jpg"};
public static ArrayList<ObjectNode> SPORT_POOL = new ArrayList<ObjectNode>();
public static Integer CULTURE_ID = 0;
public static String[] CULTURE_SRC = {"http://feeds.feedburner.com/ilblogdeilibri?format=xml", "http://feeds2.feedburner.com/slashfilm"};
public static String[] CULTURE_SRC_IMGS = {"http://www.ilblogdeilibri.com/wp-content/uploads/libri-da-gustare.jpg", "http://kaispace.files.wordpress.com/2010/09/slashfilm.jpg"};
public static ArrayList<ObjectNode> CULTURE_POOL = new ArrayList<ObjectNode>();
public static boolean STARTED = false;
public static WebSocket<JsonNode> webSocket() {
return new WebSocket<JsonNode>() {
// Called when the Websocket Handshake is done.
public void onReady(WebSocket.In<JsonNode> in, final WebSocket.Out<JsonNode> out) {
in.onMessage(new Callback<JsonNode>() {
public void invoke(JsonNode event) {
Logger.info("INCOMING MESSAGE ON NEWSFEED WS:\n"
+ event.toString());
String messageKind = event.get("kind").asText();
String displayID = event.get("displayID").asText();
if(!sockets.containsKey(displayID)){
sockets.put(displayID, new Sockets(null, null));
Logger.info("DisplayID " + displayID + " was added to the system.");
}
if(messageKind.equals("appReady")){
if(!STARTED){
STARTED = true;
final ScheduledFuture<?> beeperHandle =
- scheduler.scheduleAtFixedRate(beeper, 10, 5, TimeUnit.MINUTES);
+ scheduler.scheduleAtFixedRate(beeper, 5, 300, SECONDS);
scheduler.schedule(new Runnable() {
public void run() { beeperHandle.cancel(true); }
}, 1, TimeUnit.DAYS);
}
// Can be either small or big
String size = event.get("size").asText();
if(size.equals("small")){
// Set the socket
sockets.get(displayID).small = out;
// Initialize the status of the screen
statuses.put(displayID, new Status());
} else if(size.equals("big")) {
sockets.get(displayID).big = out;
}
Logger.info(
"\n ******* MESSAGE RECIEVED *******" +
"\n The "+ size + " view of \n" +
"newsfeed app is now available on displayID: " + displayID +
"\n*********************************"
);
} else if(messageKind.equals("mobileRequest")){
// String username = event.get("username").asText();
JsonNode pref = Json.toJson(event.get("preference"));
Sockets displaySockets = sockets.get(displayID);
Status displayStatus = statuses.get(displayID);
updateStatus(displayStatus,pref);
ObjectNode response = createResponse(displayStatus, pref);
displaySockets.small.write(response);
displaySockets.big.write(response);
Logger.info("JSON SENT TO THE DISPLAY!");
} else if(messageKind.equals("more")){
Status displayStatus = statuses.get(displayID);
Sockets displaySockets = sockets.get(displayID);
ObjectNode temp = Json.newObject();
temp.put("hot", displayStatus.hot ? true : false);
temp.put("tech", displayStatus.tech ? true : false);
temp.put("sport", displayStatus.sport ? true : false);
temp.put("culture", displayStatus.culture ? true : false);
Logger.info(temp.toString());
ObjectNode response = createResponse(displayStatus, temp);
response.put("pos",event.get("pos").asText());
String from = event.get("from").asText();
if(from.equals("small")){
displaySockets.small.write(response);
} else if (from.equals("big")){
displaySockets.big.write(response);
}
Logger.info("JSON SENT TO THE DISPLAY!");
} else {
Logger.info("WTF: " + event.toString());
}
}
});
// When the socket is closed.
in.onClose(new Callback0() {
public void invoke() {
Logger.info("\n ******* MESSAGE RECIEVED *******" +
"\n A weather tile on " + "TODO" +
"\n is now disconnected." +
"\n*********************************"
);
}
});
}
};
}
public static void updateStatus(Status status, JsonNode pref) {
if(pref.get("hot").asBoolean() && !status.hot){
status.hot = true;
}
if(pref.get("tech").asBoolean() && !status.tech){
status.tech = true;
}
if(pref.get("sport").asBoolean() && !status.sport){
status.sport = true;
}
if(pref.get("culture").asBoolean() && !status.culture){
status.culture = true;
}
}
public static int findLastIndex(ArrayList<ObjectNode> pool, int start, int qty){
try {
int end = start+qty;
pool.subList(start, end);
return end;
} catch (IndexOutOfBoundsException e) {
return pool.size();
}
}
public static ObjectNode createResponse(Status status, JsonNode pref){
Logger.info("TAKING NEWS FROM POOLS");
ObjectNode response = Json.newObject();
if(pref.get("hot").asBoolean() && (HOT_POOL.size() > status.last_hot) ){
int lastIndex = findLastIndex(HOT_POOL, status.last_hot, 10);
response.put("hot",Json.toJson(HOT_POOL.subList(status.last_hot, lastIndex)));
status.last_hot = lastIndex;
}
if(pref.get("tech").asBoolean() && (TECH_POOL.size() > status.last_tech) ){
int lastIndex = findLastIndex(TECH_POOL, status.last_tech, 10);
response.put("tech",Json.toJson(TECH_POOL.subList(status.last_tech, lastIndex)));
status.last_tech = lastIndex;
}
if(pref.get("sport").asBoolean() && (SPORT_POOL.size() > status.last_sport) ){
int lastIndex = findLastIndex(SPORT_POOL, status.last_sport, 10);
response.put("sport",Json.toJson(SPORT_POOL.subList(status.last_sport, lastIndex)));
status.last_sport = lastIndex;
}
if(pref.get("culture").asBoolean() && (CULTURE_POOL.size() > status.last_culture) ){
int lastIndex = findLastIndex(CULTURE_POOL, status.last_culture, 10);
response.put("culture",Json.toJson(CULTURE_POOL.subList(status.last_culture, lastIndex)));
status.last_culture = lastIndex;
}
return response;
}
public static JsonNode xmlToJSON(String feedURL) {
String baseURL = "https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=" + feedURL + "&num=100";
try {
URL url = new URL(baseURL);
URLConnection connection = url.openConnection();
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while((line = reader.readLine()) != null) {
builder.append(line);
}
ObjectMapper mapper = new ObjectMapper();
JsonNode df = mapper.readValue(builder.toString(), JsonNode.class);
return df;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Given a JSON containing a set of feeds sources,
* it returns a new JSON containing the titles of the various
* news.
* @param json of feeds recieved from the mobile
* @return
*/
public static void updatePools() {
try {
extractInformations(HOT_SRC, HOT_POOL, HOT_SRC_IMGS);
extractInformations(TECH_SRC, TECH_POOL, TECH_SRC_IMGS);
extractInformations(SPORT_SRC, SPORT_POOL, SPORT_SRC_IMGS);
extractInformations(CULTURE_SRC, CULTURE_POOL, CULTURE_SRC_IMGS);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
/**
* Check if the current news in already present
* in the pool
* @param pool
* @param newsContent
* @return
*/
public static boolean isNew(ArrayList<ObjectNode> pool, String newsContent){
for(ObjectNode currentNews: pool){
String currentNewsContent = currentNews.get("content").asText();
if(newsContent.equals(currentNewsContent)) return false;
}
return true;
}
public static void extractInformations(String[] feeds, ArrayList<ObjectNode> pool, String[] imgSrc) throws MalformedURLException {
int index = 0;
for (String feed : feeds){
JsonNode jsonFeed = xmlToJSON(feed).get("responseData").get("feed");
String newsSource = jsonFeed.get("title").asText();
Logger.info("PROCESSING: " + newsSource);
Iterator<JsonNode> entries = jsonFeed.get("entries").getElements();
while(entries.hasNext()){
JsonNode currentEntry = entries.next();
ObjectNode currentNews = Json.newObject();
currentNews.put("source", newsSource);
String content = currentEntry.get("content").asText();
if(content == null){
continue;
}
if(!isNew(pool, content)){
continue;
}
// Logger.info("new item of " + newsSource + " is being processed...");
String link = currentEntry.get("link").asText();
MicrosoftConditionalCommentTagTypes.register();
PHPTagTypes.register();
PHPTagTypes.PHP_SHORT.deregister();
MasonTagTypes.register();
Source source;
ArrayList<String> imgs = new ArrayList<String>();
imgs.add(imgSrc[index]);
try {
source = new Source(new URL(link));
List<Element> elementList = source.getAllElements(HTMLElementName.IMG);
for (Segment segment : elementList) {
Attributes tagAttr = segment.getFirstStartTag().getAttributes();
if(tagAttr == null) continue;
final Attribute alt = tagAttr.get("alt");
if(alt == null) continue;
Integer width = 0;
if(tagAttr.getValue("width") != null){
width = new Integer(tagAttr.getValue("width"));
}
Integer height = 0;
if(tagAttr.getValue("height") != null){
height = new Integer(tagAttr.getValue("height"));
}
if (alt!=null &&
(
(width > 100 && height > 100) ||
(width > 400 && height == 0) ||
(height > 400 && width == 0)
)
)
{
imgs.add(segment.toString());
} else {
//Logger.info("NOT APPROPRIATE \n" + "------------------------------------------------- \n");
}
}
} catch (IOException e) {
e.printStackTrace();
}
currentNews.put("link", link);
String title = currentEntry.get("title").asText();
if(title == null) continue;
currentNews.put("title", title);
currentNews.put("content", content);
currentNews.put("imgs", Json.toJson(imgs));
pool.add(currentNews);
index++;
}
}
}
public static class Sockets {
public WebSocket.Out<JsonNode> small;
public WebSocket.Out<JsonNode> big;
public Sockets(Out<JsonNode> small, Out<JsonNode> big) {
this.small = small;
this.big = big;
}
}
// IF THE POOL IS MODIFIED
public static class Status {
public boolean hot, tech, sport, culture;
public int last_hot, last_tech,last_sport,last_culture;
public Status() {
this.hot = this.tech = this.sport = this.culture = false;
this.last_hot = this.last_tech = this.last_sport = this.last_culture = 0;
}
}
}
| true | true | public static WebSocket<JsonNode> webSocket() {
return new WebSocket<JsonNode>() {
// Called when the Websocket Handshake is done.
public void onReady(WebSocket.In<JsonNode> in, final WebSocket.Out<JsonNode> out) {
in.onMessage(new Callback<JsonNode>() {
public void invoke(JsonNode event) {
Logger.info("INCOMING MESSAGE ON NEWSFEED WS:\n"
+ event.toString());
String messageKind = event.get("kind").asText();
String displayID = event.get("displayID").asText();
if(!sockets.containsKey(displayID)){
sockets.put(displayID, new Sockets(null, null));
Logger.info("DisplayID " + displayID + " was added to the system.");
}
if(messageKind.equals("appReady")){
if(!STARTED){
STARTED = true;
final ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 10, 5, TimeUnit.MINUTES);
scheduler.schedule(new Runnable() {
public void run() { beeperHandle.cancel(true); }
}, 1, TimeUnit.DAYS);
}
// Can be either small or big
String size = event.get("size").asText();
if(size.equals("small")){
// Set the socket
sockets.get(displayID).small = out;
// Initialize the status of the screen
statuses.put(displayID, new Status());
} else if(size.equals("big")) {
sockets.get(displayID).big = out;
}
Logger.info(
"\n ******* MESSAGE RECIEVED *******" +
"\n The "+ size + " view of \n" +
"newsfeed app is now available on displayID: " + displayID +
"\n*********************************"
);
} else if(messageKind.equals("mobileRequest")){
// String username = event.get("username").asText();
JsonNode pref = Json.toJson(event.get("preference"));
Sockets displaySockets = sockets.get(displayID);
Status displayStatus = statuses.get(displayID);
updateStatus(displayStatus,pref);
ObjectNode response = createResponse(displayStatus, pref);
displaySockets.small.write(response);
displaySockets.big.write(response);
Logger.info("JSON SENT TO THE DISPLAY!");
} else if(messageKind.equals("more")){
Status displayStatus = statuses.get(displayID);
Sockets displaySockets = sockets.get(displayID);
ObjectNode temp = Json.newObject();
temp.put("hot", displayStatus.hot ? true : false);
temp.put("tech", displayStatus.tech ? true : false);
temp.put("sport", displayStatus.sport ? true : false);
temp.put("culture", displayStatus.culture ? true : false);
Logger.info(temp.toString());
ObjectNode response = createResponse(displayStatus, temp);
response.put("pos",event.get("pos").asText());
String from = event.get("from").asText();
if(from.equals("small")){
displaySockets.small.write(response);
} else if (from.equals("big")){
displaySockets.big.write(response);
}
Logger.info("JSON SENT TO THE DISPLAY!");
} else {
Logger.info("WTF: " + event.toString());
}
}
});
// When the socket is closed.
in.onClose(new Callback0() {
public void invoke() {
Logger.info("\n ******* MESSAGE RECIEVED *******" +
"\n A weather tile on " + "TODO" +
"\n is now disconnected." +
"\n*********************************"
);
}
});
}
};
}
| public static WebSocket<JsonNode> webSocket() {
return new WebSocket<JsonNode>() {
// Called when the Websocket Handshake is done.
public void onReady(WebSocket.In<JsonNode> in, final WebSocket.Out<JsonNode> out) {
in.onMessage(new Callback<JsonNode>() {
public void invoke(JsonNode event) {
Logger.info("INCOMING MESSAGE ON NEWSFEED WS:\n"
+ event.toString());
String messageKind = event.get("kind").asText();
String displayID = event.get("displayID").asText();
if(!sockets.containsKey(displayID)){
sockets.put(displayID, new Sockets(null, null));
Logger.info("DisplayID " + displayID + " was added to the system.");
}
if(messageKind.equals("appReady")){
if(!STARTED){
STARTED = true;
final ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 5, 300, SECONDS);
scheduler.schedule(new Runnable() {
public void run() { beeperHandle.cancel(true); }
}, 1, TimeUnit.DAYS);
}
// Can be either small or big
String size = event.get("size").asText();
if(size.equals("small")){
// Set the socket
sockets.get(displayID).small = out;
// Initialize the status of the screen
statuses.put(displayID, new Status());
} else if(size.equals("big")) {
sockets.get(displayID).big = out;
}
Logger.info(
"\n ******* MESSAGE RECIEVED *******" +
"\n The "+ size + " view of \n" +
"newsfeed app is now available on displayID: " + displayID +
"\n*********************************"
);
} else if(messageKind.equals("mobileRequest")){
// String username = event.get("username").asText();
JsonNode pref = Json.toJson(event.get("preference"));
Sockets displaySockets = sockets.get(displayID);
Status displayStatus = statuses.get(displayID);
updateStatus(displayStatus,pref);
ObjectNode response = createResponse(displayStatus, pref);
displaySockets.small.write(response);
displaySockets.big.write(response);
Logger.info("JSON SENT TO THE DISPLAY!");
} else if(messageKind.equals("more")){
Status displayStatus = statuses.get(displayID);
Sockets displaySockets = sockets.get(displayID);
ObjectNode temp = Json.newObject();
temp.put("hot", displayStatus.hot ? true : false);
temp.put("tech", displayStatus.tech ? true : false);
temp.put("sport", displayStatus.sport ? true : false);
temp.put("culture", displayStatus.culture ? true : false);
Logger.info(temp.toString());
ObjectNode response = createResponse(displayStatus, temp);
response.put("pos",event.get("pos").asText());
String from = event.get("from").asText();
if(from.equals("small")){
displaySockets.small.write(response);
} else if (from.equals("big")){
displaySockets.big.write(response);
}
Logger.info("JSON SENT TO THE DISPLAY!");
} else {
Logger.info("WTF: " + event.toString());
}
}
});
// When the socket is closed.
in.onClose(new Callback0() {
public void invoke() {
Logger.info("\n ******* MESSAGE RECIEVED *******" +
"\n A weather tile on " + "TODO" +
"\n is now disconnected." +
"\n*********************************"
);
}
});
}
};
}
|
diff --git a/Java_CCN/com/parc/ccn/security/keys/BasicKeyManager.java b/Java_CCN/com/parc/ccn/security/keys/BasicKeyManager.java
index 40ef9459d..096e4ee8c 100644
--- a/Java_CCN/com/parc/ccn/security/keys/BasicKeyManager.java
+++ b/Java_CCN/com/parc/ccn/security/keys/BasicKeyManager.java
@@ -1,420 +1,419 @@
package com.parc.ccn.security.keys;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import com.parc.ccn.Library;
import com.parc.ccn.config.ConfigurationException;
import com.parc.ccn.config.SystemConfiguration;
import com.parc.ccn.config.UserConfiguration;
import com.parc.ccn.config.SystemConfiguration.DEBUGGING_FLAGS;
import com.parc.ccn.data.ContentName;
import com.parc.ccn.data.security.KeyLocator;
import com.parc.ccn.data.security.PublisherID;
import com.parc.ccn.data.security.PublisherPublicKeyDigest;
import com.parc.security.crypto.certificates.BCX509CertificateGenerator;
public class BasicKeyManager extends KeyManager {
protected KeyStore _keystore = null;
protected String _defaultAlias = null;
protected PublisherPublicKeyDigest _defaultKeyID = null;
protected X509Certificate _certificate = null;
protected PrivateKey _privateKey = null;
protected KeyLocator _keyLocator = null;
protected boolean _initialized = false;
protected KeyRepository _keyRepository = null;
private char [] _password = null;
public BasicKeyManager() throws ConfigurationException, IOException {
_keyRepository = new KeyRepository();
// must call initialize
}
/**
* Separate this for the usual reasons; so subclasses can get set up before it's called.
* Could make fake base class constructor, and call loadKeyStore in subclass constructors,
* but this wouldn't work past one level, and this allows subclasses to override initialize behavior.
* @throws ConfigurationException
*/
public synchronized void initialize() throws ConfigurationException {
if (_initialized)
return;
loadKeyStore();
_initialized = true;
}
protected boolean initialized() { return _initialized; }
protected void setPassword(char [] password) {
_password = password;
}
protected void loadKeyStore() throws ConfigurationException {
File keyStoreFile = new File(UserConfiguration.keystoreFileName());
if (!keyStoreFile.exists()) {
Library.logger().info("Creating new CCN key store..." + UserConfiguration.keystoreFileName());
_keystore = createKeyStore();
}
if (null == _keystore) {
FileInputStream in = null;
Library.logger().info("Loading CCN key store from " + UserConfiguration.keystoreFileName() + "...");
try {
_password = UserConfiguration.keystorePassword().toCharArray();
in = new FileInputStream(UserConfiguration.keystoreFileName());
loadKeyStore(in);
} catch (FileNotFoundException e) {
Library.logger().warning("Cannot open existing key store file: " + UserConfiguration.keystoreFileName());
throw new ConfigurationException("Cannot open existing key store file: " + UserConfiguration.keystoreFileName());
}
}
}
/**
* Must have set _password.
* @param in
* @throws ConfigurationException
*/
protected void loadKeyStore(InputStream in) throws ConfigurationException {
if (null == _keystore) {
try {
- Library.logger().info("Loading CCN key store from " + UserConfiguration.keystoreFileName() + "...");
+ Library.logger().info("Loading CCN key store...");
_keystore = KeyStore.getInstance(UserConfiguration.defaultKeystoreType());
- in = new FileInputStream(UserConfiguration.keystoreFileName());
_keystore.load(in, _password);
} catch (NoSuchAlgorithmException e) {
- Library.logger().warning("Cannot load default keystore.");
- throw new ConfigurationException("Cannot load default keystore: " + UserConfiguration.keystoreFileName()+ ".");
+ Library.logger().warning("Cannot load keystore: " + e);
+ throw new ConfigurationException("Cannot load default keystore: " + e);
} catch (CertificateException e) {
- Library.logger().warning("Cannot load default keystore with no certificates.");
- throw new ConfigurationException("Cannot load default keystore with no certificates.");
+ Library.logger().warning("Cannot load keystore with no certificates.");
+ throw new ConfigurationException("Cannot load keystore with no certificates.");
} catch (IOException e) {
- Library.logger().warning("Cannot open existing key store file: " + UserConfiguration.keystoreFileName() + ": " + e.getMessage());
+ Library.logger().warning("Cannot open existing key store: " + e);
throw new ConfigurationException(e);
} catch (KeyStoreException e) {
- Library.logger().warning("Cannot create instance of preferred key store type: " + e.getMessage());
+ Library.logger().warning("Cannot create instance of preferred key store type: " + UserConfiguration.defaultKeystoreType() + " " + e.getMessage());
Library.warningStackTrace(e);
- throw new ConfigurationException("Cannot create instance of default key store type: " + e.getMessage());
+ throw new ConfigurationException("Cannot create instance of default key store type: " + UserConfiguration.defaultKeystoreType() + " " + e.getMessage());
} finally {
if (null != in)
try {
in.close();
} catch (IOException e) {
Library.logger().warning("IOException closing key store file after load.");
Library.warningStackTrace(e);
}
}
}
_defaultAlias = UserConfiguration.defaultKeyAlias();
KeyStore.PrivateKeyEntry entry = null;
try {
entry = (KeyStore.PrivateKeyEntry)_keystore.getEntry(_defaultAlias, new KeyStore.PasswordProtection(_password));
if (null == entry) {
Library.logger().warning("Cannot get default key entry: " + _defaultAlias);
}
_privateKey = entry.getPrivateKey();
_certificate = (X509Certificate)entry.getCertificate();
_defaultKeyID = new PublisherPublicKeyDigest(_certificate.getPublicKey());
// Check to make sure we've published information about
// this key. (e.g. in testing, we may frequently
// nuke the contents of our repository even though the
// key remains, so need to republish). Or the first
// time we load this keystore, we need to publish.
ContentName keyName = getDefaultKeyName(_defaultKeyID.digest());
_keyLocator = new KeyLocator(keyName, new PublisherID(_defaultKeyID));
Library.logger().info("Default key locator: " + _keyLocator);
if (null == getKey(_defaultKeyID, _keyLocator)) {
boolean resetFlag = false;
if (SystemConfiguration.checkDebugFlag(DEBUGGING_FLAGS.DEBUG_SIGNATURES)) {
resetFlag = true;
SystemConfiguration.setDebugFlag(DEBUGGING_FLAGS.DEBUG_SIGNATURES, false);
}
keyRepository().publishKey(_keyLocator.name().name(), _certificate.getPublicKey(),
_defaultKeyID, _privateKey);
if (resetFlag) {
SystemConfiguration.setDebugFlag(DEBUGGING_FLAGS.DEBUG_SIGNATURES, true);
}
}
} catch (Exception e) {
generateConfigurationException("Cannot retrieve default user keystore entry.", e);
}
}
synchronized protected KeyStore createKeyStore() throws ConfigurationException {
File ccnDir = new File(UserConfiguration.ccnDirectory());
if (!ccnDir.exists()) {
if (!ccnDir.mkdirs()) {
generateConfigurationException("Cannot create user CCN directory: " + ccnDir.getAbsolutePath(), null);
}
}
// Alas, until 1.6, we can't set permissions on the file or directory...
// TODO DKS when switch to 1.6, add permission settings.
File keyStoreFile = new File(UserConfiguration.keystoreFileName());
if (keyStoreFile.exists())
return null;
_password = UserConfiguration.keystorePassword().toCharArray();
FileOutputStream out = null;
try {
out = new FileOutputStream(UserConfiguration.keystoreFileName());
} catch (FileNotFoundException e) {
generateConfigurationException("Cannot create keystore file: " + UserConfiguration.keystoreFileName(), e);
}
return createKeyStore(out);
}
synchronized protected KeyStore createKeyStore(OutputStream out) throws ConfigurationException {
KeyStore ks = null;
try {
ks = KeyStore.getInstance(UserConfiguration.defaultKeystoreType());
ks.load(null, _password);
} catch (NoSuchAlgorithmException e) {
generateConfigurationException("Cannot load empty default keystore.", e);
} catch (CertificateException e) {
generateConfigurationException("Cannot load empty default keystore with no certificates.", e);
} catch (KeyStoreException e) {
generateConfigurationException("Cannot create instance of default key store type.", e);
} catch (IOException e) {
generateConfigurationException("Cannot initialize instance of default key store type.", e);
}
KeyPairGenerator kpg = null;
try {
kpg = KeyPairGenerator.getInstance(UserConfiguration.defaultKeyAlgorithm());
} catch (NoSuchAlgorithmException e) {
generateConfigurationException("Cannot generate key using default algorithm: " + UserConfiguration.defaultKeyAlgorithm(), e);
}
kpg.initialize(UserConfiguration.defaultKeyLength());
KeyPair userKeyPair = kpg.generateKeyPair();
// Generate a self-signed certificate.
String subjectDN = "CN=" + UserConfiguration.userName();
X509Certificate ssCert = null;
try {
ssCert =
BCX509CertificateGenerator.GenerateX509Certificate(userKeyPair, subjectDN, BCX509CertificateGenerator.MSEC_IN_YEAR);
} catch (Exception e) {
generateConfigurationException("InvalidKeyException generating user internal certificate.", e);
}
KeyStore.PrivateKeyEntry entry =
new KeyStore.PrivateKeyEntry(userKeyPair.getPrivate(), new X509Certificate[]{ssCert});
try {
ks.setEntry(UserConfiguration.defaultKeyAlias(), entry,
new KeyStore.PasswordProtection(_password));
ks.store(out, _password);
} catch (NoSuchAlgorithmException e) {
generateConfigurationException("Cannot save default keystore.", e);
} catch (CertificateException e) {
generateConfigurationException("Cannot save default keystore with no certificates.", e);
} catch (KeyStoreException e) {
generateConfigurationException("Cannot set private key entry for user default key", e);
} catch (IOException e) {
generateConfigurationException("Cannot write keystore file: " + UserConfiguration.keystoreFileName(), e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
Library.logger().warning("IOException closing key store file after load.");
Library.warningStackTrace(e);
}
}
}
return ks;
}
static void generateConfigurationException(String message, Exception e) throws ConfigurationException {
Library.logger().warning(message + " " + e.getClass().getName() + ": " + e.getMessage());
Library.warningStackTrace(e);
throw new ConfigurationException(message, e);
}
public PublisherPublicKeyDigest getDefaultKeyID() {
return _defaultKeyID;
}
public PublicKey getDefaultPublicKey() {
return _certificate.getPublicKey();
}
public KeyLocator getDefaultKeyLocator() {
return _keyLocator;
}
public PrivateKey getDefaultSigningKey() {
return _privateKey;
}
/**
* The default key name is the publisher ID itself,
* under the user's key collection.
* @param keyID
* @return
*/
public ContentName getDefaultKeyName(byte [] keyID) {
ContentName keyDir =
ContentName.fromNative(UserConfiguration.defaultUserNamespace(),
UserConfiguration.defaultKeyName());
return new ContentName(keyDir, keyID);
}
public PublicKey getPublicKey(String alias) {
Certificate cert = null;;
try {
cert = _keystore.getCertificate(alias);
} catch (KeyStoreException e) {
Library.logger().info("No certificate for alias " + alias + " in BasicKeymManager keystore.");
return null;
}
return cert.getPublicKey();
}
public PrivateKey getSigningKey(String alias) {
PrivateKey key = null;;
try {
key = (PrivateKey)_keystore.getKey(alias, _password);
} catch (Exception e) {
Library.logger().info("No key for alias " + alias + " in BasicKeymManager keystore. " +
e.getClass().getName() + ": " + e.getMessage());
return null;
}
return key;
}
@Override
public PrivateKey [] getSigningKeys() {
// For now just return our default key. Eventually return multiple identity keys.
return new PrivateKey[]{getDefaultSigningKey()};
}
/**
* Find the key for the given publisher, using the
* available location information. Or, more generally,
* find a key at the given location that matches the
* given publisher information. If the publisher is an
* issuer, this gets tricky -- basically the information
* at the given location must be sufficient to get the
* right key.
* TODO DKS need to figure out how to decide what to do
* with a piece of content. In some sense, mime-types
* might make sense...
* @param publisher
* @param locator
* @return
* @throws IOException
* @throws InterruptedException
*/
public PublicKey getKey(PublisherPublicKeyDigest desiredKeyID,
KeyLocator locator) throws IOException, InterruptedException {
// DKS -- currently unused; contains some complex key validation behavior that
// will move into the trust managers.
// Otherwise, this is a name.
// First, try our local key repository. This will go to the network if it fails.
PublicKey key = _keyRepository.getPublicKey(desiredKeyID, locator);
return key;
}
@Override
public PublicKey getPublicKey(PublisherPublicKeyDigest publisher) throws IOException {
// TODO Auto-generated method stub
Library.logger().finer("getPublicKey: retrieving key: " + publisher);
if (_defaultKeyID.equals(publisher))
return _certificate.getPublicKey();
return keyRepository().getPublicKey(publisher);
}
@Override
public PrivateKey getSigningKey(PublisherID publisher) {
// TODO Auto-generated method stub
Library.logger().finer("getSigningKey: retrieving key: " + publisher);
if (_defaultKeyID.equals(publisher))
return _privateKey;
return null;
}
@Override
public PrivateKey getSigningKey(PublisherPublicKeyDigest publisher) {
// TODO Auto-generated method stub
Library.logger().finer("getSigningKey: retrieving key: " + publisher);
if (_defaultKeyID.equals(publisher))
return _privateKey;
return null;
}
@Override
public PublicKey getPublicKey(PublisherPublicKeyDigest publisherID, KeyLocator keyLocator) throws IOException, InterruptedException {
Library.logger().finer("getPublicKey: retrieving key: " + publisherID + " located at: " + keyLocator);
// this will try local caches, the locator itself, and if it
// has to, will go to the network. The result will be stored in the cache.
// All this tells us is that the key matches the publisher. For whether
// or not we should trust it for some reason, we have to get fancy.
return keyRepository().getPublicKey(publisherID, keyLocator);
}
@Override
public PublisherPublicKeyDigest getPublisherKeyID(PrivateKey signingKey) {
if (_privateKey.equals(signingKey))
return _defaultKeyID;
return null;
}
@Override
public KeyLocator getKeyLocator(PrivateKey signingKey) {
if (signingKey.equals(_privateKey))
return getDefaultKeyLocator();
// DKS TODO
return null;
}
@Override
public KeyRepository keyRepository() {
return _keyRepository;
}
@Override
public void publishKey(ContentName keyName,
PublisherPublicKeyDigest keyToPublish) throws IOException, InvalidKeyException, ConfigurationException {
PublicKey key = null;
if (null == keyToPublish) {
key = getDefaultPublicKey();
} else {
key = getPublicKey(keyToPublish);
if (null == key) {
throw new InvalidKeyException("Cannot retrieive key " + keyToPublish);
}
}
keyRepository().publishKey(keyName, key, getDefaultKeyID(), getDefaultSigningKey());
}
}
| false | true | protected void loadKeyStore(InputStream in) throws ConfigurationException {
if (null == _keystore) {
try {
Library.logger().info("Loading CCN key store from " + UserConfiguration.keystoreFileName() + "...");
_keystore = KeyStore.getInstance(UserConfiguration.defaultKeystoreType());
in = new FileInputStream(UserConfiguration.keystoreFileName());
_keystore.load(in, _password);
} catch (NoSuchAlgorithmException e) {
Library.logger().warning("Cannot load default keystore.");
throw new ConfigurationException("Cannot load default keystore: " + UserConfiguration.keystoreFileName()+ ".");
} catch (CertificateException e) {
Library.logger().warning("Cannot load default keystore with no certificates.");
throw new ConfigurationException("Cannot load default keystore with no certificates.");
} catch (IOException e) {
Library.logger().warning("Cannot open existing key store file: " + UserConfiguration.keystoreFileName() + ": " + e.getMessage());
throw new ConfigurationException(e);
} catch (KeyStoreException e) {
Library.logger().warning("Cannot create instance of preferred key store type: " + e.getMessage());
Library.warningStackTrace(e);
throw new ConfigurationException("Cannot create instance of default key store type: " + e.getMessage());
} finally {
if (null != in)
try {
in.close();
} catch (IOException e) {
Library.logger().warning("IOException closing key store file after load.");
Library.warningStackTrace(e);
}
}
}
_defaultAlias = UserConfiguration.defaultKeyAlias();
KeyStore.PrivateKeyEntry entry = null;
try {
entry = (KeyStore.PrivateKeyEntry)_keystore.getEntry(_defaultAlias, new KeyStore.PasswordProtection(_password));
if (null == entry) {
Library.logger().warning("Cannot get default key entry: " + _defaultAlias);
}
_privateKey = entry.getPrivateKey();
_certificate = (X509Certificate)entry.getCertificate();
_defaultKeyID = new PublisherPublicKeyDigest(_certificate.getPublicKey());
// Check to make sure we've published information about
// this key. (e.g. in testing, we may frequently
// nuke the contents of our repository even though the
// key remains, so need to republish). Or the first
// time we load this keystore, we need to publish.
ContentName keyName = getDefaultKeyName(_defaultKeyID.digest());
_keyLocator = new KeyLocator(keyName, new PublisherID(_defaultKeyID));
Library.logger().info("Default key locator: " + _keyLocator);
if (null == getKey(_defaultKeyID, _keyLocator)) {
boolean resetFlag = false;
if (SystemConfiguration.checkDebugFlag(DEBUGGING_FLAGS.DEBUG_SIGNATURES)) {
resetFlag = true;
SystemConfiguration.setDebugFlag(DEBUGGING_FLAGS.DEBUG_SIGNATURES, false);
}
keyRepository().publishKey(_keyLocator.name().name(), _certificate.getPublicKey(),
_defaultKeyID, _privateKey);
if (resetFlag) {
SystemConfiguration.setDebugFlag(DEBUGGING_FLAGS.DEBUG_SIGNATURES, true);
}
}
} catch (Exception e) {
generateConfigurationException("Cannot retrieve default user keystore entry.", e);
}
}
| protected void loadKeyStore(InputStream in) throws ConfigurationException {
if (null == _keystore) {
try {
Library.logger().info("Loading CCN key store...");
_keystore = KeyStore.getInstance(UserConfiguration.defaultKeystoreType());
_keystore.load(in, _password);
} catch (NoSuchAlgorithmException e) {
Library.logger().warning("Cannot load keystore: " + e);
throw new ConfigurationException("Cannot load default keystore: " + e);
} catch (CertificateException e) {
Library.logger().warning("Cannot load keystore with no certificates.");
throw new ConfigurationException("Cannot load keystore with no certificates.");
} catch (IOException e) {
Library.logger().warning("Cannot open existing key store: " + e);
throw new ConfigurationException(e);
} catch (KeyStoreException e) {
Library.logger().warning("Cannot create instance of preferred key store type: " + UserConfiguration.defaultKeystoreType() + " " + e.getMessage());
Library.warningStackTrace(e);
throw new ConfigurationException("Cannot create instance of default key store type: " + UserConfiguration.defaultKeystoreType() + " " + e.getMessage());
} finally {
if (null != in)
try {
in.close();
} catch (IOException e) {
Library.logger().warning("IOException closing key store file after load.");
Library.warningStackTrace(e);
}
}
}
_defaultAlias = UserConfiguration.defaultKeyAlias();
KeyStore.PrivateKeyEntry entry = null;
try {
entry = (KeyStore.PrivateKeyEntry)_keystore.getEntry(_defaultAlias, new KeyStore.PasswordProtection(_password));
if (null == entry) {
Library.logger().warning("Cannot get default key entry: " + _defaultAlias);
}
_privateKey = entry.getPrivateKey();
_certificate = (X509Certificate)entry.getCertificate();
_defaultKeyID = new PublisherPublicKeyDigest(_certificate.getPublicKey());
// Check to make sure we've published information about
// this key. (e.g. in testing, we may frequently
// nuke the contents of our repository even though the
// key remains, so need to republish). Or the first
// time we load this keystore, we need to publish.
ContentName keyName = getDefaultKeyName(_defaultKeyID.digest());
_keyLocator = new KeyLocator(keyName, new PublisherID(_defaultKeyID));
Library.logger().info("Default key locator: " + _keyLocator);
if (null == getKey(_defaultKeyID, _keyLocator)) {
boolean resetFlag = false;
if (SystemConfiguration.checkDebugFlag(DEBUGGING_FLAGS.DEBUG_SIGNATURES)) {
resetFlag = true;
SystemConfiguration.setDebugFlag(DEBUGGING_FLAGS.DEBUG_SIGNATURES, false);
}
keyRepository().publishKey(_keyLocator.name().name(), _certificate.getPublicKey(),
_defaultKeyID, _privateKey);
if (resetFlag) {
SystemConfiguration.setDebugFlag(DEBUGGING_FLAGS.DEBUG_SIGNATURES, true);
}
}
} catch (Exception e) {
generateConfigurationException("Cannot retrieve default user keystore entry.", e);
}
}
|
diff --git a/src/plugins/WebOfTrust/XMLTransformer.java b/src/plugins/WebOfTrust/XMLTransformer.java
index 25ac7749..778fce5c 100644
--- a/src/plugins/WebOfTrust/XMLTransformer.java
+++ b/src/plugins/WebOfTrust/XMLTransformer.java
@@ -1,722 +1,722 @@
/* This code is part of WoT, a plugin for Freenet. It is distributed
* under the GNU General Public License, version 2 (or at your option
* any later version). See http://www.gnu.org/ for details of the GPL. */
package plugins.WebOfTrust;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.TimeZone;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import plugins.WebOfTrust.Identity.FetchState;
import plugins.WebOfTrust.exceptions.InvalidParameterException;
import plugins.WebOfTrust.exceptions.NotInTrustTreeException;
import plugins.WebOfTrust.exceptions.NotTrustedException;
import plugins.WebOfTrust.exceptions.UnknownIdentityException;
import plugins.WebOfTrust.introduction.IntroductionPuzzle;
import com.db4o.ext.ExtObjectContainer;
import freenet.keys.FreenetURI;
import freenet.support.Base64;
import freenet.support.IllegalBase64Exception;
import freenet.support.Logger;
/**
* This class handles all XML creation and parsing of the WoT plugin, that is import and export of identities, identity introductions
* and introduction puzzles. The code for handling the XML related to identity introduction is not in a separate class in the WoT.Introduction
* package so that we do not need to create multiple instances of the XML parsers / pass the parsers to the other class.
*
* @author xor ([email protected])
*/
public final class XMLTransformer {
private static final int XML_FORMAT_VERSION = 1;
private static final int INTRODUCTION_XML_FORMAT_VERSION = 1;
/**
* Used by the IntroductionServer to limit the size of fetches to prevent DoS..
* The typical size of an identity introduction can be observed at {@link XMLTransformerTest}.
*/
public static final int MAX_INTRODUCTION_BYTE_SIZE = 1 * 1024;
/**
* Used by the IntroductionClient to limit the size of fetches to prevent DoS.
* The typical size of an introduction puzzle can be observed at {@link XMLTransformerTest}.
*/
public static final int MAX_INTRODUCTIONPUZZLE_BYTE_SIZE = 16 * 1024;
/**
* Maximal size of an identity XML file.
* TODO: We must soon introduce limits on the amount of trust values which an identity can assign, otherwise
* the WoT of some people will insert broken trust lists. Right now my seed identity of the testing WoT has 345 trustees
* and fits within 64 KiB so 256 should be enough until we have resolved this to-do.
*/
public static final int MAX_IDENTITY_XML_BYTE_SIZE = 256 * 1024;
private final WebOfTrust mWoT;
private final ExtObjectContainer mDB;
/* TODO: Check with a profiler how much memory this takes, do not cache it if it is too much */
/** Used for parsing the identity XML when decoding identities*/
private final DocumentBuilder mDocumentBuilder;
/* TODO: Check with a profiler how much memory this takes, do not cache it if it is too much */
/** Created by mDocumentBuilder, used for building the identity XML DOM when encoding identities */
private final DOMImplementation mDOM;
/* TODO: Check with a profiler how much memory this takes, do not cache it if it is too much */
/** Used for storing the XML DOM of encoded identities as physical XML text */
private final Transformer mSerializer;
private final SimpleDateFormat mDateFormat;
/* These booleans are used for preventing the construction of log-strings if logging is disabled (for saving some cpu cycles) */
private static volatile boolean logDEBUG = false;
private static volatile boolean logMINOR = false;
static {
Logger.registerClass(XMLTransformer.class);
}
/**
* Initializes the XML creator & parser and caches those objects in the new IdentityXML object so that they do not have to be initialized
* each time an identity is exported/imported.
*/
public XMLTransformer(WebOfTrust myWoT) {
mWoT = myWoT;
mDB = mWoT.getDatabase();
try {
DocumentBuilderFactory xmlFactory = DocumentBuilderFactory.newInstance();
xmlFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
// DOM parser uses .setAttribute() to pass to underlying Xerces
xmlFactory.setAttribute("http://apache.org/xml/features/disallow-doctype-decl", true);
mDocumentBuilder = xmlFactory.newDocumentBuilder();
mDOM = mDocumentBuilder.getDOMImplementation();
mSerializer = TransformerFactory.newInstance().newTransformer();
mSerializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
mSerializer.setOutputProperty(OutputKeys.INDENT, "yes"); // TODO: Disable as soon as bug 0004850 is fixed.
mSerializer.setOutputProperty(OutputKeys.STANDALONE, "no");
mDateFormat = new SimpleDateFormat("yyyy-MM-dd");
mDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
}
catch(Exception e) {
throw new RuntimeException(e);
}
}
public void exportOwnIdentity(OwnIdentity identity, OutputStream os) throws TransformerException {
Document xmlDoc;
synchronized(mDocumentBuilder) { // TODO: Figure out whether the DocumentBuilder is maybe synchronized anyway
xmlDoc = mDOM.createDocument(null, WebOfTrust.WOT_NAME, null);
}
// 1.0 does not support all Unicode characters which the String class supports. To prevent us from having to filter all Strings, we use 1.1
xmlDoc.setXmlVersion("1.1");
Element rootElement = xmlDoc.getDocumentElement();
// We include the WoT version to have an easy way of handling bogus XML which might be created by bugged versions.
rootElement.setAttribute("Version", Long.toString(Version.getRealVersion()));
/* Create the identity Element */
Element identityElement = xmlDoc.createElement("Identity");
identityElement.setAttribute("Version", Integer.toString(XML_FORMAT_VERSION)); /* Version of the XML format */
synchronized(mWoT) {
identityElement.setAttribute("Name", identity.getNickname());
identityElement.setAttribute("PublishesTrustList", Boolean.toString(identity.doesPublishTrustList()));
/* Create the context Elements */
for(String context : identity.getContexts()) {
Element contextElement = xmlDoc.createElement("Context");
contextElement.setAttribute("Name", context);
identityElement.appendChild(contextElement);
}
/* Create the property Elements */
for(Entry<String, String> property : identity.getProperties().entrySet()) {
Element propertyElement = xmlDoc.createElement("Property");
propertyElement.setAttribute("Name", property.getKey());
propertyElement.setAttribute("Value", property.getValue());
identityElement.appendChild(propertyElement);
}
/* Create the trust list Element and its trust Elements */
if(identity.doesPublishTrustList()) {
Element trustListElement = xmlDoc.createElement("TrustList");
for(Trust trust : mWoT.getGivenTrusts(identity)) {
/* We should make very sure that we do not reveal the other own identity's */
if(trust.getTruster() != identity)
throw new RuntimeException("Error in WoT: It is trying to export trust values of someone else in the trust list " +
"of " + identity + ": Trust value from " + trust.getTruster() + "");
Element trustElement = xmlDoc.createElement("Trust");
trustElement.setAttribute("Identity", trust.getTrustee().getRequestURI().toString());
trustElement.setAttribute("Value", Byte.toString(trust.getValue()));
trustElement.setAttribute("Comment", trust.getComment());
trustListElement.appendChild(trustElement);
}
identityElement.appendChild(trustListElement);
}
}
rootElement.appendChild(identityElement);
DOMSource domSource = new DOMSource(xmlDoc);
StreamResult resultStream = new StreamResult(os);
synchronized(mSerializer) { // TODO: Figure out whether the Serializer is maybe synchronized anyway
mSerializer.transform(domSource, resultStream);
}
}
/**
* Workaround class for:
* https://bugs.freenetproject.org/view.php?id=4850
* http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7031732
*
* @author [email protected]
*/
public class OneBytePerReadInputStream extends FilterInputStream {
public OneBytePerReadInputStream(InputStream in) {
super(in);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
return super.read(b, off, len<=1 ? len : 1);
}
}
private static final class ParsedIdentityXML {
static final class TrustListEntry {
final FreenetURI mTrusteeURI;
final byte mTrustValue;
final String mTrustComment;
public TrustListEntry(FreenetURI myTrusteeURI, byte myTrustValue, String myTrustComment) {
mTrusteeURI = myTrusteeURI;
mTrustValue = myTrustValue;
mTrustComment = myTrustComment;
}
}
Exception parseError = null;
String identityName = null;
Boolean identityPublishesTrustList = null;
ArrayList<String> identityContexts = null;
HashMap<String, String> identityProperties = null;
ArrayList<TrustListEntry> identityTrustList = null;
public ParsedIdentityXML() {
}
}
/**
* @param xmlInputStream An InputStream which must not return more than {@link MAX_IDENTITY_XML_BYTE_SIZE} bytes.
*/
private ParsedIdentityXML parseIdentityXML(InputStream xmlInputStream) throws IOException {
Logger.normal(this, "Parsing identity XML...");
xmlInputStream = new OneBytePerReadInputStream(xmlInputStream); // Workaround for Java bug, see the stream class for explanation
// May not be accurate by definition of available(). So the JavaDoc requires the callers to obey the size limit, this is a double-check.
if(xmlInputStream.available() > MAX_IDENTITY_XML_BYTE_SIZE)
throw new IllegalArgumentException("XML contains too many bytes: " + xmlInputStream.available());
final ParsedIdentityXML result = new ParsedIdentityXML();
try {
Document xmlDoc;
synchronized(mDocumentBuilder) { // TODO: Figure out whether the DocumentBuilder is maybe synchronized anyway
xmlDoc = mDocumentBuilder.parse(xmlInputStream);
}
final Element identityElement = (Element)xmlDoc.getElementsByTagName("Identity").item(0);
if(Integer.parseInt(identityElement.getAttribute("Version")) > XML_FORMAT_VERSION)
throw new Exception("Version " + identityElement.getAttribute("Version") + " > " + XML_FORMAT_VERSION);
result.identityName = identityElement.getAttribute("Name");
result.identityPublishesTrustList = Boolean.parseBoolean(identityElement.getAttribute("PublishesTrustList"));
final NodeList contextList = identityElement.getElementsByTagName("Context");
result.identityContexts = new ArrayList<String>(contextList.getLength() + 1);
for(int i = 0; i < contextList.getLength(); ++i) {
Element contextElement = (Element)contextList.item(i);
result.identityContexts.add(contextElement.getAttribute("Name"));
}
final NodeList propertyList = identityElement.getElementsByTagName("Property");
result.identityProperties = new HashMap<String, String>(propertyList.getLength() * 2);
for(int i = 0; i < propertyList.getLength(); ++i) {
Element propertyElement = (Element)propertyList.item(i);
result.identityProperties.put(propertyElement.getAttribute("Name"), propertyElement.getAttribute("Value"));
}
if(result.identityPublishesTrustList) {
final Element trustListElement = (Element)identityElement.getElementsByTagName("TrustList").item(0);
final NodeList trustList = trustListElement.getElementsByTagName("Trust");
result.identityTrustList = new ArrayList<ParsedIdentityXML.TrustListEntry>(trustList.getLength() + 1);
for(int i = 0; i < trustList.getLength(); ++i) {
Element trustElement = (Element)trustList.item(i);
result.identityTrustList.add(new ParsedIdentityXML.TrustListEntry(
new FreenetURI(trustElement.getAttribute("Identity")),
Byte.parseByte(trustElement.getAttribute("Value")),
trustElement.getAttribute("Comment")
));
}
}
} catch(Exception e) {
result.parseError = e;
}
Logger.normal(this, "Finished parsing identity XML.");
return result;
}
/**
* Imports a identity XML file into the given web of trust. This includes:
* - The identity itself and its attributes
* - The trust list of the identity, if it has published one in the XML.
*
* @param xmlInputStream The input stream containing the XML.
*/
public void importIdentity(FreenetURI identityURI, InputStream xmlInputStream) throws Exception {
try { // Catch import problems so we can mark the edition as parsing failed
// We first parse the XML without synchronization, then do the synchronized import into the WebOfTrust
final ParsedIdentityXML xmlData = parseIdentityXML(xmlInputStream);
synchronized(mWoT) {
synchronized(mWoT.getIdentityFetcher()) {
final Identity identity = mWoT.getIdentityByURI(identityURI);
Logger.normal(this, "Importing parsed XML for " + identity);
- long newEdition = identityURI.getEdition();
- if(identity.getEdition() > newEdition) {
- if(logDEBUG) Logger.debug(this, "Fetched an older edition: current == " + identity.getEdition() + "; fetched == " + identityURI.getEdition());
+ long newEdition = identityURI.getEdition();
+ if(identity.getEdition() > newEdition) {
+ if(logDEBUG) Logger.debug(this, "Fetched an older edition: current == " + identity.getEdition() + "; fetched == " + identityURI.getEdition());
+ return;
+ } else if(identity.getEdition() == newEdition) {
+ if(identity.getCurrentEditionFetchState() == FetchState.Fetched) {
+ if(logDEBUG) Logger.debug(this, "Fetched current edition which is marked as fetched already, not importing: " + identityURI);
return;
- } else if(identity.getEdition() == newEdition) {
- if(identity.getCurrentEditionFetchState() == FetchState.Fetched) {
- if(logDEBUG) Logger.debug(this, "Fetched current edition which is marked as fetched already, not importing: " + identityURI);
- return;
- } else if(identity.getCurrentEditionFetchState() == FetchState.ParsingFailed) {
- Logger.normal(this, "Re-fetched current-edition which was marked as parsing failed: " + identityURI);
- }
+ } else if(identity.getCurrentEditionFetchState() == FetchState.ParsingFailed) {
+ Logger.normal(this, "Re-fetched current-edition which was marked as parsing failed: " + identityURI);
}
+ }
- // We throw parse errors AFTER checking the edition number: If this XML was outdated anyway, we don't have to throw.
- if(xmlData.parseError != null)
- throw xmlData.parseError;
+ // We throw parse errors AFTER checking the edition number: If this XML was outdated anyway, we don't have to throw.
+ if(xmlData.parseError != null)
+ throw xmlData.parseError;
- synchronized(Persistent.transactionLock(mDB)) {
+ synchronized(Persistent.transactionLock(mDB)) {
try { // Transaction rollback block
identity.setEdition(newEdition); // The identity constructor only takes the edition number as a hint, so we must store it explicitly.
boolean didPublishTrustListPreviously = identity.doesPublishTrustList();
identity.setPublishTrustList(xmlData.identityPublishesTrustList);
try {
identity.setNickname(xmlData.identityName);
}
catch(Exception e) {
/* Nickname changes are not allowed, ignore them... */
Logger.error(this, "setNickname() failed.", e);
}
try { /* Failure of context importing should not make an identity disappear, therefore we catch exceptions. */
identity.setContexts(xmlData.identityContexts);
}
catch(Exception e) {
Logger.error(this, "setContexts() failed.", e);
}
try { /* Failure of property importing should not make an identity disappear, therefore we catch exceptions. */
identity.setProperties(xmlData.identityProperties);
}
catch(Exception e) {
Logger.error(this, "setProperties() failed", e);
}
mWoT.beginTrustListImport(); // We delete the old list if !identityPublishesTrustList and it did publish one earlier => we always call this.
if(xmlData.identityPublishesTrustList) {
// We import the trust list of an identity if it's score is equal to 0, but we only create new identities or import edition hints
// if the score is greater than 0. Solving a captcha therefore only allows you to create one single identity.
boolean positiveScore = false;
boolean hasCapacity = false;
// TODO: getBestScore/getBestCapacity should always yield a positive result because we store a positive score object for an OwnIdentity
// upon creation. The only case where it could not exist might be restoreIdentity() ... check that. If it is created there as well,
// remove the additional check here.
if(identity instanceof OwnIdentity) {
// Importing of OwnIdentities is always allowed
positiveScore = true;
hasCapacity = true;
} else {
try {
positiveScore = mWoT.getBestScore(identity) > 0;
hasCapacity = mWoT.getBestCapacity(identity) > 0;
}
catch(NotInTrustTreeException e) { }
}
HashSet<String> identitiesWithUpdatedEditionHint = null;
if(positiveScore) {
identitiesWithUpdatedEditionHint = new HashSet<String>(xmlData.identityTrustList.size() * 2);
}
for(final ParsedIdentityXML.TrustListEntry trustListEntry : xmlData.identityTrustList) {
final FreenetURI trusteeURI = trustListEntry.mTrusteeURI;
final byte trustValue = trustListEntry.mTrustValue;
final String trustComment = trustListEntry.mTrustComment;
Identity trustee = null;
try {
trustee = mWoT.getIdentityByURI(trusteeURI);
if(positiveScore) {
if(trustee.setNewEditionHint(trusteeURI.getEdition())) {
identitiesWithUpdatedEditionHint.add(trustee.getID());
trustee.storeWithoutCommit();
}
}
}
catch(UnknownIdentityException e) {
if(hasCapacity) { /* We only create trustees if the truster has capacity to rate them. */
try {
trustee = new Identity(mWoT, trusteeURI, null, false);
trustee.storeWithoutCommit();
} catch(MalformedURLException e2) {
/* Malformed URI in the trustlist. Log at minor since there
* is nothing the user can do anyway. */
if(logMINOR) {
Logger.minor(this,
"Caugth IllegalArgumentException while creating new " +
"Identity. Truster is " + identity + ", request URI " +
"is " + trusteeURI,
e2);
}
}
}
}
if(trustee != null)
mWoT.setTrustWithoutCommit(identity, trustee, trustValue, trustComment);
}
for(Trust trust : mWoT.getGivenTrustsOfDifferentEdition(identity, identityURI.getEdition())) {
mWoT.removeTrustWithoutCommit(trust);
}
IdentityFetcher identityFetcher = mWoT.getIdentityFetcher();
if(positiveScore) {
for(String id : identitiesWithUpdatedEditionHint)
identityFetcher.storeUpdateEditionHintCommandWithoutCommit(id);
// We do not have to store fetch commands for new identities here, setTrustWithoutCommit does it.
}
} else if(!xmlData.identityPublishesTrustList && didPublishTrustListPreviously && !(identity instanceof OwnIdentity)) {
// If it does not publish a trust list anymore, we delete all trust values it has given.
for(Trust trust : mWoT.getGivenTrusts(identity))
mWoT.removeTrustWithoutCommit(trust);
}
mWoT.finishTrustListImport();
identity.onFetched(); // Marks the identity as parsed successfully
identity.storeAndCommit();
}
- catch(Exception e) {
+ catch(Exception e) {
mWoT.abortTrustListImport(e); // Does the rollback
throw e;
} // try
- } // synchronized(Persistent.transactionLock(db))
+ } // synchronized(Persistent.transactionLock(db))
Logger.normal(this, "Finished XML import for " + identity);
} // synchronized(mWoT)
} // synchronized(mWoT.getIdentityFetcher())
} // try
catch(Exception e) {
synchronized(mWoT) {
synchronized(mWoT.getIdentityFetcher()) {
try {
final Identity identity = mWoT.getIdentityByURI(identityURI);
final long newEdition = identityURI.getEdition();
if(identity.getEdition() <= newEdition) {
Logger.normal(this, "Marking edition as parsing failed: " + identityURI);
identity.setEdition(newEdition);
identity.onParsingFailed();
identity.storeAndCommit();
} else {
Logger.normal(this, "Not marking edition as parsing failed, we have already fetched a new one (" +
identity.getEdition() + "):" + identityURI);
}
}
catch(UnknownIdentityException uie) {
Logger.error(this, "Fetched an unknown identity: " + identityURI);
}
}
}
throw e;
}
}
public void exportIntroduction(OwnIdentity identity, OutputStream os) throws TransformerException {
Document xmlDoc;
synchronized(mDocumentBuilder) { // TODO: Figure out whether the DocumentBuilder is maybe synchronized anyway
xmlDoc = mDOM.createDocument(null, WebOfTrust.WOT_NAME, null);
}
// 1.0 does not support all Unicode characters which the String class supports. To prevent us from having to filter all Strings, we use 1.1
xmlDoc.setXmlVersion("1.1");
Element rootElement = xmlDoc.getDocumentElement();
// We include the WoT version to have an easy way of handling bogus XML which might be created by bugged versions.
rootElement.setAttribute("Version", Long.toString(Version.getRealVersion()));
Element introElement = xmlDoc.createElement("IdentityIntroduction");
introElement.setAttribute("Version", Integer.toString(XML_FORMAT_VERSION)); /* Version of the XML format */
Element identityElement = xmlDoc.createElement("Identity");
// synchronized(mWoT) { // Not necessary according to JavaDoc of identity.getRequestURI()
identityElement.setAttribute("URI", identity.getRequestURI().toString());
//}
introElement.appendChild(identityElement);
rootElement.appendChild(introElement);
DOMSource domSource = new DOMSource(xmlDoc);
StreamResult resultStream = new StreamResult(os);
synchronized(mSerializer) { // TODO: Figure out whether the Serializer is maybe synchronized anyway
mSerializer.transform(domSource, resultStream);
}
}
/**
* Creates an identity from an identity introduction, stores it in the database and returns the new identity.
* If the identity already exists, the existing identity is returned.
*
* @param xmlInputStream An InputStream which must not return more than {@link MAX_INTRODUCTION_BYTE_SIZE} bytes.
* @throws InvalidParameterException If the XML format is unknown or if the puzzle owner does not allow introduction anymore.
* @throws IOException
* @throws SAXException
*/
public Identity importIntroduction(OwnIdentity puzzleOwner, InputStream xmlInputStream)
throws InvalidParameterException, SAXException, IOException {
xmlInputStream = new OneBytePerReadInputStream(xmlInputStream); // Workaround for Java bug, see the stream class for explanation
// May not be accurate by definition of available(). So the JavaDoc requires the callers to obey the size limit, this is a double-check.
if(xmlInputStream.available() > MAX_INTRODUCTION_BYTE_SIZE)
throw new IllegalArgumentException("XML contains too many bytes: " + xmlInputStream.available());
FreenetURI identityURI;
Identity newIdentity;
Document xmlDoc;
synchronized(mDocumentBuilder) { // TODO: Figure out whether the DocumentBuilder is maybe synchronized anyway
xmlDoc = mDocumentBuilder.parse(xmlInputStream);
}
Element introductionElement = (Element)xmlDoc.getElementsByTagName("IdentityIntroduction").item(0);
if(Integer.parseInt(introductionElement.getAttribute("Version")) > XML_FORMAT_VERSION)
throw new InvalidParameterException("Version " + introductionElement.getAttribute("Version") + " > " + XML_FORMAT_VERSION);
Element identityElement = (Element)introductionElement.getElementsByTagName("Identity").item(0);
identityURI = new FreenetURI(identityElement.getAttribute("URI"));
final IdentityFetcher identityFetcher = mWoT.getIdentityFetcher();
synchronized(mWoT) {
synchronized(identityFetcher) {
if(!puzzleOwner.hasContext(IntroductionPuzzle.INTRODUCTION_CONTEXT))
throw new InvalidParameterException("Trying to import an identity identroduction for an own identity which does not allow introduction.");
synchronized(Persistent.transactionLock(mDB)) {
try {
try {
newIdentity = mWoT.getIdentityByURI(identityURI);
if(logMINOR) Logger.minor(this, "Imported introduction for an already existing identity: " + newIdentity);
}
catch (UnknownIdentityException e) {
newIdentity = new Identity(mWoT, identityURI, null, false);
// We do NOT call setEdition(): An attacker might solve puzzles pretending to be someone else and publish bogus edition numbers for
// that identity by that. The identity constructor only takes the edition number as edition hint, this is the proper behavior.
// TODO: As soon as we have code for signing XML with an identity SSK we could sign the introduction XML and therefore prevent that
// attack.
//newIdentity.setEdition(identityURI.getEdition());
newIdentity.storeWithoutCommit();
if(logMINOR) Logger.minor(this, "Imported introduction for an unknown identity: " + newIdentity);
}
try {
mWoT.getTrust(puzzleOwner, newIdentity); /* Double check ... */
if(logMINOR) Logger.minor(this, "The identity is already trusted.");
}
catch(NotTrustedException ex) {
// 0 trust will not allow the import of other new identities for the new identity because the trust list import code will only create
// new identities if the score of an identity is > 0, not if it is equal to 0.
mWoT.setTrustWithoutCommit(puzzleOwner, newIdentity, (byte)0, "Trust received by solving a captcha.");
}
// setTrustWithoutCommit() does this for us.
// identityFetcher.storeStartFetchCommandWithoutCommit(newIdentity.getID());
newIdentity.checkedCommit(this);
}
catch(RuntimeException error) {
Persistent.checkedRollbackAndThrow(mDB, this, error);
throw error; // Satisfy the compiler
}
}
}
}
return newIdentity;
}
public void exportIntroductionPuzzle(IntroductionPuzzle puzzle, OutputStream os)
throws TransformerException, ParserConfigurationException {
Document xmlDoc;
synchronized(mDocumentBuilder) { // TODO: Figure out whether the DocumentBuilder is maybe synchronized anyway
xmlDoc = mDOM.createDocument(null, WebOfTrust.WOT_NAME, null);
}
// 1.0 does not support all Unicode characters which the String class supports. To prevent us from having to filter all Strings, we use 1.1
xmlDoc.setXmlVersion("1.1");
Element rootElement = xmlDoc.getDocumentElement();
// We include the WoT version to have an easy way of handling bogus XML which might be created by bugged versions.
rootElement.setAttribute("Version", Long.toString(Version.getRealVersion()));
Element puzzleElement = xmlDoc.createElement("IntroductionPuzzle");
puzzleElement.setAttribute("Version", Integer.toString(INTRODUCTION_XML_FORMAT_VERSION)); /* Version of the XML format */
// This lock is actually not necessary because all values which are taken from the puzzle are final. We leave it here just to make sure that it does
// not get lost if it becomes necessary someday.
synchronized(puzzle) {
puzzleElement.setAttribute("ID", puzzle.getID());
puzzleElement.setAttribute("Type", puzzle.getType().toString());
puzzleElement.setAttribute("MimeType", puzzle.getMimeType());
synchronized(mDateFormat) {
puzzleElement.setAttribute("ValidUntil", mDateFormat.format(puzzle.getValidUntilDate()));
}
Element dataElement = xmlDoc.createElement("Data");
dataElement.setAttribute("Value", Base64.encodeStandard(puzzle.getData()));
puzzleElement.appendChild(dataElement);
}
rootElement.appendChild(puzzleElement);
DOMSource domSource = new DOMSource(xmlDoc);
StreamResult resultStream = new StreamResult(os);
synchronized(mSerializer) {
mSerializer.transform(domSource, resultStream);
}
}
/**
* @param xmlInputStream An InputStream which must not return more than {@link MAX_INTRODUCTIONPUZZLE_BYTE_SIZE} bytes.
*/
public IntroductionPuzzle importIntroductionPuzzle(FreenetURI puzzleURI, InputStream xmlInputStream)
throws SAXException, IOException, InvalidParameterException, UnknownIdentityException, IllegalBase64Exception, ParseException {
xmlInputStream = new OneBytePerReadInputStream(xmlInputStream); // Workaround for Java bug, see the stream class for explanation
// May not be accurate by definition of available(). So the JavaDoc requires the callers to obey the size limit, this is a double-check.
if(xmlInputStream.available() > MAX_INTRODUCTIONPUZZLE_BYTE_SIZE)
throw new IllegalArgumentException("XML contains too many bytes: " + xmlInputStream.available());
String puzzleID;
IntroductionPuzzle.PuzzleType puzzleType;
String puzzleMimeType;
Date puzzleValidUntilDate;
byte[] puzzleData;
Document xmlDoc;
synchronized(mDocumentBuilder) { // TODO: Figure out whether the DocumentBuilder is maybe synchronized anyway
xmlDoc = mDocumentBuilder.parse(xmlInputStream);
}
Element puzzleElement = (Element)xmlDoc.getElementsByTagName("IntroductionPuzzle").item(0);
if(Integer.parseInt(puzzleElement.getAttribute("Version")) > INTRODUCTION_XML_FORMAT_VERSION)
throw new InvalidParameterException("Version " + puzzleElement.getAttribute("Version") + " > " + INTRODUCTION_XML_FORMAT_VERSION);
puzzleID = puzzleElement.getAttribute("ID");
puzzleType = IntroductionPuzzle.PuzzleType.valueOf(puzzleElement.getAttribute("Type"));
puzzleMimeType = puzzleElement.getAttribute("MimeType");
synchronized(mDateFormat) {
puzzleValidUntilDate = mDateFormat.parse(puzzleElement.getAttribute("ValidUntil"));
}
Element dataElement = (Element)puzzleElement.getElementsByTagName("Data").item(0);
puzzleData = Base64.decodeStandard(dataElement.getAttribute("Value"));
IntroductionPuzzle puzzle;
synchronized(mWoT) {
Identity puzzleInserter = mWoT.getIdentityByURI(puzzleURI);
puzzle = new IntroductionPuzzle(mWoT, puzzleInserter, puzzleID, puzzleType, puzzleMimeType, puzzleData,
IntroductionPuzzle.getDateFromRequestURI(puzzleURI), puzzleValidUntilDate, IntroductionPuzzle.getIndexFromRequestURI(puzzleURI));
mWoT.getIntroductionPuzzleStore().storeAndCommit(puzzle);
}
return puzzle;
}
}
| false | true | public void importIdentity(FreenetURI identityURI, InputStream xmlInputStream) throws Exception {
try { // Catch import problems so we can mark the edition as parsing failed
// We first parse the XML without synchronization, then do the synchronized import into the WebOfTrust
final ParsedIdentityXML xmlData = parseIdentityXML(xmlInputStream);
synchronized(mWoT) {
synchronized(mWoT.getIdentityFetcher()) {
final Identity identity = mWoT.getIdentityByURI(identityURI);
Logger.normal(this, "Importing parsed XML for " + identity);
long newEdition = identityURI.getEdition();
if(identity.getEdition() > newEdition) {
if(logDEBUG) Logger.debug(this, "Fetched an older edition: current == " + identity.getEdition() + "; fetched == " + identityURI.getEdition());
return;
} else if(identity.getEdition() == newEdition) {
if(identity.getCurrentEditionFetchState() == FetchState.Fetched) {
if(logDEBUG) Logger.debug(this, "Fetched current edition which is marked as fetched already, not importing: " + identityURI);
return;
} else if(identity.getCurrentEditionFetchState() == FetchState.ParsingFailed) {
Logger.normal(this, "Re-fetched current-edition which was marked as parsing failed: " + identityURI);
}
}
// We throw parse errors AFTER checking the edition number: If this XML was outdated anyway, we don't have to throw.
if(xmlData.parseError != null)
throw xmlData.parseError;
synchronized(Persistent.transactionLock(mDB)) {
try { // Transaction rollback block
identity.setEdition(newEdition); // The identity constructor only takes the edition number as a hint, so we must store it explicitly.
boolean didPublishTrustListPreviously = identity.doesPublishTrustList();
identity.setPublishTrustList(xmlData.identityPublishesTrustList);
try {
identity.setNickname(xmlData.identityName);
}
catch(Exception e) {
/* Nickname changes are not allowed, ignore them... */
Logger.error(this, "setNickname() failed.", e);
}
try { /* Failure of context importing should not make an identity disappear, therefore we catch exceptions. */
identity.setContexts(xmlData.identityContexts);
}
catch(Exception e) {
Logger.error(this, "setContexts() failed.", e);
}
try { /* Failure of property importing should not make an identity disappear, therefore we catch exceptions. */
identity.setProperties(xmlData.identityProperties);
}
catch(Exception e) {
Logger.error(this, "setProperties() failed", e);
}
mWoT.beginTrustListImport(); // We delete the old list if !identityPublishesTrustList and it did publish one earlier => we always call this.
if(xmlData.identityPublishesTrustList) {
// We import the trust list of an identity if it's score is equal to 0, but we only create new identities or import edition hints
// if the score is greater than 0. Solving a captcha therefore only allows you to create one single identity.
boolean positiveScore = false;
boolean hasCapacity = false;
// TODO: getBestScore/getBestCapacity should always yield a positive result because we store a positive score object for an OwnIdentity
// upon creation. The only case where it could not exist might be restoreIdentity() ... check that. If it is created there as well,
// remove the additional check here.
if(identity instanceof OwnIdentity) {
// Importing of OwnIdentities is always allowed
positiveScore = true;
hasCapacity = true;
} else {
try {
positiveScore = mWoT.getBestScore(identity) > 0;
hasCapacity = mWoT.getBestCapacity(identity) > 0;
}
catch(NotInTrustTreeException e) { }
}
HashSet<String> identitiesWithUpdatedEditionHint = null;
if(positiveScore) {
identitiesWithUpdatedEditionHint = new HashSet<String>(xmlData.identityTrustList.size() * 2);
}
for(final ParsedIdentityXML.TrustListEntry trustListEntry : xmlData.identityTrustList) {
final FreenetURI trusteeURI = trustListEntry.mTrusteeURI;
final byte trustValue = trustListEntry.mTrustValue;
final String trustComment = trustListEntry.mTrustComment;
Identity trustee = null;
try {
trustee = mWoT.getIdentityByURI(trusteeURI);
if(positiveScore) {
if(trustee.setNewEditionHint(trusteeURI.getEdition())) {
identitiesWithUpdatedEditionHint.add(trustee.getID());
trustee.storeWithoutCommit();
}
}
}
catch(UnknownIdentityException e) {
if(hasCapacity) { /* We only create trustees if the truster has capacity to rate them. */
try {
trustee = new Identity(mWoT, trusteeURI, null, false);
trustee.storeWithoutCommit();
} catch(MalformedURLException e2) {
/* Malformed URI in the trustlist. Log at minor since there
* is nothing the user can do anyway. */
if(logMINOR) {
Logger.minor(this,
"Caugth IllegalArgumentException while creating new " +
"Identity. Truster is " + identity + ", request URI " +
"is " + trusteeURI,
e2);
}
}
}
}
if(trustee != null)
mWoT.setTrustWithoutCommit(identity, trustee, trustValue, trustComment);
}
for(Trust trust : mWoT.getGivenTrustsOfDifferentEdition(identity, identityURI.getEdition())) {
mWoT.removeTrustWithoutCommit(trust);
}
IdentityFetcher identityFetcher = mWoT.getIdentityFetcher();
if(positiveScore) {
for(String id : identitiesWithUpdatedEditionHint)
identityFetcher.storeUpdateEditionHintCommandWithoutCommit(id);
// We do not have to store fetch commands for new identities here, setTrustWithoutCommit does it.
}
} else if(!xmlData.identityPublishesTrustList && didPublishTrustListPreviously && !(identity instanceof OwnIdentity)) {
// If it does not publish a trust list anymore, we delete all trust values it has given.
for(Trust trust : mWoT.getGivenTrusts(identity))
mWoT.removeTrustWithoutCommit(trust);
}
mWoT.finishTrustListImport();
identity.onFetched(); // Marks the identity as parsed successfully
identity.storeAndCommit();
}
catch(Exception e) {
mWoT.abortTrustListImport(e); // Does the rollback
throw e;
} // try
} // synchronized(Persistent.transactionLock(db))
Logger.normal(this, "Finished XML import for " + identity);
} // synchronized(mWoT)
} // synchronized(mWoT.getIdentityFetcher())
} // try
catch(Exception e) {
synchronized(mWoT) {
synchronized(mWoT.getIdentityFetcher()) {
try {
final Identity identity = mWoT.getIdentityByURI(identityURI);
final long newEdition = identityURI.getEdition();
if(identity.getEdition() <= newEdition) {
Logger.normal(this, "Marking edition as parsing failed: " + identityURI);
identity.setEdition(newEdition);
identity.onParsingFailed();
identity.storeAndCommit();
} else {
Logger.normal(this, "Not marking edition as parsing failed, we have already fetched a new one (" +
identity.getEdition() + "):" + identityURI);
}
}
catch(UnknownIdentityException uie) {
Logger.error(this, "Fetched an unknown identity: " + identityURI);
}
}
}
throw e;
}
}
| public void importIdentity(FreenetURI identityURI, InputStream xmlInputStream) throws Exception {
try { // Catch import problems so we can mark the edition as parsing failed
// We first parse the XML without synchronization, then do the synchronized import into the WebOfTrust
final ParsedIdentityXML xmlData = parseIdentityXML(xmlInputStream);
synchronized(mWoT) {
synchronized(mWoT.getIdentityFetcher()) {
final Identity identity = mWoT.getIdentityByURI(identityURI);
Logger.normal(this, "Importing parsed XML for " + identity);
long newEdition = identityURI.getEdition();
if(identity.getEdition() > newEdition) {
if(logDEBUG) Logger.debug(this, "Fetched an older edition: current == " + identity.getEdition() + "; fetched == " + identityURI.getEdition());
return;
} else if(identity.getEdition() == newEdition) {
if(identity.getCurrentEditionFetchState() == FetchState.Fetched) {
if(logDEBUG) Logger.debug(this, "Fetched current edition which is marked as fetched already, not importing: " + identityURI);
return;
} else if(identity.getCurrentEditionFetchState() == FetchState.ParsingFailed) {
Logger.normal(this, "Re-fetched current-edition which was marked as parsing failed: " + identityURI);
}
}
// We throw parse errors AFTER checking the edition number: If this XML was outdated anyway, we don't have to throw.
if(xmlData.parseError != null)
throw xmlData.parseError;
synchronized(Persistent.transactionLock(mDB)) {
try { // Transaction rollback block
identity.setEdition(newEdition); // The identity constructor only takes the edition number as a hint, so we must store it explicitly.
boolean didPublishTrustListPreviously = identity.doesPublishTrustList();
identity.setPublishTrustList(xmlData.identityPublishesTrustList);
try {
identity.setNickname(xmlData.identityName);
}
catch(Exception e) {
/* Nickname changes are not allowed, ignore them... */
Logger.error(this, "setNickname() failed.", e);
}
try { /* Failure of context importing should not make an identity disappear, therefore we catch exceptions. */
identity.setContexts(xmlData.identityContexts);
}
catch(Exception e) {
Logger.error(this, "setContexts() failed.", e);
}
try { /* Failure of property importing should not make an identity disappear, therefore we catch exceptions. */
identity.setProperties(xmlData.identityProperties);
}
catch(Exception e) {
Logger.error(this, "setProperties() failed", e);
}
mWoT.beginTrustListImport(); // We delete the old list if !identityPublishesTrustList and it did publish one earlier => we always call this.
if(xmlData.identityPublishesTrustList) {
// We import the trust list of an identity if it's score is equal to 0, but we only create new identities or import edition hints
// if the score is greater than 0. Solving a captcha therefore only allows you to create one single identity.
boolean positiveScore = false;
boolean hasCapacity = false;
// TODO: getBestScore/getBestCapacity should always yield a positive result because we store a positive score object for an OwnIdentity
// upon creation. The only case where it could not exist might be restoreIdentity() ... check that. If it is created there as well,
// remove the additional check here.
if(identity instanceof OwnIdentity) {
// Importing of OwnIdentities is always allowed
positiveScore = true;
hasCapacity = true;
} else {
try {
positiveScore = mWoT.getBestScore(identity) > 0;
hasCapacity = mWoT.getBestCapacity(identity) > 0;
}
catch(NotInTrustTreeException e) { }
}
HashSet<String> identitiesWithUpdatedEditionHint = null;
if(positiveScore) {
identitiesWithUpdatedEditionHint = new HashSet<String>(xmlData.identityTrustList.size() * 2);
}
for(final ParsedIdentityXML.TrustListEntry trustListEntry : xmlData.identityTrustList) {
final FreenetURI trusteeURI = trustListEntry.mTrusteeURI;
final byte trustValue = trustListEntry.mTrustValue;
final String trustComment = trustListEntry.mTrustComment;
Identity trustee = null;
try {
trustee = mWoT.getIdentityByURI(trusteeURI);
if(positiveScore) {
if(trustee.setNewEditionHint(trusteeURI.getEdition())) {
identitiesWithUpdatedEditionHint.add(trustee.getID());
trustee.storeWithoutCommit();
}
}
}
catch(UnknownIdentityException e) {
if(hasCapacity) { /* We only create trustees if the truster has capacity to rate them. */
try {
trustee = new Identity(mWoT, trusteeURI, null, false);
trustee.storeWithoutCommit();
} catch(MalformedURLException e2) {
/* Malformed URI in the trustlist. Log at minor since there
* is nothing the user can do anyway. */
if(logMINOR) {
Logger.minor(this,
"Caugth IllegalArgumentException while creating new " +
"Identity. Truster is " + identity + ", request URI " +
"is " + trusteeURI,
e2);
}
}
}
}
if(trustee != null)
mWoT.setTrustWithoutCommit(identity, trustee, trustValue, trustComment);
}
for(Trust trust : mWoT.getGivenTrustsOfDifferentEdition(identity, identityURI.getEdition())) {
mWoT.removeTrustWithoutCommit(trust);
}
IdentityFetcher identityFetcher = mWoT.getIdentityFetcher();
if(positiveScore) {
for(String id : identitiesWithUpdatedEditionHint)
identityFetcher.storeUpdateEditionHintCommandWithoutCommit(id);
// We do not have to store fetch commands for new identities here, setTrustWithoutCommit does it.
}
} else if(!xmlData.identityPublishesTrustList && didPublishTrustListPreviously && !(identity instanceof OwnIdentity)) {
// If it does not publish a trust list anymore, we delete all trust values it has given.
for(Trust trust : mWoT.getGivenTrusts(identity))
mWoT.removeTrustWithoutCommit(trust);
}
mWoT.finishTrustListImport();
identity.onFetched(); // Marks the identity as parsed successfully
identity.storeAndCommit();
}
catch(Exception e) {
mWoT.abortTrustListImport(e); // Does the rollback
throw e;
} // try
} // synchronized(Persistent.transactionLock(db))
Logger.normal(this, "Finished XML import for " + identity);
} // synchronized(mWoT)
} // synchronized(mWoT.getIdentityFetcher())
} // try
catch(Exception e) {
synchronized(mWoT) {
synchronized(mWoT.getIdentityFetcher()) {
try {
final Identity identity = mWoT.getIdentityByURI(identityURI);
final long newEdition = identityURI.getEdition();
if(identity.getEdition() <= newEdition) {
Logger.normal(this, "Marking edition as parsing failed: " + identityURI);
identity.setEdition(newEdition);
identity.onParsingFailed();
identity.storeAndCommit();
} else {
Logger.normal(this, "Not marking edition as parsing failed, we have already fetched a new one (" +
identity.getEdition() + "):" + identityURI);
}
}
catch(UnknownIdentityException uie) {
Logger.error(this, "Fetched an unknown identity: " + identityURI);
}
}
}
throw e;
}
}
|
diff --git a/modules/http/src/org/apache/axis2/transport/http/server/DefaultConnectionListener.java b/modules/http/src/org/apache/axis2/transport/http/server/DefaultConnectionListener.java
index 8d48343..d931c8b 100644
--- a/modules/http/src/org/apache/axis2/transport/http/server/DefaultConnectionListener.java
+++ b/modules/http/src/org/apache/axis2/transport/http/server/DefaultConnectionListener.java
@@ -1,121 +1,123 @@
/*
* 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.axis2.transport.http.server;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.params.HttpParams;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class DefaultConnectionListener implements IOProcessor {
private static Log LOG = LogFactory.getLog(DefaultConnectionListener.class);
private volatile boolean destroyed = false;
private final int port;
private final HttpConnectionManager connmanager;
private final ConnectionListenerFailureHandler failureHandler;
private final HttpParams params;
private ServerSocket serversocket = null;
/**
* Use this constructor to provide a custom ConnectionListenerFailureHandler, e.g. by subclassing DefaultConnectionListenerFailureHandler
*/
public DefaultConnectionListener(
int port,
final HttpConnectionManager connmanager,
final ConnectionListenerFailureHandler failureHandler,
final HttpParams params) throws IOException {
super();
if (connmanager == null) {
throw new IllegalArgumentException("Connection manager may not be null");
}
if (failureHandler == null) {
throw new IllegalArgumentException("Failure handler may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
this.port = port;
this.connmanager = connmanager;
this.failureHandler = failureHandler;
this.params = params;
}
public void run() {
try {
while (!Thread.interrupted()) {
try {
if (serversocket == null || serversocket.isClosed()) {
if (LOG.isInfoEnabled()) {
LOG.info("Listening on port " + port);
}
serversocket = new ServerSocket(port);
serversocket.setReuseAddress(true);
}
LOG.debug("Waiting for incoming HTTP connection");
Socket socket = this.serversocket.accept();
if (LOG.isDebugEnabled()) {
LOG.debug("Incoming HTTP connection from " +
socket.getRemoteSocketAddress());
}
AxisHttpConnection conn = new AxisHttpConnectionImpl(socket, this.params);
this.connmanager.process(conn);
+ } catch(java.io.InterruptedIOException ie) {
+ break;
} catch (Throwable ex) {
if (Thread.interrupted()) {
break;
}
if (!failureHandler.failed(this, ex)) {
break;
}
}
}
} finally {
destroy();
}
}
public void close() throws IOException {
if (this.serversocket != null) {
this.serversocket.close();
}
}
public void destroy() {
this.destroyed = true;
try {
close();
} catch (IOException ex) {
if (LOG.isWarnEnabled()) {
LOG.warn("I/O error closing listener", ex);
}
}
}
public boolean isDestroyed() {
return this.destroyed;
}
}
| true | true | public void run() {
try {
while (!Thread.interrupted()) {
try {
if (serversocket == null || serversocket.isClosed()) {
if (LOG.isInfoEnabled()) {
LOG.info("Listening on port " + port);
}
serversocket = new ServerSocket(port);
serversocket.setReuseAddress(true);
}
LOG.debug("Waiting for incoming HTTP connection");
Socket socket = this.serversocket.accept();
if (LOG.isDebugEnabled()) {
LOG.debug("Incoming HTTP connection from " +
socket.getRemoteSocketAddress());
}
AxisHttpConnection conn = new AxisHttpConnectionImpl(socket, this.params);
this.connmanager.process(conn);
} catch (Throwable ex) {
if (Thread.interrupted()) {
break;
}
if (!failureHandler.failed(this, ex)) {
break;
}
}
}
} finally {
destroy();
}
}
| public void run() {
try {
while (!Thread.interrupted()) {
try {
if (serversocket == null || serversocket.isClosed()) {
if (LOG.isInfoEnabled()) {
LOG.info("Listening on port " + port);
}
serversocket = new ServerSocket(port);
serversocket.setReuseAddress(true);
}
LOG.debug("Waiting for incoming HTTP connection");
Socket socket = this.serversocket.accept();
if (LOG.isDebugEnabled()) {
LOG.debug("Incoming HTTP connection from " +
socket.getRemoteSocketAddress());
}
AxisHttpConnection conn = new AxisHttpConnectionImpl(socket, this.params);
this.connmanager.process(conn);
} catch(java.io.InterruptedIOException ie) {
break;
} catch (Throwable ex) {
if (Thread.interrupted()) {
break;
}
if (!failureHandler.failed(this, ex)) {
break;
}
}
}
} finally {
destroy();
}
}
|
diff --git a/src/main/java/com/britesnow/snow/web/WebController.java b/src/main/java/com/britesnow/snow/web/WebController.java
index daf0a8c..c640804 100644
--- a/src/main/java/com/britesnow/snow/web/WebController.java
+++ b/src/main/java/com/britesnow/snow/web/WebController.java
@@ -1,553 +1,554 @@
package com.britesnow.snow.web;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.britesnow.snow.util.FileUtil;
import com.britesnow.snow.util.MapUtil;
import com.britesnow.snow.util.Pair;
import com.britesnow.snow.web.AbortWithHttpStatusException.HttpStatus;
import com.britesnow.snow.web.auth.AuthToken;
import com.britesnow.snow.web.auth.AuthRequest;
import com.britesnow.snow.web.db.hibernate.HibernateSessionInViewHandler;
import com.britesnow.snow.web.handler.WebHandlerContext;
import com.britesnow.snow.web.handler.WebHandlerException;
import com.britesnow.snow.web.less.LessProcessor;
import com.britesnow.snow.web.path.FramePathsResolver;
import com.britesnow.snow.web.path.ResourceFileResolver;
import com.britesnow.snow.web.path.ResourcePathResolver;
import com.britesnow.snow.web.renderer.WebBundleManager;
import com.google.common.base.Throwables;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
@Singleton
public class WebController {
static private Logger logger = LoggerFactory.getLogger(WebController.class);
private static final String CHAR_ENCODING = "UTF-8";
public static int BUFFER_SIZE = 2048 * 2;
private ServletFileUpload fileUploader;
// For now, a very simple cache for the .less.css result
private Map<String, Pair<Long, String>> lessCache = new ConcurrentHashMap<String, Pair<Long, String>>();
@Inject
private HttpWriter httpWriter;
@Inject(optional = true)
private ServletContext servletContext;
@Inject
private Application application;
@Inject
private WebBundleManager webBundleManager;
@Inject(optional = true)
private AuthRequest authService;
@Inject(optional = true)
private HibernateSessionInViewHandler hibernateSessionInViewHandler = null;
@Inject(optional = true)
private RequestLifecycle requestLifeCycle = null;
@Inject
private FramePathsResolver framePathsResolver;
@Inject
private ResourcePathResolver resourcePathResolver;
@Inject
private ResourceFileResolver pathFileResolver;
private ThreadLocal<RequestContext> requestContextTl = new ThreadLocal<RequestContext>();
private CurrentRequestContextHolder currentRequestContextHolder = new CurrentRequestContextHolder() {
@Override
public RequestContext getCurrentRequestContext() {
return requestContextTl.get();
}
};
@Inject
private LessProcessor lessProcessor;
// will be injected from .properties file
// FIXME: need to implement this.
// private boolean ignoreTemplateNotFound = false;
public CurrentRequestContextHolder getCurrentRequestContextHolder() {
return currentRequestContextHolder;
}
// --------- Injects --------- //
@Inject(optional = true)
public void injectIgnoreTemplateNotFound(@Named("snow.ignoreTemplateNotFound") String ignore) {
if ("true".equalsIgnoreCase(ignore)) {
// ignoreTemplateNotFound = true;
}
}
public void init() {
application.init();
/* --------- Initialize the FileUploader --------- */
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
// factory.setSizeThreshold(yourMaxMemorySize);
// factory.setRepository(yourTempDirectory);
fileUploader = new ServletFileUpload(factory);
/* --------- /Initialize the FileUploader --------- */
}
public void destroy() {
application.shutdown();
}
public void service(HttpServletRequest request, HttpServletResponse response) throws Exception {
request.setCharacterEncoding(CHAR_ENCODING);
response.setCharacterEncoding(CHAR_ENCODING);
RequestContext rc = new RequestContext(request, response, servletContext, fileUploader);
service(rc);
}
public void service(RequestContext rc) {
ResponseType responseType = null;
try {
requestContextTl.set(rc);
HttpServletRequest request = rc.getReq();
// get the request resourcePath
String resourcePath = resourcePathResolver.resolve(rc.getPathInfo(),rc);
// --------- Resolve the ResponseType --------- //
// determine the requestType
if (application.hasWebResourceHandlerFor(resourcePath)) {
responseType = ResponseType.webResource;
} else if (isTemplatePath(resourcePath)) {
responseType = ResponseType.template;
} else if (isWebActionResponseJson(resourcePath,rc)) {
responseType = ResponseType.webActionResponseJson;
} else if (isJsonPath(resourcePath)) {
responseType = ResponseType.json;
} else if (webBundleManager.isWebBundle(resourcePath)) {
responseType = ResponseType.webBundle;
} else if (resourcePath.endsWith(".less.css")) {
responseType = ResponseType.lessCss;
} else {
responseType = ResponseType.file;
}
// --------- /Resolve the ResponseType --------- //
// set the resourcePath and fix it if needed
switch (responseType) {
case json:
case template:
rc.setResourcePath(fixTemplateAndJsonResourcePath(resourcePath));
break;
default:
rc.setResourcePath(resourcePath);
break;
}
// if we have template request, then, resolve the framePaths
if (responseType == ResponseType.template) {
String[] framePaths = framePathsResolver.resolve(rc);
rc.setFramePaths(framePaths);
}
// --------- Open HibernateSession --------- //
if (hibernateSessionInViewHandler != null) {
hibernateSessionInViewHandler.openSessionInView();
}
// --------- /Open HibernateSession --------- //
// --------- Auth --------- //
if (authService != null) {
AuthToken<?> auth = authService.authRequest(rc);
rc.setAuthToken(auth);
}
// --------- /Auth --------- //
// --------- RequestLifeCycle Start --------- //
if (requestLifeCycle != null) {
requestLifeCycle.start(rc);
}
// --------- /RequestLifeCycle Start --------- //
// --------- Processing the Post (if any) --------- //
if ("POST".equals(request.getMethod())) {
String actionName = resolveWebActionName(rc);
if (actionName != null) {
WebActionResponse webActionResponse = null;
webActionResponse = application.processWebAction(actionName, rc);
rc.setWebActionResponse(webActionResponse);
}
// --------- afterActionProcessing --------- //
if (hibernateSessionInViewHandler != null) {
hibernateSessionInViewHandler.afterActionProcessing();
}
// --------- /afterActionProcessing --------- //
}
// --------- /Processing the Post (if any) --------- //
serviceRequestContext(responseType, rc);
// this catch is for when this exception is thrown prior to entering the web handler method.
// (e.g. a WebHandlerMethodInterceptor).
} catch (Throwable t) {
try {
t = findEventualInvocationTargetException(t);
// TODO: need to check if we still need this.
WebHandlerContext webHandlerContext = null;
if (t instanceof WebHandlerException) {
t = ((WebHandlerException) t).getCause();
webHandlerContext = ((WebHandlerException) t).getWebHandlerContext();
}
// first, try to see if the application process it with its WebExceptionHandler;
boolean exceptionProcessed = application.processWebExceptionCatcher(t, webHandlerContext, rc);
if (!exceptionProcessed) {
+ logger.error("Error while processing request : " + rc.getPathInfo() + " because: " + t.getMessage(),t);
throw t;
}
} catch (AbortWithHttpStatusException e) {
sendHttpError(rc, e.getStatus(), e.getMessage());
} catch (AbortWithHttpRedirectException e) {
sendHttpRedirect(rc, e);
} catch (Throwable e) {
// and this is the normal case...
sendHttpError(rc, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
logger.error(getLogErrorString(e));
}
} finally {
// --------- RequestLifeCycle End --------- //
if (requestLifeCycle != null) {
requestLifeCycle.end(rc);
}
// --------- /RequestLifeCycle End --------- //
// Remove the requestContext from the threadLocal
// NOTE: might want to do that after the closeSessionInView.
requestContextTl.remove();
// --------- Close HibernateSession --------- //
if (hibernateSessionInViewHandler != null) {
hibernateSessionInViewHandler.closeSessionInView();
}
// --------- /Close HibernateSession --------- //
}
}
public void serviceRequestContext(ResponseType responseType, RequestContext rc) {
switch (responseType) {
case template:
serviceTemplate(rc);
break;
case json:
serviceJson(rc);
break;
case webActionResponseJson:
serviceWebActionResponse(rc);
break;
case webResource:
serviceWebResource(rc);
break;
case webBundle:
serviceWebBundle(rc);
break;
case lessCss:
serviceLessCss(rc);
break;
case file:
serviceFile(rc);
break;
}
}
// --------- Service Request --------- //
private void serviceTemplate(RequestContext rc) {
HttpServletRequest req = rc.getReq();
HttpServletResponse res = rc.getRes();
try {
// TODO: probably need to remove this, not sure it does anything here (or it even should be here.
req.setCharacterEncoding(CHAR_ENCODING);
// TODO: needs to implement this
/*
* if (!ignoreTemplateNotFound && !webApplication.getPart(part.getPri()).getResourceFile().exists()) {
* sendHttpError(rc, HttpServletResponse.SC_NOT_FOUND, null); return; }
*/
res.setContentType("text/html;charset=" + CHAR_ENCODING);
// if not cachable, then, set the appropriate headers.
res.setHeader("Pragma", "No-cache");
res.setHeader("Cache-Control", "no-cache,no-store,max-age=0");
res.setDateHeader("Expires", 1);
application.processTemplate(rc);
rc.getWriter().close();
} catch (Throwable t) {
throw Throwables.propagate(t);
}
}
private void serviceWebActionResponse(RequestContext rc) {
setJsonHeaders(rc);
application.processWebActionResponseJson(rc);
try {
rc.getWriter().close();
} catch (IOException e) {
throw Throwables.propagate(e);
}
}
private void serviceJson(RequestContext rc) {
setJsonHeaders(rc);
application.processJson(rc);
try {
rc.getWriter().close();
} catch (IOException e) {
throw Throwables.propagate(e);
}
}
private void setJsonHeaders(RequestContext rc) {
HttpServletRequest req = rc.getReq();
HttpServletResponse res = rc.getRes();
// NOTE: we might want to let the render deal with this (not sure)
try {
req.setCharacterEncoding(CHAR_ENCODING);
} catch (UnsupportedEncodingException e) {
throw Throwables.propagate(e);
}
res.setContentType("application/json");
// no cash for now.
res.setHeader("Pragma", "No-cache");
res.setHeader("Cache-Control", "no-cache,no-store,max-age=0");
res.setDateHeader("Expires", 1);
}
public void serviceWebBundle(RequestContext rc) {
String contextPath = rc.getContextPath();
String resourcePath = rc.getResourcePath();
String href = new StringBuilder(contextPath).append(resourcePath).toString();
String content = webBundleManager.getContent(resourcePath, rc);
StringReader reader = new StringReader(content);
httpWriter.writeStringContent(rc, href, reader, true, null);
}
private void serviceWebResource(RequestContext rc) {
application.processWebResourceHandler(rc);
}
private void serviceLessCss(RequestContext rc) {
String resourcePath = rc.getResourcePath();
// --------- Process the .less file --------- //
String lessFilePath = resourcePath.substring(0, resourcePath.length() - 4);
File lessFile = pathFileResolver.resolve(lessFilePath,rc);
if (!lessFile.exists()) {
throw new AbortWithHttpStatusException(HttpStatus.NOT_FOUND, "File " + lessFilePath + " not found");
}
// Now, determine the youngest .less file
long maxTime = 0;
File lessFolder = lessFile.getParentFile();
for (File file : lessFolder.listFiles()) {
String name = file.getName().toLowerCase();
if (name.endsWith(".less")) {
long time = file.lastModified();
if (time > maxTime) {
maxTime = time;
}
}
}
String lessResult = null;
Pair<Long, String> timeAndContent = lessCache.get(lessFilePath);
if (timeAndContent != null && maxTime <= timeAndContent.getFirst()) {
// if we have a match, and none of the maxTime of all the .less file still smaller or equal than the cache
// item, then, still valid
lessResult = timeAndContent.getSecond();
} else {
lessResult = lessProcessor.compile(lessFile);
lessCache.put(lessFilePath, new Pair<Long, String>(maxTime, lessResult));
}
// --------- /Process the .less file --------- //
Reader contentReader = new StringReader(lessResult);
String fileName = FileUtil.getFilePathAndName(resourcePath)[1];
httpWriter.writeStringContent(rc, fileName, contentReader, true, null);
}
private void serviceFile(RequestContext rc) {
String resourcePath = rc.getResourcePath();
File resourceFile = pathFileResolver.resolve(resourcePath,rc);
if (resourceFile.exists()) {
boolean isCachable = isCachable(resourcePath);
httpWriter.writeFile(rc, resourceFile, isCachable, null);
} else {
sendHttpError(rc, HttpServletResponse.SC_NOT_FOUND, null);
}
}
// --------- /Service Request --------- //
private void sendHttpError(RequestContext rc, int errorCode, String message) {
// if the response has already been committed, there's not much we can do about it at this point...just let it
// go.
// the one place where the response is likely to be committed already is if the exception causing the error
// originates while processing a template. the template will usually have already output enough html so that
// the container has already started writing back to the client.
if (!rc.getRes().isCommitted()) {
try {
rc.getRes().sendError(errorCode, message);
} catch (IOException e) {
throw Throwables.propagate(e);
}
}
}
private void sendHttpRedirect(RequestContext rc, AbortWithHttpRedirectException e){
// like above, there's not much we can do if the response has already been committed. in that case,
// we'll just silently ignore the exception.
HttpServletResponse response = rc.getRes();
if (!response.isCommitted()) {
response.setStatus(e.getRedirectCode());
response.addHeader("Location", e.getLocation());
}
}
/*
* if it it and InvocationTargetException or RuntimeException that wrap a InvocationTargetException, then, return
* the target.
*/
static private Throwable findEventualInvocationTargetException(Throwable t) {
InvocationTargetException ie = null;
if (t instanceof InvocationTargetException) {
ie = (InvocationTargetException) t;
} else if (t.getCause() != null && t.getCause() instanceof InvocationTargetException) {
ie = (InvocationTargetException) t.getCause();
}
if (ie != null) {
t = ie.getTargetException();
}
return t;
}
/*
* First the resourcePath by remove extension (.json or .ftl) and adding index if the path end with "/"
*/
static private String fixTemplateAndJsonResourcePath(String resourcePath) {
String path = FileUtil.getFileNameAndExtension(resourcePath)[0];
return path;
}
static Set cachableExtension = MapUtil.setIt(".css", ".less", ".js", ".png", ".gif", ".jpeg");
/**
* Return true if the content pointed by the pathInfo is static.<br>
* Right now, just return true if there is no extension
*
* @param path
* @return
*/
static private final boolean isTemplatePath(String path) {
if (path.lastIndexOf('.') == -1 || path.endsWith(".ftl")) {
return true;
} else {
return false;
}
}
static private final boolean isJsonPath(String path) {
if (path.endsWith(".json")) {
return true;
} else {
return false;
}
}
static private final boolean isWebActionResponseJson(String resourcePath, RequestContext rc){
if (rc.getReq().getMethod().equals("POST")){
if (resourcePath.endsWith(".do") || "/_actionResponse.json".equals(resourcePath)){
return true;
}
}
return false;
}
static private final String resolveWebActionName(RequestContext rc){
String resourcePath = rc.getResourcePath();
// if it is a .do request
if (resourcePath.endsWith(".do")){
return resourcePath.substring(1,resourcePath.length() - 3);
}
return rc.getParam("action");
}
static final private boolean isCachable(String pathInfo) {
String ext = FileUtil.getFileNameAndExtension(pathInfo)[1];
return cachableExtension.contains(ext);
}
static final private String getLogErrorString(Throwable e) {
StringBuilder errorSB = new StringBuilder();
errorSB.append(e.getMessage());
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
errorSB.append("\n-- StackTrace:\n").append(sw.toString()).append("\n-- /StackTrace");
return errorSB.toString();
}
}
| true | true | public void service(RequestContext rc) {
ResponseType responseType = null;
try {
requestContextTl.set(rc);
HttpServletRequest request = rc.getReq();
// get the request resourcePath
String resourcePath = resourcePathResolver.resolve(rc.getPathInfo(),rc);
// --------- Resolve the ResponseType --------- //
// determine the requestType
if (application.hasWebResourceHandlerFor(resourcePath)) {
responseType = ResponseType.webResource;
} else if (isTemplatePath(resourcePath)) {
responseType = ResponseType.template;
} else if (isWebActionResponseJson(resourcePath,rc)) {
responseType = ResponseType.webActionResponseJson;
} else if (isJsonPath(resourcePath)) {
responseType = ResponseType.json;
} else if (webBundleManager.isWebBundle(resourcePath)) {
responseType = ResponseType.webBundle;
} else if (resourcePath.endsWith(".less.css")) {
responseType = ResponseType.lessCss;
} else {
responseType = ResponseType.file;
}
// --------- /Resolve the ResponseType --------- //
// set the resourcePath and fix it if needed
switch (responseType) {
case json:
case template:
rc.setResourcePath(fixTemplateAndJsonResourcePath(resourcePath));
break;
default:
rc.setResourcePath(resourcePath);
break;
}
// if we have template request, then, resolve the framePaths
if (responseType == ResponseType.template) {
String[] framePaths = framePathsResolver.resolve(rc);
rc.setFramePaths(framePaths);
}
// --------- Open HibernateSession --------- //
if (hibernateSessionInViewHandler != null) {
hibernateSessionInViewHandler.openSessionInView();
}
// --------- /Open HibernateSession --------- //
// --------- Auth --------- //
if (authService != null) {
AuthToken<?> auth = authService.authRequest(rc);
rc.setAuthToken(auth);
}
// --------- /Auth --------- //
// --------- RequestLifeCycle Start --------- //
if (requestLifeCycle != null) {
requestLifeCycle.start(rc);
}
// --------- /RequestLifeCycle Start --------- //
// --------- Processing the Post (if any) --------- //
if ("POST".equals(request.getMethod())) {
String actionName = resolveWebActionName(rc);
if (actionName != null) {
WebActionResponse webActionResponse = null;
webActionResponse = application.processWebAction(actionName, rc);
rc.setWebActionResponse(webActionResponse);
}
// --------- afterActionProcessing --------- //
if (hibernateSessionInViewHandler != null) {
hibernateSessionInViewHandler.afterActionProcessing();
}
// --------- /afterActionProcessing --------- //
}
// --------- /Processing the Post (if any) --------- //
serviceRequestContext(responseType, rc);
// this catch is for when this exception is thrown prior to entering the web handler method.
// (e.g. a WebHandlerMethodInterceptor).
} catch (Throwable t) {
try {
t = findEventualInvocationTargetException(t);
// TODO: need to check if we still need this.
WebHandlerContext webHandlerContext = null;
if (t instanceof WebHandlerException) {
t = ((WebHandlerException) t).getCause();
webHandlerContext = ((WebHandlerException) t).getWebHandlerContext();
}
// first, try to see if the application process it with its WebExceptionHandler;
boolean exceptionProcessed = application.processWebExceptionCatcher(t, webHandlerContext, rc);
if (!exceptionProcessed) {
throw t;
}
} catch (AbortWithHttpStatusException e) {
sendHttpError(rc, e.getStatus(), e.getMessage());
} catch (AbortWithHttpRedirectException e) {
sendHttpRedirect(rc, e);
} catch (Throwable e) {
// and this is the normal case...
sendHttpError(rc, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
logger.error(getLogErrorString(e));
}
} finally {
// --------- RequestLifeCycle End --------- //
if (requestLifeCycle != null) {
requestLifeCycle.end(rc);
}
// --------- /RequestLifeCycle End --------- //
// Remove the requestContext from the threadLocal
// NOTE: might want to do that after the closeSessionInView.
requestContextTl.remove();
// --------- Close HibernateSession --------- //
if (hibernateSessionInViewHandler != null) {
hibernateSessionInViewHandler.closeSessionInView();
}
// --------- /Close HibernateSession --------- //
}
}
| public void service(RequestContext rc) {
ResponseType responseType = null;
try {
requestContextTl.set(rc);
HttpServletRequest request = rc.getReq();
// get the request resourcePath
String resourcePath = resourcePathResolver.resolve(rc.getPathInfo(),rc);
// --------- Resolve the ResponseType --------- //
// determine the requestType
if (application.hasWebResourceHandlerFor(resourcePath)) {
responseType = ResponseType.webResource;
} else if (isTemplatePath(resourcePath)) {
responseType = ResponseType.template;
} else if (isWebActionResponseJson(resourcePath,rc)) {
responseType = ResponseType.webActionResponseJson;
} else if (isJsonPath(resourcePath)) {
responseType = ResponseType.json;
} else if (webBundleManager.isWebBundle(resourcePath)) {
responseType = ResponseType.webBundle;
} else if (resourcePath.endsWith(".less.css")) {
responseType = ResponseType.lessCss;
} else {
responseType = ResponseType.file;
}
// --------- /Resolve the ResponseType --------- //
// set the resourcePath and fix it if needed
switch (responseType) {
case json:
case template:
rc.setResourcePath(fixTemplateAndJsonResourcePath(resourcePath));
break;
default:
rc.setResourcePath(resourcePath);
break;
}
// if we have template request, then, resolve the framePaths
if (responseType == ResponseType.template) {
String[] framePaths = framePathsResolver.resolve(rc);
rc.setFramePaths(framePaths);
}
// --------- Open HibernateSession --------- //
if (hibernateSessionInViewHandler != null) {
hibernateSessionInViewHandler.openSessionInView();
}
// --------- /Open HibernateSession --------- //
// --------- Auth --------- //
if (authService != null) {
AuthToken<?> auth = authService.authRequest(rc);
rc.setAuthToken(auth);
}
// --------- /Auth --------- //
// --------- RequestLifeCycle Start --------- //
if (requestLifeCycle != null) {
requestLifeCycle.start(rc);
}
// --------- /RequestLifeCycle Start --------- //
// --------- Processing the Post (if any) --------- //
if ("POST".equals(request.getMethod())) {
String actionName = resolveWebActionName(rc);
if (actionName != null) {
WebActionResponse webActionResponse = null;
webActionResponse = application.processWebAction(actionName, rc);
rc.setWebActionResponse(webActionResponse);
}
// --------- afterActionProcessing --------- //
if (hibernateSessionInViewHandler != null) {
hibernateSessionInViewHandler.afterActionProcessing();
}
// --------- /afterActionProcessing --------- //
}
// --------- /Processing the Post (if any) --------- //
serviceRequestContext(responseType, rc);
// this catch is for when this exception is thrown prior to entering the web handler method.
// (e.g. a WebHandlerMethodInterceptor).
} catch (Throwable t) {
try {
t = findEventualInvocationTargetException(t);
// TODO: need to check if we still need this.
WebHandlerContext webHandlerContext = null;
if (t instanceof WebHandlerException) {
t = ((WebHandlerException) t).getCause();
webHandlerContext = ((WebHandlerException) t).getWebHandlerContext();
}
// first, try to see if the application process it with its WebExceptionHandler;
boolean exceptionProcessed = application.processWebExceptionCatcher(t, webHandlerContext, rc);
if (!exceptionProcessed) {
logger.error("Error while processing request : " + rc.getPathInfo() + " because: " + t.getMessage(),t);
throw t;
}
} catch (AbortWithHttpStatusException e) {
sendHttpError(rc, e.getStatus(), e.getMessage());
} catch (AbortWithHttpRedirectException e) {
sendHttpRedirect(rc, e);
} catch (Throwable e) {
// and this is the normal case...
sendHttpError(rc, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
logger.error(getLogErrorString(e));
}
} finally {
// --------- RequestLifeCycle End --------- //
if (requestLifeCycle != null) {
requestLifeCycle.end(rc);
}
// --------- /RequestLifeCycle End --------- //
// Remove the requestContext from the threadLocal
// NOTE: might want to do that after the closeSessionInView.
requestContextTl.remove();
// --------- Close HibernateSession --------- //
if (hibernateSessionInViewHandler != null) {
hibernateSessionInViewHandler.closeSessionInView();
}
// --------- /Close HibernateSession --------- //
}
}
|
diff --git a/core/src/main/java/hudson/FilePath.java b/core/src/main/java/hudson/FilePath.java
index f276e6880..6cab5c4d0 100644
--- a/core/src/main/java/hudson/FilePath.java
+++ b/core/src/main/java/hudson/FilePath.java
@@ -1,866 +1,866 @@
package hudson;
import hudson.Launcher.LocalLauncher;
import hudson.Launcher.RemoteLauncher;
import hudson.model.Hudson;
import hudson.model.TaskListener;
import hudson.remoting.Callable;
import hudson.remoting.Channel;
import hudson.remoting.DelegatingCallable;
import hudson.remoting.Future;
import hudson.remoting.Pipe;
import hudson.remoting.RemoteOutputStream;
import hudson.remoting.VirtualChannel;
import hudson.util.FormFieldValidator;
import hudson.util.IOException2;
import hudson.util.StreamResource;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Copy;
import org.apache.tools.ant.taskdefs.Untar;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.tar.TarEntry;
import org.apache.tools.tar.TarOutputStream;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.io.Writer;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.GZIPInputStream;
/**
* {@link File} like object with remoting support.
*
* <p>
* Unlike {@link File}, which always implies a file path on the current computer,
* {@link FilePath} represents a file path on a specific slave or the master.
*
* Despite that, {@link FilePath} can be used much like {@link File}. It exposes
* a bunch of operations (and we should add more operations as long as they are
* generally useful), and when invoked against a file on a remote node, {@link FilePath}
* executes the necessary code remotely, thereby providing semi-transparent file
* operations.
*
* <h2>Using {@link FilePath} smartly</h2>
* <p>
* The transparency makes it easy to write plugins without worrying too much about
* remoting, by making it works like NFS, where remoting happens at the file-system
* later.
*
* <p>
* But one should note that such use of remoting may not be optional. Sometimes,
* it makes more sense to move some computation closer to the data, as opposed to
* move the data to the computation. For example, if you are just computing a MD5
* digest of a file, then it would make sense to do the digest on the host where
* the file is located, as opposed to send the whole data to the master and do MD5
* digesting there.
*
* <p>
* {@link FilePath} supports this "code migration" by in the
* {@link #act(FileCallable)} method. One can pass in a custom implementation
* of {@link FileCallable}, to be executed on the node where the data is located.
* The following code shows the example:
*
* <pre>
* FilePath file = ...;
*
* // make 'file' a fresh empty directory.
* file.act(new FileCallable<Void>() {
* // if 'file' is on a different node, this FileCallable will
* // be transfered to that node and executed there.
* public Void invoke(File f,VirtualChannel channel) {
* // f and file represents the same thing
* f.deleteContents();
* f.mkdirs();
* }
* });
* </pre>
*
* <p>
* When {@link FileCallable} is transfered to a remote node, it will be done so
* by using the same Java serializaiton scheme that the remoting module uses.
* See {@link Channel} for more about this.
*
* <p>
* {@link FilePath} itself can be sent over to a remote node as a part of {@link Callable}
* serialization. For example, sending a {@link FilePath} of a remote node to that
* node causes {@link FilePath} to become "local". Similarly, sending a
* {@link FilePath} that represents the local computer causes it to become "remote."
*
* @author Kohsuke Kawaguchi
*/
public final class FilePath implements Serializable {
/**
* When this {@link FilePath} represents the remote path,
* this field is always non-null on master (the field represents
* the channel to the remote slave.) When transferred to a slave via remoting,
* this field reverts back to null, since it's transient.
*
* When this {@link FilePath} represents a path on the master,
* this field is null on master. When transferred to a slave via remoting,
* this field becomes non-null, representing the {@link Channel}
* back to the master.
*
* This is used to determine whether we are running on the master or the slave.
*/
private transient VirtualChannel channel;
// since the platform of the slave might be different, can't use java.io.File
private final String remote;
public FilePath(VirtualChannel channel, String remote) {
this.channel = channel;
this.remote = remote;
}
/**
* To create {@link FilePath} on the master computer.
*/
public FilePath(File localPath) {
this.channel = null;
this.remote = localPath.getPath();
}
public FilePath(FilePath base, String rel) {
this.channel = base.channel;
if(base.isUnix()) {
this.remote = base.remote+'/'+rel;
} else {
this.remote = base.remote+'\\'+rel;
}
}
/**
* Checks if the remote path is Unix.
*/
private boolean isUnix() {
// Windows can handle '/' as a path separator but Unix can't,
// so err on Unix side
return remote.indexOf("\\")==-1;
}
public String getRemote() {
return remote;
}
/**
* Creates a zip file from this directory or a file and sends that to the given output stream.
*/
public void createZipArchive(OutputStream os) throws IOException, InterruptedException {
final OutputStream out = (channel!=null)?new RemoteOutputStream(os):os;
act(new FileCallable<Void>() {
private transient byte[] buf;
public Void invoke(File f, VirtualChannel channel) throws IOException {
buf = new byte[8192];
ZipOutputStream zip = new ZipOutputStream(out);
scan(f,zip,"");
zip.close();
return null;
}
private void scan(File f, ZipOutputStream zip, String path) throws IOException {
if(f.isDirectory()) {
for( File child : f.listFiles() )
scan(child,zip,path+f.getName()+'/');
} else {
zip.putNextEntry(new ZipEntry(path+f.getName()));
FileInputStream in = new FileInputStream(f);
int len;
while((len=in.read(buf))>0)
zip.write(buf,0,len);
in.close();
zip.closeEntry();
}
}
private static final long serialVersionUID = 1L;
});
}
/**
* Code that gets executed on the machine where the {@link FilePath} is local.
* Used to act on {@link FilePath}.
*
* @see FilePath#act(FileCallable)
*/
public static interface FileCallable<T> extends Serializable {
/**
* Performs the computational task on the node where the data is located.
*
* @param f
* {@link File} that represents the local file that {@link FilePath} has represented.
* @param channel
* The "back pointer" of the {@link Channel} that represents the communication
* with the node from where the code was sent.
*/
T invoke(File f, VirtualChannel channel) throws IOException;
}
/**
* Executes some program on the machine that this {@link FilePath} exists,
* so that one can perform local file operations.
*/
public <T> T act(final FileCallable<T> callable) throws IOException, InterruptedException {
if(channel!=null) {
// run this on a remote system
try {
return channel.call(new FileCallableWrapper<T>(callable));
} catch (IOException e) {
// wrap it into a new IOException so that we get the caller's stack trace as well.
throw new IOException2("remote file operation failed",e);
}
} else {
// the file is on the local machine.
return callable.invoke(new File(remote), Hudson.MasterComputer.localChannel);
}
}
/**
* Executes some program on the machine that this {@link FilePath} exists,
* so that one can perform local file operations.
*/
public <T> Future<T> actAsync(final FileCallable<T> callable) throws IOException, InterruptedException {
try {
return (channel!=null ? channel : Hudson.MasterComputer.localChannel)
.callAsync(new FileCallableWrapper<T>(callable));
} catch (IOException e) {
// wrap it into a new IOException so that we get the caller's stack trace as well.
throw new IOException2("remote file operation failed",e);
}
}
/**
* Executes some program on the machine that this {@link FilePath} exists,
* so that one can perform local file operations.
*/
public <V,E extends Throwable> V act(Callable<V,E> callable) throws IOException, InterruptedException, E {
if(channel!=null) {
// run this on a remote system
return channel.call(callable);
} else {
// the file is on the local machine
return callable.call();
}
}
/**
* Converts this file to the URI, relative to the machine
* on which this file is available.
*/
public URI toURI() throws IOException, InterruptedException {
return act(new FileCallable<URI>() {
public URI invoke(File f, VirtualChannel channel) {
return f.toURI();
}
});
}
/**
* Creates this directory.
*/
public void mkdirs() throws IOException, InterruptedException {
if(act(new FileCallable<Boolean>() {
public Boolean invoke(File f, VirtualChannel channel) throws IOException {
return !f.mkdirs() && !f.exists();
}
}))
throw new IOException("Failed to mkdirs: "+remote);
}
/**
* Deletes this directory, including all its contents recursively.
*/
public void deleteRecursive() throws IOException, InterruptedException {
act(new FileCallable<Void>() {
public Void invoke(File f, VirtualChannel channel) throws IOException {
Util.deleteRecursive(f);
return null;
}
});
}
/**
* Deletes all the contents of this directory, but not the directory itself
*/
public void deleteContents() throws IOException, InterruptedException {
act(new FileCallable<Void>() {
public Void invoke(File f, VirtualChannel channel) throws IOException {
Util.deleteContentsRecursive(f);
return null;
}
});
}
/**
* Gets just the file name portion.
*
* This method assumes that the file name is the same between local and remote.
*/
public String getName() {
String r = remote;
if(r.endsWith("\\") || r.endsWith("/"))
r = r.substring(0,r.length()-1);
int len = r.length()-1;
while(len>=0) {
char ch = r.charAt(len);
if(ch=='\\' || ch=='/')
break;
len--;
}
return r.substring(len+1);
}
/**
* The same as {@code new FilePath(this,rel)} but more OO.
*/
public FilePath child(String rel) {
return new FilePath(this,rel);
}
/**
* Gets the parent file.
*/
public FilePath getParent() {
int len = remote.length()-1;
while(len>=0) {
char ch = remote.charAt(len);
if(ch=='\\' || ch=='/')
break;
len--;
}
return new FilePath( channel, remote.substring(0,len) );
}
/**
* Creates a temporary file.
*/
public FilePath createTempFile(final String prefix, final String suffix) throws IOException, InterruptedException {
try {
return new FilePath(this,act(new FileCallable<String>() {
public String invoke(File dir, VirtualChannel channel) throws IOException {
File f = File.createTempFile(prefix, suffix, dir);
return f.getName();
}
}));
} catch (IOException e) {
throw new IOException2("Failed to create a temp file on "+remote,e);
}
}
/**
* Creates a temporary file in this directory and set the contents by the
* given text (encoded in the platform default encoding)
*/
public FilePath createTextTempFile(final String prefix, final String suffix, final String contents) throws IOException, InterruptedException {
return createTextTempFile(prefix,suffix,contents,true);
}
/**
* Creates a temporary file in this directory and set the contents by the
* given text (encoded in the platform default encoding)
*/
public FilePath createTextTempFile(final String prefix, final String suffix, final String contents, final boolean inThisDirectory) throws IOException, InterruptedException {
try {
return new FilePath(channel,act(new FileCallable<String>() {
public String invoke(File dir, VirtualChannel channel) throws IOException {
if(!inThisDirectory)
dir = null;
File f = File.createTempFile(prefix, suffix, dir);
Writer w = new FileWriter(f);
w.write(contents);
w.close();
return f.getAbsolutePath();
}
}));
} catch (IOException e) {
throw new IOException2("Failed to create a temp file on "+remote,e);
}
}
/**
* Deletes this file.
*/
public boolean delete() throws IOException, InterruptedException {
return act(new FileCallable<Boolean>() {
public Boolean invoke(File f, VirtualChannel channel) throws IOException {
return f.delete();
}
});
}
/**
* Checks if the file exists.
*/
public boolean exists() throws IOException, InterruptedException {
return act(new FileCallable<Boolean>() {
public Boolean invoke(File f, VirtualChannel channel) throws IOException {
return f.exists();
}
});
}
/**
* Gets the last modified time stamp of this file, by using the clock
* of the machine where this file actually resides.
*
* @see File#lastModified()
*/
public long lastModified() throws IOException, InterruptedException {
return act(new FileCallable<Long>() {
public Long invoke(File f, VirtualChannel channel) throws IOException {
return f.lastModified();
}
});
}
/**
* Checks if the file is a directory.
*/
public boolean isDirectory() throws IOException, InterruptedException {
return act(new FileCallable<Boolean>() {
public Boolean invoke(File f, VirtualChannel channel) throws IOException {
return f.isDirectory();
}
});
}
/**
* List up files in this directory.
*
* @param filter
* The optional filter used to narrow down the result.
* If non-null, must be {@link Serializable}.
* If this {@link FilePath} represents a remote path,
* the filter object will be executed on the remote machine.
*/
public List<FilePath> list(final FileFilter filter) throws IOException, InterruptedException {
return act(new FileCallable<List<FilePath>>() {
public List<FilePath> invoke(File f, VirtualChannel channel) throws IOException {
File[] children = f.listFiles(filter);
if(children ==null) return null;
ArrayList<FilePath> r = new ArrayList<FilePath>(children.length);
for (File child : children)
r.add(new FilePath(child));
return r;
}
});
}
/**
* List up files in this directory that matches the given Ant-style filter.
*
* @param includes
* See {@link FileSet} for the syntax. String like "foo/*.zip".
*/
public FilePath[] list(final String includes) throws IOException, InterruptedException {
return act(new FileCallable<FilePath[]>() {
public FilePath[] invoke(File f, VirtualChannel channel) throws IOException {
FileSet fs = new FileSet();
fs.setDir(f);
fs.setIncludes(includes);
DirectoryScanner ds = fs.getDirectoryScanner(new org.apache.tools.ant.Project());
String[] files = ds.getIncludedFiles();
FilePath[] r = new FilePath[files.length];
for( int i=0; i<r.length; i++ )
r[i] = new FilePath(new File(f,files[i]));
return r;
}
});
}
/**
* Reads this file.
*/
public InputStream read() throws IOException {
if(channel==null)
return new FileInputStream(new File(remote));
final Pipe p = Pipe.createRemoteToLocal();
channel.callAsync(new Callable<Void,IOException>() {
public Void call() throws IOException {
FileInputStream fis = new FileInputStream(new File(remote));
Util.copyStream(fis,p.getOut());
fis.close();
p.getOut().close();
return null;
}
});
return p.getIn();
}
/**
* Writes to this file.
* If this file already exists, it will be overwritten.
* If the directory doesn't exist, it will be created.
*/
public OutputStream write() throws IOException, InterruptedException {
if(channel==null) {
File f = new File(remote);
f.getParentFile().mkdirs();
return new FileOutputStream(f);
}
return channel.call(new Callable<OutputStream,IOException>() {
public OutputStream call() throws IOException {
File f = new File(remote);
f.getParentFile().mkdirs();
FileOutputStream fos = new FileOutputStream(f);
return new RemoteOutputStream(fos);
}
});
}
/**
* Computes the MD5 digest of the file in hex string.
*/
public String digest() throws IOException, InterruptedException {
return act(new FileCallable<String>() {
public String invoke(File f, VirtualChannel channel) throws IOException {
return Util.getDigestOf(new FileInputStream(f));
}
});
}
/**
* Copies this file to the specified target.
*/
public void copyTo(FilePath target) throws IOException, InterruptedException {
OutputStream out = target.write();
try {
copyTo(out);
} finally {
out.close();
}
}
/**
* Sends the contents of this file into the given {@link OutputStream}.
*/
public void copyTo(OutputStream os) throws IOException, InterruptedException {
final OutputStream out = new RemoteOutputStream(os);
act(new FileCallable<Void>() {
public Void invoke(File f, VirtualChannel channel) throws IOException {
FileInputStream fis = new FileInputStream(f);
Util.copyStream(fis,out);
fis.close();
out.close();
return null;
}
});
}
/**
* Remoting interface used for {@link FilePath#copyRecursiveTo(String, FilePath)}.
*
* TODO: this might not be the most efficient way to do the copy.
*/
interface RemoteCopier {
/**
* @param fileName
* relative path name to the output file. Path separator must be '/'.
*/
void open(String fileName) throws IOException;
void write(byte[] buf, int len) throws IOException;
void close() throws IOException;
}
public int copyRecursiveTo(String fileMask, FilePath target) throws IOException, InterruptedException {
return copyRecursiveTo(fileMask,null,target);
}
/**
* Copies the files that match the given file mask to the specified target node.
*
* @param excludes
* Files to be excluded. Can be null.
* @return
* the number of files copied.
*/
public int copyRecursiveTo(final String fileMask, final String excludes, final FilePath target) throws IOException, InterruptedException {
if(this.channel==target.channel) {
// local to local copy.
return act(new FileCallable<Integer>() {
public Integer invoke(File base, VirtualChannel channel) throws IOException {
assert target.channel==null;
try {
class CopyImpl extends Copy {
private int copySize;
public CopyImpl() {
setProject(new org.apache.tools.ant.Project());
}
protected void doFileOperations() {
copySize = super.fileCopyMap.size();
super.doFileOperations();
}
public int getNumCopied() {
return copySize;
}
}
CopyImpl copyTask = new CopyImpl();
copyTask.setTodir(new File(target.remote));
FileSet src = new FileSet();
src.setDir(base);
src.setIncludes(fileMask);
src.setExcludes(excludes);
copyTask.addFileset(src);
copyTask.execute();
return copyTask.getNumCopied();
} catch (BuildException e) {
throw new IOException2("Failed to copy "+base+"/"+fileMask+" to "+target,e);
}
}
});
} else
if(this.channel==null) {
// local -> remote copy
final Pipe pipe = Pipe.createLocalToRemote();
Future<Void> future = target.actAsync(new FileCallable<Void>() {
public Void invoke(File f, VirtualChannel channel) throws IOException {
readFromTar(f,pipe.getIn());
return null;
}
});
int r = writeToTar(new File(remote),fileMask,excludes,pipe);
try {
future.get();
} catch (ExecutionException e) {
throw new IOException2(e);
}
return r;
} else {
// remote -> local copy
final Pipe pipe = Pipe.createRemoteToLocal();
Future<Integer> future = actAsync(new FileCallable<Integer>() {
public Integer invoke(File f, VirtualChannel channel) throws IOException {
return writeToTar(f,fileMask,excludes,pipe);
}
});
- readFromTar(new File(remote),pipe.getIn());
+ readFromTar(new File(target.remote),pipe.getIn());
try {
return future.get();
} catch (ExecutionException e) {
throw new IOException2(e);
}
}
}
/**
* Writes to a tar stream and stores obtained files to the base dir.
*
* @return
* number of files/directories that are written.
*/
private Integer writeToTar(File baseDir, String fileMask, String excludes, Pipe pipe) throws IOException {
FileSet fs = new FileSet();
fs.setDir(baseDir);
fs.setIncludes(fileMask);
if(excludes!=null)
fs.setExcludes(excludes);
byte[] buf = new byte[8192];
TarOutputStream tar = new TarOutputStream(new GZIPOutputStream(new BufferedOutputStream(pipe.getOut())));
DirectoryScanner ds = fs.getDirectoryScanner(new org.apache.tools.ant.Project());
String[] files = ds.getIncludedFiles();
for( String f : files) {
if(Functions.isWindows())
f = f.replace('\\','/');
File file = new File(baseDir, f);
TarEntry te = new TarEntry(f);
te.setModTime(file.lastModified());
if(!file.isDirectory())
te.setSize(file.length());
tar.putNextEntry(te);
if (!file.isDirectory()) {
FileInputStream in = new FileInputStream(file);
int len;
while((len=in.read(buf))>=0)
tar.write(buf,0,len);
in.close();
}
tar.closeEntry();
}
tar.close();
return files.length;
}
/**
* Reads from a tar stream and stores obtained files to the base dir.
*/
private static void readFromTar(File baseDir, InputStream in) throws IOException {
Untar untar = new Untar();
untar.setProject(new Project());
untar.add(new StreamResource(new BufferedInputStream(new GZIPInputStream(in))));
untar.setDest(baseDir);
untar.execute();
}
/**
* Creates a {@link Launcher} for starting processes on the node
* that has this file.
* @since 1.89
*/
public Launcher createLauncher(TaskListener listener) {
if(channel==null)
return new LocalLauncher(listener);
else
return new RemoteLauncher(listener,channel,isUnix());
}
/**
* Validates the ant file mask (like "foo/bar/*.txt")
* against this directory, and try to point out the problem.
*
* <p>
* This is useful in conjunction with {@link FormFieldValidator}.
*
* @return
* null if no error was found.
* @since 1.90
* @see FormFieldValidator.WorkspaceFileMask
*/
public String validateAntFileMask(final String fileMask) throws IOException, InterruptedException {
return act(new FileCallable<String>() {
public String invoke(File dir, VirtualChannel channel) throws IOException {
String previous = null;
String pattern = fileMask;
while(true) {
FileSet fs = new FileSet();
fs.setDir(dir);
fs.setIncludes(pattern);
DirectoryScanner ds = fs.getDirectoryScanner(new org.apache.tools.ant.Project());
if(ds.getIncludedFilesCount()!=0 || ds.getIncludedDirsCount()!=0) {
// found a match
if(pattern.equals(fileMask))
return null; // no error
if(previous==null)
return String.format("'%s' doesn't match anything, although '%s' exists",
fileMask, pattern );
else
return String.format("'%s' doesn't match anything: '%s' exists but not '%s'",
fileMask, pattern, previous );
}
int idx = Math.max(pattern.lastIndexOf('\\'),pattern.lastIndexOf('/'));
if(idx<0) {
if(pattern.equals(fileMask))
return String.format("'%s' doesn't match anything", fileMask );
else
return String.format("'%s' doesn't match anything: even '%s' doesn't exist",
fileMask, pattern );
}
// cut off the trailing component and try again
previous = pattern;
pattern = pattern.substring(0,idx);
}
}
});
}
@Deprecated
public String toString() {
// to make writing JSPs easily, return local
return remote;
}
public VirtualChannel getChannel() {
if(channel!=null) return channel;
else return Hudson.MasterComputer.localChannel;
}
private void writeObject(ObjectOutputStream oos) throws IOException {
Channel target = Channel.current();
if(channel!=null && channel!=target)
throw new IllegalStateException("Can't send a remote FilePath to a different remote channel");
oos.defaultWriteObject();
oos.writeBoolean(channel==null);
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
Channel channel = Channel.current();
assert channel!=null;
ois.defaultReadObject();
if(ois.readBoolean()) {
this.channel = channel;
} else {
this.channel = null;
}
}
private static final long serialVersionUID = 1L;
/**
* Adapts {@link FileCallable} to {@link Callable}.
*/
private class FileCallableWrapper<T> implements DelegatingCallable<T,IOException> {
private final FileCallable<T> callable;
public FileCallableWrapper(FileCallable<T> callable) {
this.callable = callable;
}
public T call() throws IOException {
return callable.invoke(new File(remote), Channel.current());
}
public ClassLoader getClassLoader() {
return callable.getClass().getClassLoader();
}
private static final long serialVersionUID = 1L;
}
}
| true | true | public int copyRecursiveTo(final String fileMask, final String excludes, final FilePath target) throws IOException, InterruptedException {
if(this.channel==target.channel) {
// local to local copy.
return act(new FileCallable<Integer>() {
public Integer invoke(File base, VirtualChannel channel) throws IOException {
assert target.channel==null;
try {
class CopyImpl extends Copy {
private int copySize;
public CopyImpl() {
setProject(new org.apache.tools.ant.Project());
}
protected void doFileOperations() {
copySize = super.fileCopyMap.size();
super.doFileOperations();
}
public int getNumCopied() {
return copySize;
}
}
CopyImpl copyTask = new CopyImpl();
copyTask.setTodir(new File(target.remote));
FileSet src = new FileSet();
src.setDir(base);
src.setIncludes(fileMask);
src.setExcludes(excludes);
copyTask.addFileset(src);
copyTask.execute();
return copyTask.getNumCopied();
} catch (BuildException e) {
throw new IOException2("Failed to copy "+base+"/"+fileMask+" to "+target,e);
}
}
});
} else
if(this.channel==null) {
// local -> remote copy
final Pipe pipe = Pipe.createLocalToRemote();
Future<Void> future = target.actAsync(new FileCallable<Void>() {
public Void invoke(File f, VirtualChannel channel) throws IOException {
readFromTar(f,pipe.getIn());
return null;
}
});
int r = writeToTar(new File(remote),fileMask,excludes,pipe);
try {
future.get();
} catch (ExecutionException e) {
throw new IOException2(e);
}
return r;
} else {
// remote -> local copy
final Pipe pipe = Pipe.createRemoteToLocal();
Future<Integer> future = actAsync(new FileCallable<Integer>() {
public Integer invoke(File f, VirtualChannel channel) throws IOException {
return writeToTar(f,fileMask,excludes,pipe);
}
});
readFromTar(new File(remote),pipe.getIn());
try {
return future.get();
} catch (ExecutionException e) {
throw new IOException2(e);
}
}
}
| public int copyRecursiveTo(final String fileMask, final String excludes, final FilePath target) throws IOException, InterruptedException {
if(this.channel==target.channel) {
// local to local copy.
return act(new FileCallable<Integer>() {
public Integer invoke(File base, VirtualChannel channel) throws IOException {
assert target.channel==null;
try {
class CopyImpl extends Copy {
private int copySize;
public CopyImpl() {
setProject(new org.apache.tools.ant.Project());
}
protected void doFileOperations() {
copySize = super.fileCopyMap.size();
super.doFileOperations();
}
public int getNumCopied() {
return copySize;
}
}
CopyImpl copyTask = new CopyImpl();
copyTask.setTodir(new File(target.remote));
FileSet src = new FileSet();
src.setDir(base);
src.setIncludes(fileMask);
src.setExcludes(excludes);
copyTask.addFileset(src);
copyTask.execute();
return copyTask.getNumCopied();
} catch (BuildException e) {
throw new IOException2("Failed to copy "+base+"/"+fileMask+" to "+target,e);
}
}
});
} else
if(this.channel==null) {
// local -> remote copy
final Pipe pipe = Pipe.createLocalToRemote();
Future<Void> future = target.actAsync(new FileCallable<Void>() {
public Void invoke(File f, VirtualChannel channel) throws IOException {
readFromTar(f,pipe.getIn());
return null;
}
});
int r = writeToTar(new File(remote),fileMask,excludes,pipe);
try {
future.get();
} catch (ExecutionException e) {
throw new IOException2(e);
}
return r;
} else {
// remote -> local copy
final Pipe pipe = Pipe.createRemoteToLocal();
Future<Integer> future = actAsync(new FileCallable<Integer>() {
public Integer invoke(File f, VirtualChannel channel) throws IOException {
return writeToTar(f,fileMask,excludes,pipe);
}
});
readFromTar(new File(target.remote),pipe.getIn());
try {
return future.get();
} catch (ExecutionException e) {
throw new IOException2(e);
}
}
}
|
diff --git a/src/upload/Upload.java b/src/upload/Upload.java
index 1f560c7..1b06633 100644
--- a/src/upload/Upload.java
+++ b/src/upload/Upload.java
@@ -1,55 +1,55 @@
package upload;
import static org.testng.AssertJUnit.assertEquals;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import org.openqa.selenium.By;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;
import pageFactory.ContentPage;
import basic.BasicTestCase;
public class Upload extends BasicTestCase {
private ContentPage obj = PageFactory.initElements(getWebDriver(), ContentPage.class);
WebDriverWait wait = new WebDriverWait(driver, 30);
//Upload track
@Test(priority = 1, groups={"Upload"}, description="Проверяет загрузку треков на сайт")
public void UploadTrack () throws Exception {
driver.get(musicUrl);
assertPage(musicUrl);
obj.Upload.click(); //go to upload link on head
setClipboard("C:\\test.mp3");
- wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[contains(@id,'SWFUpload_0')]"))).click();//click on upload button
+ driver.findElement(By.xpath("//*[contains(@id,'SWFUpload_0')]")).click();//click on upload button
keySendToWinForm();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath(".//*[@id='file_complete_status']/a"))).click(); // go to play list after download
driver.navigate().refresh();
assertEquals("Неизвестный исполнитель — test" ,driver.findElement(By.xpath("//*[@class='left']//*[@class='advanced_playlist']/li[1]")).getAttribute("audio_name")); //check track
obj.DelTrack.click(); //delete track from play list
}
//Функция для копирования в обуфер обмена Windows
public static void setClipboard(String str) {
StringSelection ss = new StringSelection(str);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
}
//Функция для отправки строки из буфера обмена в Win форму (аля на хуй скрипт)
public void keySendToWinForm () throws AWTException {
Robot robot = new Robot();
robot.delay(3000);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
}
}
| true | true | public void UploadTrack () throws Exception {
driver.get(musicUrl);
assertPage(musicUrl);
obj.Upload.click(); //go to upload link on head
setClipboard("C:\\test.mp3");
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[contains(@id,'SWFUpload_0')]"))).click();//click on upload button
keySendToWinForm();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath(".//*[@id='file_complete_status']/a"))).click(); // go to play list after download
driver.navigate().refresh();
assertEquals("Неизвестный исполнитель — test" ,driver.findElement(By.xpath("//*[@class='left']//*[@class='advanced_playlist']/li[1]")).getAttribute("audio_name")); //check track
obj.DelTrack.click(); //delete track from play list
}
| public void UploadTrack () throws Exception {
driver.get(musicUrl);
assertPage(musicUrl);
obj.Upload.click(); //go to upload link on head
setClipboard("C:\\test.mp3");
driver.findElement(By.xpath("//*[contains(@id,'SWFUpload_0')]")).click();//click on upload button
keySendToWinForm();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath(".//*[@id='file_complete_status']/a"))).click(); // go to play list after download
driver.navigate().refresh();
assertEquals("Неизвестный исполнитель — test" ,driver.findElement(By.xpath("//*[@class='left']//*[@class='advanced_playlist']/li[1]")).getAttribute("audio_name")); //check track
obj.DelTrack.click(); //delete track from play list
}
|
diff --git a/osgify-core/src/main/java/org/sourcepit/osgify/core/packaging/Repackager.java b/osgify-core/src/main/java/org/sourcepit/osgify/core/packaging/Repackager.java
index 7d13692..c2e2b0d 100644
--- a/osgify-core/src/main/java/org/sourcepit/osgify/core/packaging/Repackager.java
+++ b/osgify-core/src/main/java/org/sourcepit/osgify/core/packaging/Repackager.java
@@ -1,209 +1,209 @@
/**
* Copyright (c) 2012 Sourcepit.org contributors 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
*/
package org.sourcepit.osgify.core.packaging;
import static org.sourcepit.common.utils.io.IOResources.buffIn;
import static org.sourcepit.common.utils.io.IOResources.buffOut;
import static org.sourcepit.common.utils.io.IOResources.fileIn;
import static org.sourcepit.common.utils.io.IOResources.fileOut;
import static org.sourcepit.common.utils.io.IOResources.jarIn;
import static org.sourcepit.common.utils.io.IOResources.jarOut;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import java.util.jar.JarOutputStream;
import javax.inject.Named;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sourcepit.common.manifest.Manifest;
import org.sourcepit.common.manifest.osgi.resource.GenericManifestResourceImpl;
import org.sourcepit.common.utils.io.IOOperation;
import org.sourcepit.common.utils.lang.Exceptions;
import org.sourcepit.common.utils.lang.PipedIOException;
import org.sourcepit.common.utils.path.PathMatcher;
/**
* @author Bernd Vogt <[email protected]>
*/
@Named
public class Repackager
{
private final static PathMatcher JAR_CONTENT_MATCHER = createJarContentMatcher();
private final Logger logger = LoggerFactory.getLogger(Repackager.class);
public void injectManifest(final File jarFile, final Manifest manifest) throws PipedIOException
{
try
{
final File tmpFile = move(jarFile);
copyJarAndInjectManifest(tmpFile, jarFile, manifest);
org.apache.commons.io.FileUtils.forceDelete(tmpFile);
}
catch (IOException e)
{
throw Exceptions.pipe(e);
}
}
private File move(final File srcFile) throws IOException
{
String prefix = ".rejar";
String dirName = srcFile.getParentFile().getAbsolutePath();
String fileName = srcFile.getName();
File destFile = createTmpFile(dirName, fileName, prefix);
final boolean rename = srcFile.renameTo(destFile);
if (!rename)
{
org.apache.commons.io.FileUtils.copyFile(srcFile, destFile);
if (!srcFile.delete())
{
FileUtils.deleteQuietly(destFile);
throw new IOException("Failed to delete original file '" + srcFile + "' after copy to '" + destFile + "'");
}
}
return destFile;
}
private static File createTmpFile(String dirName, String fileName, String prefix) throws IOException
{
int unique = 0;
File file;
do
{
file = genFile(dirName, fileName, prefix, unique++);
}
while (!file.createNewFile());
return file;
}
private static File genFile(String dirName, String fileName, String prefix, int counter)
{
StringBuilder path = new StringBuilder();
path.append(dirName);
path.append(File.separatorChar);
path.append(fileName);
if (counter > 0)
{
final String n = String.valueOf(counter);
int lead = 5 - n.length();
for (int i = 0; i < lead; i++)
{
path.append('0');
}
path.append(n);
}
path.append(prefix);
return new File(path.toString());
}
public void copyJarAndInjectManifest(final File srcJarFile, final File destJarFile, final Manifest manifest)
throws PipedIOException
{
new IOOperation<JarOutputStream>(jarOut(buffOut(fileOut(destJarFile))))
{
@Override
protected void run(JarOutputStream destJarOut) throws IOException
{
rePackageJarFile(srcJarFile, manifest, destJarOut);
}
}.run();
}
private void rePackageJarFile(File srcJarFile, final Manifest manifest, final JarOutputStream destJarOut)
throws IOException
{
destJarOut.putNextEntry(new JarEntry(JarFile.MANIFEST_NAME));
writeManifest(manifest, destJarOut);
destJarOut.closeEntry();
new IOOperation<JarInputStream>(jarIn(buffIn(fileIn(srcJarFile))))
{
@Override
protected void run(JarInputStream srcJarIn) throws IOException
{
copyJarContents(srcJarIn, destJarOut);
}
}.run();
}
private void writeManifest(Manifest manifest, OutputStream out) throws IOException
{
Resource manifestResource = new GenericManifestResourceImpl();
manifestResource.getContents().add(EcoreUtil.copy(manifest));
manifestResource.save(out, null);
}
private void copyJarContents(JarInputStream srcJarIn, final JarOutputStream destJarOut) throws IOException
{
final Set<String> processedEntires = new HashSet<String>();
JarEntry srcEntry = srcJarIn.getNextJarEntry();
while (srcEntry != null)
{
final String entryName = srcEntry.getName();
if (JAR_CONTENT_MATCHER.isMatch(entryName))
{
if (processedEntires.add(entryName))
{
- destJarOut.putNextEntry(srcEntry);
+ destJarOut.putNextEntry(new JarEntry(srcEntry.getName()));
IOUtils.copy(srcJarIn, destJarOut);
destJarOut.closeEntry();
}
else
{
logger.warn("Ignored duplicate jar entry: " + entryName);
}
}
srcJarIn.closeEntry();
srcEntry = srcJarIn.getNextJarEntry();
}
}
private static PathMatcher createJarContentMatcher()
{
final Set<String> excludes = new HashSet<String>();
excludes.add(JarFile.MANIFEST_NAME); // will be set manually
excludes.add("META-INF/*.SF");
excludes.add("META-INF/*.DSA");
excludes.add("META-INF/*.RSA");
final String matcherPattern = toPathMatcherPattern(excludes);
return PathMatcher.parse(matcherPattern, "/", ",");
}
private static String toPathMatcherPattern(Set<String> excludes)
{
final StringBuilder sb = new StringBuilder();
for (String exclude : excludes)
{
sb.append('!');
sb.append(exclude);
sb.append(',');
}
if (sb.length() > 0)
{
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
}
| true | true | private void copyJarContents(JarInputStream srcJarIn, final JarOutputStream destJarOut) throws IOException
{
final Set<String> processedEntires = new HashSet<String>();
JarEntry srcEntry = srcJarIn.getNextJarEntry();
while (srcEntry != null)
{
final String entryName = srcEntry.getName();
if (JAR_CONTENT_MATCHER.isMatch(entryName))
{
if (processedEntires.add(entryName))
{
destJarOut.putNextEntry(srcEntry);
IOUtils.copy(srcJarIn, destJarOut);
destJarOut.closeEntry();
}
else
{
logger.warn("Ignored duplicate jar entry: " + entryName);
}
}
srcJarIn.closeEntry();
srcEntry = srcJarIn.getNextJarEntry();
}
}
| private void copyJarContents(JarInputStream srcJarIn, final JarOutputStream destJarOut) throws IOException
{
final Set<String> processedEntires = new HashSet<String>();
JarEntry srcEntry = srcJarIn.getNextJarEntry();
while (srcEntry != null)
{
final String entryName = srcEntry.getName();
if (JAR_CONTENT_MATCHER.isMatch(entryName))
{
if (processedEntires.add(entryName))
{
destJarOut.putNextEntry(new JarEntry(srcEntry.getName()));
IOUtils.copy(srcJarIn, destJarOut);
destJarOut.closeEntry();
}
else
{
logger.warn("Ignored duplicate jar entry: " + entryName);
}
}
srcJarIn.closeEntry();
srcEntry = srcJarIn.getNextJarEntry();
}
}
|
diff --git a/seminar/exercises/datamining/core/src/test/java/de/tuberlin/dima/aim/exercises/three/AverageTemperaturePerMonthPactTest.java b/seminar/exercises/datamining/core/src/test/java/de/tuberlin/dima/aim/exercises/three/AverageTemperaturePerMonthPactTest.java
index a7390d2..c70afc7 100644
--- a/seminar/exercises/datamining/core/src/test/java/de/tuberlin/dima/aim/exercises/three/AverageTemperaturePerMonthPactTest.java
+++ b/seminar/exercises/datamining/core/src/test/java/de/tuberlin/dima/aim/exercises/three/AverageTemperaturePerMonthPactTest.java
@@ -1,81 +1,82 @@
/**
* Copyright (C) 2011 AIM III course DIMA TU Berlin
*
* This programm is free software; you can redistribute it and/or modify
* it under the terms of 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.tuberlin.dima.aim.exercises.three;
import com.google.common.collect.Lists;
import de.tuberlin.dima.aim.exercises.HadoopAndPactTestcase;
import eu.stratosphere.pact.common.contract.MapContract;
import eu.stratosphere.pact.common.contract.ReduceContract;
import eu.stratosphere.pact.common.type.KeyValuePair;
import eu.stratosphere.pact.common.type.base.PactDouble;
import eu.stratosphere.pact.common.type.base.PactInteger;
import eu.stratosphere.pact.common.type.base.PactNull;
import eu.stratosphere.pact.common.type.base.PactString;
import eu.stratosphere.pact.testing.TestPlan;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
import java.util.regex.Pattern;
public class AverageTemperaturePerMonthPactTest extends HadoopAndPactTestcase {
private static final Pattern SEPARATOR = Pattern.compile("\t");
@Test
public void computeTemperatures() throws IOException {
MapContract<PactNull, PactString, AverageTemperaturePerMonthPact.YearMonthKey, PactInteger> mapContract =
new MapContract<PactNull, PactString, AverageTemperaturePerMonthPact.YearMonthKey, PactInteger>(
AverageTemperaturePerMonthPact.TemperaturePerYearAndMonthMapper.class);
ReduceContract<AverageTemperaturePerMonthPact.YearMonthKey, PactInteger,
AverageTemperaturePerMonthPact.YearMonthKey, PactDouble> reduceContract =
new ReduceContract<AverageTemperaturePerMonthPact.YearMonthKey, PactInteger,
AverageTemperaturePerMonthPact.YearMonthKey, PactDouble>(
AverageTemperaturePerMonthPact.TemperatePerYearAndMonthReducer.class);
reduceContract.setInput(mapContract);
TestPlan testPlan = new TestPlan(reduceContract);
for (String line : readLines("/one/temperatures.tsv")) {
testPlan.getInput().add(PactNull.getInstance(), new PactString(line));
}
+ testPlan.setAllowedPactDoubleDelta(0.0001);
for (KeyValuePair<AverageTemperaturePerMonthPact.YearMonthKey, PactDouble> expectedResult : expectedResults()) {
testPlan.getExpectedOutput().add(expectedResult.getKey(), expectedResult.getValue());
}
testPlan.run();
}
Iterable<KeyValuePair<AverageTemperaturePerMonthPact.YearMonthKey, PactDouble>> expectedResults() throws IOException {
List<KeyValuePair<AverageTemperaturePerMonthPact.YearMonthKey, PactDouble>> results = Lists.newArrayList();
for (String line : readLines("/three/averageTemperatures.tsv")) {
String[] tokens = SEPARATOR.split(line);
results.add(new KeyValuePair<AverageTemperaturePerMonthPact.YearMonthKey, PactDouble>(
new AverageTemperaturePerMonthPact.YearMonthKey(Short.parseShort(tokens[0]), Short.parseShort(tokens[1])),
new PactDouble(Double.parseDouble(tokens[2]))));
}
return results;
}
}
| true | true | public void computeTemperatures() throws IOException {
MapContract<PactNull, PactString, AverageTemperaturePerMonthPact.YearMonthKey, PactInteger> mapContract =
new MapContract<PactNull, PactString, AverageTemperaturePerMonthPact.YearMonthKey, PactInteger>(
AverageTemperaturePerMonthPact.TemperaturePerYearAndMonthMapper.class);
ReduceContract<AverageTemperaturePerMonthPact.YearMonthKey, PactInteger,
AverageTemperaturePerMonthPact.YearMonthKey, PactDouble> reduceContract =
new ReduceContract<AverageTemperaturePerMonthPact.YearMonthKey, PactInteger,
AverageTemperaturePerMonthPact.YearMonthKey, PactDouble>(
AverageTemperaturePerMonthPact.TemperatePerYearAndMonthReducer.class);
reduceContract.setInput(mapContract);
TestPlan testPlan = new TestPlan(reduceContract);
for (String line : readLines("/one/temperatures.tsv")) {
testPlan.getInput().add(PactNull.getInstance(), new PactString(line));
}
for (KeyValuePair<AverageTemperaturePerMonthPact.YearMonthKey, PactDouble> expectedResult : expectedResults()) {
testPlan.getExpectedOutput().add(expectedResult.getKey(), expectedResult.getValue());
}
testPlan.run();
}
| public void computeTemperatures() throws IOException {
MapContract<PactNull, PactString, AverageTemperaturePerMonthPact.YearMonthKey, PactInteger> mapContract =
new MapContract<PactNull, PactString, AverageTemperaturePerMonthPact.YearMonthKey, PactInteger>(
AverageTemperaturePerMonthPact.TemperaturePerYearAndMonthMapper.class);
ReduceContract<AverageTemperaturePerMonthPact.YearMonthKey, PactInteger,
AverageTemperaturePerMonthPact.YearMonthKey, PactDouble> reduceContract =
new ReduceContract<AverageTemperaturePerMonthPact.YearMonthKey, PactInteger,
AverageTemperaturePerMonthPact.YearMonthKey, PactDouble>(
AverageTemperaturePerMonthPact.TemperatePerYearAndMonthReducer.class);
reduceContract.setInput(mapContract);
TestPlan testPlan = new TestPlan(reduceContract);
for (String line : readLines("/one/temperatures.tsv")) {
testPlan.getInput().add(PactNull.getInstance(), new PactString(line));
}
testPlan.setAllowedPactDoubleDelta(0.0001);
for (KeyValuePair<AverageTemperaturePerMonthPact.YearMonthKey, PactDouble> expectedResult : expectedResults()) {
testPlan.getExpectedOutput().add(expectedResult.getKey(), expectedResult.getValue());
}
testPlan.run();
}
|
diff --git a/src/gui/BoardGUIDevelopment.java b/src/gui/BoardGUIDevelopment.java
index 00c08ab..ac3df48 100644
--- a/src/gui/BoardGUIDevelopment.java
+++ b/src/gui/BoardGUIDevelopment.java
@@ -1,141 +1,141 @@
package gui;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import sharedfiles.Board;
import sharedfiles.Piece;
public class BoardGUIDevelopment {
private JFrame frame;
private String[][] pieces;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
BoardGUIDevelopment window = new BoardGUIDevelopment();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public BoardGUIDevelopment() {
pieces = new String[8][8];
readBoard(new Board());
initialize();
}
private void readBoard(Board board) {
Piece[][] temp = board.getBoardArray();
for (int i = 0; i < temp.length; i++) {
for (int j = 0; j < temp.length; j++) {
pieces[i][j] = temp[i][j].toString();
}
}
}
protected ImageIcon createImageIcon(String path, String description) {
java.net.URL url = getClass().getResource(path);
if (url != null) {
return new ImageIcon(url, description);
} else {
System.err.println("DERPYFILE COULDN'T BE LOCATED: " + path);
return null;
}
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
Board b = new Board();
- b.Randomize();
+ b.randomize();
readBoard(b);
frame = new JFrame();
frame.setSize(425, 425);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
int i = 8;
int j = 8;
GridLayout steven = new GridLayout(i, j);
steven.setHgap(2);
steven.setVgap(2);
JPanel[][] panelHolder = new JPanel[i][j];
frame.setLayout(steven);
for (int m = 0; m < i; m++) {
for (int n = 0; n < j; n++) {
panelHolder[m][n] = new JPanel();
panelHolder[m][n].setSize(60, 60);
frame.add(panelHolder[m][n]);
}
}
for (int m = 0; m < i; m++) {
for (int n = 0; n < j; n++) {
String pieceType = pieces[m][n];
String tempResourceName = "" + Character.toLowerCase(pieceType.charAt(0));
switch (pieceType.charAt(1)) {
case 'X':
tempResourceName = "Blank";
break;
case 'B':
tempResourceName.concat("Bishop");
break;
case 'R':
tempResourceName.concat("Rook");
break;
case 'P':
tempResourceName.concat("Pawn");
break;
case 'Q':
tempResourceName.concat("Queen");
break;
case 'K':
tempResourceName.concat("King");
break;
case 'N':
tempResourceName.concat("Knight");
break;
default:
System.out.println("Reached default case in piece string array of BoardGUIDevelopment");
System.out.println("Exiting");
System.exit(1);
break;
}
tempResourceName.concat(".png");
ImageIcon icon = createImageIcon(tempResourceName, "Derpy Spot");
JLabel label = new JLabel();
label.setIcon(icon);
panelHolder[m][n].add(label);
}
}
frame.getContentPane().setLayout(steven);
}
}
| true | true | private void initialize() {
Board b = new Board();
b.Randomize();
readBoard(b);
frame = new JFrame();
frame.setSize(425, 425);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
int i = 8;
int j = 8;
GridLayout steven = new GridLayout(i, j);
steven.setHgap(2);
steven.setVgap(2);
JPanel[][] panelHolder = new JPanel[i][j];
frame.setLayout(steven);
for (int m = 0; m < i; m++) {
for (int n = 0; n < j; n++) {
panelHolder[m][n] = new JPanel();
panelHolder[m][n].setSize(60, 60);
frame.add(panelHolder[m][n]);
}
}
for (int m = 0; m < i; m++) {
for (int n = 0; n < j; n++) {
String pieceType = pieces[m][n];
String tempResourceName = "" + Character.toLowerCase(pieceType.charAt(0));
switch (pieceType.charAt(1)) {
case 'X':
tempResourceName = "Blank";
break;
case 'B':
tempResourceName.concat("Bishop");
break;
case 'R':
tempResourceName.concat("Rook");
break;
case 'P':
tempResourceName.concat("Pawn");
break;
case 'Q':
tempResourceName.concat("Queen");
break;
case 'K':
tempResourceName.concat("King");
break;
case 'N':
tempResourceName.concat("Knight");
break;
default:
System.out.println("Reached default case in piece string array of BoardGUIDevelopment");
System.out.println("Exiting");
System.exit(1);
break;
}
tempResourceName.concat(".png");
ImageIcon icon = createImageIcon(tempResourceName, "Derpy Spot");
JLabel label = new JLabel();
label.setIcon(icon);
panelHolder[m][n].add(label);
}
}
frame.getContentPane().setLayout(steven);
}
| private void initialize() {
Board b = new Board();
b.randomize();
readBoard(b);
frame = new JFrame();
frame.setSize(425, 425);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
int i = 8;
int j = 8;
GridLayout steven = new GridLayout(i, j);
steven.setHgap(2);
steven.setVgap(2);
JPanel[][] panelHolder = new JPanel[i][j];
frame.setLayout(steven);
for (int m = 0; m < i; m++) {
for (int n = 0; n < j; n++) {
panelHolder[m][n] = new JPanel();
panelHolder[m][n].setSize(60, 60);
frame.add(panelHolder[m][n]);
}
}
for (int m = 0; m < i; m++) {
for (int n = 0; n < j; n++) {
String pieceType = pieces[m][n];
String tempResourceName = "" + Character.toLowerCase(pieceType.charAt(0));
switch (pieceType.charAt(1)) {
case 'X':
tempResourceName = "Blank";
break;
case 'B':
tempResourceName.concat("Bishop");
break;
case 'R':
tempResourceName.concat("Rook");
break;
case 'P':
tempResourceName.concat("Pawn");
break;
case 'Q':
tempResourceName.concat("Queen");
break;
case 'K':
tempResourceName.concat("King");
break;
case 'N':
tempResourceName.concat("Knight");
break;
default:
System.out.println("Reached default case in piece string array of BoardGUIDevelopment");
System.out.println("Exiting");
System.exit(1);
break;
}
tempResourceName.concat(".png");
ImageIcon icon = createImageIcon(tempResourceName, "Derpy Spot");
JLabel label = new JLabel();
label.setIcon(icon);
panelHolder[m][n].add(label);
}
}
frame.getContentPane().setLayout(steven);
}
|
diff --git a/src/java/com/plausiblelabs/mdb/AccessExporter.java b/src/java/com/plausiblelabs/mdb/AccessExporter.java
index 52f3bff..68675f5 100644
--- a/src/java/com/plausiblelabs/mdb/AccessExporter.java
+++ b/src/java/com/plausiblelabs/mdb/AccessExporter.java
@@ -1,336 +1,336 @@
/*
* Copyright (c) 2008 Plausible Labs Cooperative, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of any 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 com.plausiblelabs.mdb;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.healthmarketscience.jackcess.Column;
import com.healthmarketscience.jackcess.Database;
import com.healthmarketscience.jackcess.Index;
import com.healthmarketscience.jackcess.Table;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
/**
* Handles export of an MS Access database to an SQLite file.
*/
public class AccessExporter {
/**
* Create a new exporter with the provided MS Access
* database
*
* @param db A reference to an Access database.
*/
public AccessExporter (Database db) {
this.db = db;
}
/* XXX: Manual escaping of identifiers. */
private String escapeIdentifier (final String identifier) {
return "'" + identifier.replace("'", "''") + "'";
}
/**
* Iterate over and create SQLite indeces for every index defined
* in the MS Access table.
*
* @param table MS Access table
* @param jdbc The SQLite database JDBC connection
* @throws SQLException
*/
private void createIndexes(final Table table, final Connection jdbc) throws SQLException {
final List<Index> indexes = table.getIndexes();
for (Index index : indexes) {
createIndex(index, jdbc);
}
}
/**
* Create an index in an SQLite table for the corresponding index in MS Access
*
* @param table MS Access table
* @param jdbc The SQLite database JDBC connection
* @throws SQLException
*/
private void createIndex(final Index index, final Connection jdbc) throws SQLException {
final List<Index.ColumnDescriptor> columns = index.getColumns();
final StringBuilder stmtBuilder = new StringBuilder();
/* Create the statement */
final String tableName = index.getTable().getName();
final String indexName = tableName + "_" + index.getName();
final String uniqueString = index.isUnique() ? "UNIQUE" : "";
stmtBuilder.append("CREATE "+ uniqueString + " INDEX " + escapeIdentifier(indexName));
stmtBuilder.append(" ON " + escapeIdentifier(tableName) + " (");
final int columnCount = columns.size();
for (int i = 0; i < columnCount; i++){
final Index.ColumnDescriptor column = columns.get(i);
stmtBuilder.append(escapeIdentifier(column.getName()));
stmtBuilder.append(" ");
if (i + 1 < columnCount)
stmtBuilder.append(", ");
}
stmtBuilder.append(")");
/* Execute it */
final Statement stmt = jdbc.createStatement();
stmt.execute(stmtBuilder.toString());
}
/**
* Create an SQLite table for the corresponding MS Access table.
*
* @param table MS Access table
* @param jdbc The SQLite database JDBC connection
* @throws SQLException
*/
private void createTable (final Table table, final Connection jdbc) throws SQLException {
final List<Column> columns = table.getColumns();
final StringBuilder stmtBuilder = new StringBuilder();
/* Create the statement */
stmtBuilder.append("CREATE TABLE " + escapeIdentifier(table.getName()) + " (");
final int columnCount = columns.size();
for (int i = 0; i < columnCount; i++) {
final Column column = columns.get(i);
stmtBuilder.append(escapeIdentifier(column.getName()));
stmtBuilder.append(" ");
switch (column.getType()) {
/* Blob */
case BINARY:
case OLE:
stmtBuilder.append("BLOB");
break;
/* Integers */
case BOOLEAN:
case BYTE:
case INT:
case LONG:
stmtBuilder.append("INTEGER");
break;
/* Timestamp */
case SHORT_DATE_TIME:
stmtBuilder.append("DATETIME");
break;
/* Floating point */
case DOUBLE:
case FLOAT:
case NUMERIC:
stmtBuilder.append("DOUBLE");
break;
/* Strings */
case TEXT:
case GUID:
case MEMO:
stmtBuilder.append("TEXT");
break;
/* Money -- This can't be floating point, so let's be safe with strings */
case MONEY:
stmtBuilder.append("TEXT");
break;
default:
throw new SQLException("Unhandled MS Acess datatype: " + column.getType());
}
if (i + 1 < columnCount)
stmtBuilder.append(", ");
}
stmtBuilder.append(")");
/* Execute it */
final Statement stmt = jdbc.createStatement();
stmt.execute(stmtBuilder.toString());
}
/**
* Iterate over and create SQLite tables for every table defined
* in the MS Access database.
*
* @param jdbc The SQLite database JDBC connection
*/
private void createTables (final Connection jdbc) throws IOException, SQLException {
final Set<String> tableNames = db.getTableNames();
for (String tableName : tableNames) {
Table table = db.getTable(tableName);
createTable(table, jdbc);
createIndexes(table, jdbc);
}
}
private void populateTable (Table table, Connection jdbc) throws SQLException, IOException {
final List<Column> columns = table.getColumns();
final StringBuilder stmtBuilder = new StringBuilder();
final StringBuilder valueStmtBuilder = new StringBuilder();
/* Record the column count */
final int columnCount = columns.size();
/* Build the INSERT statement (in two pieces simultaneously) */
stmtBuilder.append("INSERT INTO " + escapeIdentifier(table.getName()) + " (");
valueStmtBuilder.append("(");
for (int i = 0; i < columnCount; i++) {
final Column column = columns.get(i);
/* The column name and the VALUE binding */
stmtBuilder.append(escapeIdentifier(column.getName()));
valueStmtBuilder.append("?");
if (i + 1 < columnCount) {
stmtBuilder.append(", ");
valueStmtBuilder.append(", ");
}
}
/* Now append the VALUES piece */
stmtBuilder.append(") VALUES ");
stmtBuilder.append(valueStmtBuilder);
stmtBuilder.append(")");
/* Create the prepared statement */
final PreparedStatement prep = jdbc.prepareStatement(stmtBuilder.toString());
/* Kick off the insert spree */
for (Map<String, Object> row : table) {
/* Bind all the column values. We let JDBC do type conversion -- is this correct?. */
for (int i = 0; i < columnCount; i++) {
final Column column = columns.get(i);
final Object value = row.get(column.getName());
/* If null, just bail out early and avoid a lot of NULL checking */
if (value == null) {
prep.setObject(i + 1, value);
continue;
}
/* Perform any conversions */
switch (column.getType()) {
case BINARY:
case OLE:
ByteArrayOutputStream bStream = new ByteArrayOutputStream();
ObjectOutputStream oStream = new ObjectOutputStream(bStream);
oStream.writeObject(row.get(column.getName()));
prep.setBytes(i + 1, bStream.toByteArray());
break;
case FLOAT:
- prep.setDouble(+1, (Double) row.get(column.getName()));
+ prep.setDouble(i+1, (Float) row.get(column.getName()));
break;
case MONEY:
/* Store money as a string. Is there any other valid representation in SQLite? */
prep.setString(i + 1, row.get(column.getName()).toString());
break;
case BOOLEAN:
/* The SQLite JDBC driver does not handle boolean values */
final boolean bool;
final int intVal;
/* Determine the value (1/0) */
bool = (Boolean) row.get(column.getName());
if (bool)
intVal = 1;
else
intVal = 0;
/* Store it */
prep.setInt(i + 1, intVal);
break;
default:
prep.setObject(i + 1, row.get(column.getName()));
break;
}
}
/* Execute the insert */
prep.executeUpdate();
}
}
/**
* Iterate over all data and populate the SQLite tables
* @param jdbc The SQLite database JDBC connection
* @throws IOException
* @throws SQLException
*/
private void populateTables (final Connection jdbc) throws IOException, SQLException {
final Set<String> tableNames = db.getTableNames();
for (String tableName : tableNames) {
Table table = db.getTable(tableName);
populateTable(table, jdbc);
}
}
/**
* Export the Access database to the given SQLite JDBC connection.
* The referenced SQLite database should be empty.
*
* @param jdbc A JDBC connection to a SQLite database.
* @throws SQLException
*/
public void export (final Connection jdbc) throws IOException, SQLException {
/* Start a transaction */
jdbc.setAutoCommit(false);
/* Create the tables */
createTables(jdbc);
/* Populate the tables */
populateTables(jdbc);
jdbc.commit();
jdbc.setAutoCommit(true);
}
/** MS Access database */
private final Database db;
}
| true | true | private void populateTable (Table table, Connection jdbc) throws SQLException, IOException {
final List<Column> columns = table.getColumns();
final StringBuilder stmtBuilder = new StringBuilder();
final StringBuilder valueStmtBuilder = new StringBuilder();
/* Record the column count */
final int columnCount = columns.size();
/* Build the INSERT statement (in two pieces simultaneously) */
stmtBuilder.append("INSERT INTO " + escapeIdentifier(table.getName()) + " (");
valueStmtBuilder.append("(");
for (int i = 0; i < columnCount; i++) {
final Column column = columns.get(i);
/* The column name and the VALUE binding */
stmtBuilder.append(escapeIdentifier(column.getName()));
valueStmtBuilder.append("?");
if (i + 1 < columnCount) {
stmtBuilder.append(", ");
valueStmtBuilder.append(", ");
}
}
/* Now append the VALUES piece */
stmtBuilder.append(") VALUES ");
stmtBuilder.append(valueStmtBuilder);
stmtBuilder.append(")");
/* Create the prepared statement */
final PreparedStatement prep = jdbc.prepareStatement(stmtBuilder.toString());
/* Kick off the insert spree */
for (Map<String, Object> row : table) {
/* Bind all the column values. We let JDBC do type conversion -- is this correct?. */
for (int i = 0; i < columnCount; i++) {
final Column column = columns.get(i);
final Object value = row.get(column.getName());
/* If null, just bail out early and avoid a lot of NULL checking */
if (value == null) {
prep.setObject(i + 1, value);
continue;
}
/* Perform any conversions */
switch (column.getType()) {
case BINARY:
case OLE:
ByteArrayOutputStream bStream = new ByteArrayOutputStream();
ObjectOutputStream oStream = new ObjectOutputStream(bStream);
oStream.writeObject(row.get(column.getName()));
prep.setBytes(i + 1, bStream.toByteArray());
break;
case FLOAT:
prep.setDouble(+1, (Double) row.get(column.getName()));
break;
case MONEY:
/* Store money as a string. Is there any other valid representation in SQLite? */
prep.setString(i + 1, row.get(column.getName()).toString());
break;
case BOOLEAN:
/* The SQLite JDBC driver does not handle boolean values */
final boolean bool;
final int intVal;
/* Determine the value (1/0) */
bool = (Boolean) row.get(column.getName());
if (bool)
intVal = 1;
else
intVal = 0;
/* Store it */
prep.setInt(i + 1, intVal);
break;
default:
prep.setObject(i + 1, row.get(column.getName()));
break;
}
}
/* Execute the insert */
prep.executeUpdate();
}
}
| private void populateTable (Table table, Connection jdbc) throws SQLException, IOException {
final List<Column> columns = table.getColumns();
final StringBuilder stmtBuilder = new StringBuilder();
final StringBuilder valueStmtBuilder = new StringBuilder();
/* Record the column count */
final int columnCount = columns.size();
/* Build the INSERT statement (in two pieces simultaneously) */
stmtBuilder.append("INSERT INTO " + escapeIdentifier(table.getName()) + " (");
valueStmtBuilder.append("(");
for (int i = 0; i < columnCount; i++) {
final Column column = columns.get(i);
/* The column name and the VALUE binding */
stmtBuilder.append(escapeIdentifier(column.getName()));
valueStmtBuilder.append("?");
if (i + 1 < columnCount) {
stmtBuilder.append(", ");
valueStmtBuilder.append(", ");
}
}
/* Now append the VALUES piece */
stmtBuilder.append(") VALUES ");
stmtBuilder.append(valueStmtBuilder);
stmtBuilder.append(")");
/* Create the prepared statement */
final PreparedStatement prep = jdbc.prepareStatement(stmtBuilder.toString());
/* Kick off the insert spree */
for (Map<String, Object> row : table) {
/* Bind all the column values. We let JDBC do type conversion -- is this correct?. */
for (int i = 0; i < columnCount; i++) {
final Column column = columns.get(i);
final Object value = row.get(column.getName());
/* If null, just bail out early and avoid a lot of NULL checking */
if (value == null) {
prep.setObject(i + 1, value);
continue;
}
/* Perform any conversions */
switch (column.getType()) {
case BINARY:
case OLE:
ByteArrayOutputStream bStream = new ByteArrayOutputStream();
ObjectOutputStream oStream = new ObjectOutputStream(bStream);
oStream.writeObject(row.get(column.getName()));
prep.setBytes(i + 1, bStream.toByteArray());
break;
case FLOAT:
prep.setDouble(i+1, (Float) row.get(column.getName()));
break;
case MONEY:
/* Store money as a string. Is there any other valid representation in SQLite? */
prep.setString(i + 1, row.get(column.getName()).toString());
break;
case BOOLEAN:
/* The SQLite JDBC driver does not handle boolean values */
final boolean bool;
final int intVal;
/* Determine the value (1/0) */
bool = (Boolean) row.get(column.getName());
if (bool)
intVal = 1;
else
intVal = 0;
/* Store it */
prep.setInt(i + 1, intVal);
break;
default:
prep.setObject(i + 1, row.get(column.getName()));
break;
}
}
/* Execute the insert */
prep.executeUpdate();
}
}
|
diff --git a/ProjectAPI/src/org/gephi/project/io/LoadTask.java b/ProjectAPI/src/org/gephi/project/io/LoadTask.java
index 3c25de1d5..45b1349ae 100644
--- a/ProjectAPI/src/org/gephi/project/io/LoadTask.java
+++ b/ProjectAPI/src/org/gephi/project/io/LoadTask.java
@@ -1,115 +1,115 @@
/*
Copyright 2008-2010 Gephi
Authors : Mathieu Bastian <[email protected]>
Website : http://www.gephi.org
This file is part of Gephi.
Gephi 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.
Gephi 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 Gephi. If not, see <http://www.gnu.org/licenses/>.
*/
package org.gephi.project.io;
import java.io.File;
import javax.xml.stream.Location;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLReporter;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.gephi.project.impl.ProjectImpl;
import org.gephi.project.impl.ProjectInformationImpl;
import org.gephi.project.api.Project;
import org.gephi.project.impl.ProjectControllerImpl;
import org.gephi.utils.longtask.spi.LongTask;
import org.gephi.utils.progress.Progress;
import org.gephi.utils.progress.ProgressTicket;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.util.Lookup;
import org.openide.util.NbBundle;
/**
*
* @author Mathieu Bastian
*/
public class LoadTask implements LongTask, Runnable {
private File file;
private GephiReader gephiReader;
private boolean cancel = false;
private ProgressTicket progressTicket;
public LoadTask(File file) {
this.file = file;
}
public void run() {
try {
Progress.start(progressTicket);
- Progress.setDisplayName(progressTicket, NbBundle.getMessage(SaveTask.class, "LoadTask.name"));
+ Progress.setDisplayName(progressTicket, NbBundle.getMessage(LoadTask.class, "LoadTask.name"));
FileObject fileObject = FileUtil.toFileObject(file);
if (FileUtil.isArchiveFile(fileObject)) {
//Unzip
fileObject = FileUtil.getArchiveRoot(fileObject).getChildren()[0];
}
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
if (inputFactory.isPropertySupported("javax.xml.stream.isValidating")) {
inputFactory.setProperty("javax.xml.stream.isValidating", Boolean.FALSE);
}
inputFactory.setXMLReporter(new XMLReporter() {
@Override
public void report(String message, String errorType, Object relatedInformation, Location location) throws XMLStreamException {
System.out.println("Error:" + errorType + ", message : " + message);
}
});
XMLStreamReader reader = inputFactory.createXMLStreamReader(fileObject.getInputStream());
if (!cancel) {
//Project instance
Project project = new ProjectImpl();
project.getLookup().lookup(ProjectInformationImpl.class).setFile(file);
//GephiReader
gephiReader = new GephiReader();
project = gephiReader.readAll(reader, project);
//Add project
if (!cancel) {
ProjectControllerImpl pc = Lookup.getDefault().lookup(ProjectControllerImpl.class);
pc.openProject(project);
}
}
Progress.finish(progressTicket);
} catch (Exception ex) {
ex.printStackTrace();
if (ex instanceof GephiFormatException) {
throw (GephiFormatException) ex;
}
throw new GephiFormatException(GephiReader.class, ex);
}
}
public boolean cancel() {
cancel = true;
if (gephiReader != null) {
gephiReader.cancel();
}
return true;
}
public void setProgressTicket(ProgressTicket progressTicket) {
this.progressTicket = progressTicket;
}
}
| true | true | public void run() {
try {
Progress.start(progressTicket);
Progress.setDisplayName(progressTicket, NbBundle.getMessage(SaveTask.class, "LoadTask.name"));
FileObject fileObject = FileUtil.toFileObject(file);
if (FileUtil.isArchiveFile(fileObject)) {
//Unzip
fileObject = FileUtil.getArchiveRoot(fileObject).getChildren()[0];
}
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
if (inputFactory.isPropertySupported("javax.xml.stream.isValidating")) {
inputFactory.setProperty("javax.xml.stream.isValidating", Boolean.FALSE);
}
inputFactory.setXMLReporter(new XMLReporter() {
@Override
public void report(String message, String errorType, Object relatedInformation, Location location) throws XMLStreamException {
System.out.println("Error:" + errorType + ", message : " + message);
}
});
XMLStreamReader reader = inputFactory.createXMLStreamReader(fileObject.getInputStream());
if (!cancel) {
//Project instance
Project project = new ProjectImpl();
project.getLookup().lookup(ProjectInformationImpl.class).setFile(file);
//GephiReader
gephiReader = new GephiReader();
project = gephiReader.readAll(reader, project);
//Add project
if (!cancel) {
ProjectControllerImpl pc = Lookup.getDefault().lookup(ProjectControllerImpl.class);
pc.openProject(project);
}
}
Progress.finish(progressTicket);
} catch (Exception ex) {
ex.printStackTrace();
if (ex instanceof GephiFormatException) {
throw (GephiFormatException) ex;
}
throw new GephiFormatException(GephiReader.class, ex);
}
}
| public void run() {
try {
Progress.start(progressTicket);
Progress.setDisplayName(progressTicket, NbBundle.getMessage(LoadTask.class, "LoadTask.name"));
FileObject fileObject = FileUtil.toFileObject(file);
if (FileUtil.isArchiveFile(fileObject)) {
//Unzip
fileObject = FileUtil.getArchiveRoot(fileObject).getChildren()[0];
}
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
if (inputFactory.isPropertySupported("javax.xml.stream.isValidating")) {
inputFactory.setProperty("javax.xml.stream.isValidating", Boolean.FALSE);
}
inputFactory.setXMLReporter(new XMLReporter() {
@Override
public void report(String message, String errorType, Object relatedInformation, Location location) throws XMLStreamException {
System.out.println("Error:" + errorType + ", message : " + message);
}
});
XMLStreamReader reader = inputFactory.createXMLStreamReader(fileObject.getInputStream());
if (!cancel) {
//Project instance
Project project = new ProjectImpl();
project.getLookup().lookup(ProjectInformationImpl.class).setFile(file);
//GephiReader
gephiReader = new GephiReader();
project = gephiReader.readAll(reader, project);
//Add project
if (!cancel) {
ProjectControllerImpl pc = Lookup.getDefault().lookup(ProjectControllerImpl.class);
pc.openProject(project);
}
}
Progress.finish(progressTicket);
} catch (Exception ex) {
ex.printStackTrace();
if (ex instanceof GephiFormatException) {
throw (GephiFormatException) ex;
}
throw new GephiFormatException(GephiReader.class, ex);
}
}
|
diff --git a/src/test/java/com/flazr/io/flv/H263PacketTest.java b/src/test/java/com/flazr/io/flv/H263PacketTest.java
index a1b2ae6..231bd03 100644
--- a/src/test/java/com/flazr/io/flv/H263PacketTest.java
+++ b/src/test/java/com/flazr/io/flv/H263PacketTest.java
@@ -1,20 +1,20 @@
package com.flazr.io.flv;
import com.flazr.util.Utils;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import static org.junit.Assert.*;
import org.junit.Test;
public class H263PacketTest {
@Test
public void testParseH263Header() {
ChannelBuffer in = ChannelBuffers.wrappedBuffer(
Utils.fromHex("00008400814000f0343f"));
- H263Packet packet = new H263Packet(in);
+ H263Packet packet = new H263Packet(in, 0);
assertEquals(640, packet.getWidth());
assertEquals(480, packet.getHeight());
}
}
| true | true | public void testParseH263Header() {
ChannelBuffer in = ChannelBuffers.wrappedBuffer(
Utils.fromHex("00008400814000f0343f"));
H263Packet packet = new H263Packet(in);
assertEquals(640, packet.getWidth());
assertEquals(480, packet.getHeight());
}
| public void testParseH263Header() {
ChannelBuffer in = ChannelBuffers.wrappedBuffer(
Utils.fromHex("00008400814000f0343f"));
H263Packet packet = new H263Packet(in, 0);
assertEquals(640, packet.getWidth());
assertEquals(480, packet.getHeight());
}
|
diff --git a/src/main/java/net/syamn/sakuracmd/commands/other/AdminCommand.java b/src/main/java/net/syamn/sakuracmd/commands/other/AdminCommand.java
index d5b5a08..6487c49 100644
--- a/src/main/java/net/syamn/sakuracmd/commands/other/AdminCommand.java
+++ b/src/main/java/net/syamn/sakuracmd/commands/other/AdminCommand.java
@@ -1,107 +1,106 @@
/**
* SakuraCmd - Package: net.syamn.sakuracmd.commands.other
* Created: 2013/01/18 15:22:18
*/
package net.syamn.sakuracmd.commands.other;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import net.syamn.sakuracmd.commands.BaseCommand;
import net.syamn.sakuracmd.permission.Perms;
import net.syamn.utils.StrUtil;
import net.syamn.utils.Util;
import net.syamn.utils.exception.CommandException;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
/**
* AdminCommand (AdminCommand.java)
* @author syam(syamn)
*/
public class AdminCommand extends BaseCommand {
public AdminCommand() {
bePlayer = false;
name = "admin";
perm = Perms.ADMIN;
argLength = 1;
usage = "<- admin commands";
}
@Override
public void execute() throws CommandException {
final String sub = args.remove(0).trim().toLowerCase(Locale.ENGLISH);
// bcast
if (sub.equals("bcast") && args.size() > 0) {
- args.remove(0);
Util.broadcastMessage(StrUtil.join(args, " "));
return;
}
// item
if (sub.equals("item") && isPlayer && args.size() > 0){
final String action = args.remove(0).trim().toLowerCase(Locale.ENGLISH);
final String str = (args.size() > 0) ? Util.coloring(StrUtil.join(args, " ")) : null;
ItemStack is = player.getItemInHand();
if (is == null || is.getType() == Material.AIR){
throw new CommandException("&c手にアイテムを持っていません!");
}
ItemMeta meta = is.getItemMeta();
if (action.equals("name")){
if (str == null){
throw new CommandException("&cメッセージが入力されていません!");
}
meta.setDisplayName(str);
}else if (action.equals("add")){
if (str == null){
throw new CommandException("&cメッセージが入力されていません!");
}
List<String> lores = meta.getLore();
if (lores == null){
lores = new ArrayList<String>();
}
lores.add(str);
meta.setLore(lores);
}else if (action.equals("clear")){
meta.setLore(null);
}else{
throw new CommandException("&c指定したNBT編集アクションは存在しません!");
}
is.setItemMeta(meta);
player.setItemInHand(is);
Util.message(sender, "&aNBTを編集しました!");
return;
}
// head
if (sub.equals("head") && isPlayer && args.size() > 0){
final String name = args.get(0).trim();
if (!StrUtil.isValidName(name)){
throw new CommandException("&cプレイヤー名が不正です!");
}
ItemStack is = player.getItemInHand();
if(is == null || is.getType() != Material.SKULL_ITEM){
throw new CommandException("&cプレイヤーヘッドを持っていません!");
}
is.setDurability((short) 3);
SkullMeta meta = (SkullMeta) is.getItemMeta();
meta.setOwner(name);
is.setItemMeta(meta);
player.setItemInHand(is);
Util.message(sender, "&aプレイヤーヘッドを " + name + " に変更しました!");
return;
}
Util.message(sender, "&cUnknown sub-command!");
}
}
| true | true | public void execute() throws CommandException {
final String sub = args.remove(0).trim().toLowerCase(Locale.ENGLISH);
// bcast
if (sub.equals("bcast") && args.size() > 0) {
args.remove(0);
Util.broadcastMessage(StrUtil.join(args, " "));
return;
}
// item
if (sub.equals("item") && isPlayer && args.size() > 0){
final String action = args.remove(0).trim().toLowerCase(Locale.ENGLISH);
final String str = (args.size() > 0) ? Util.coloring(StrUtil.join(args, " ")) : null;
ItemStack is = player.getItemInHand();
if (is == null || is.getType() == Material.AIR){
throw new CommandException("&c手にアイテムを持っていません!");
}
ItemMeta meta = is.getItemMeta();
if (action.equals("name")){
if (str == null){
throw new CommandException("&cメッセージが入力されていません!");
}
meta.setDisplayName(str);
}else if (action.equals("add")){
if (str == null){
throw new CommandException("&cメッセージが入力されていません!");
}
List<String> lores = meta.getLore();
if (lores == null){
lores = new ArrayList<String>();
}
lores.add(str);
meta.setLore(lores);
}else if (action.equals("clear")){
meta.setLore(null);
}else{
throw new CommandException("&c指定したNBT編集アクションは存在しません!");
}
is.setItemMeta(meta);
player.setItemInHand(is);
Util.message(sender, "&aNBTを編集しました!");
return;
}
// head
if (sub.equals("head") && isPlayer && args.size() > 0){
final String name = args.get(0).trim();
if (!StrUtil.isValidName(name)){
throw new CommandException("&cプレイヤー名が不正です!");
}
ItemStack is = player.getItemInHand();
if(is == null || is.getType() != Material.SKULL_ITEM){
throw new CommandException("&cプレイヤーヘッドを持っていません!");
}
is.setDurability((short) 3);
SkullMeta meta = (SkullMeta) is.getItemMeta();
meta.setOwner(name);
is.setItemMeta(meta);
player.setItemInHand(is);
Util.message(sender, "&aプレイヤーヘッドを " + name + " に変更しました!");
return;
}
Util.message(sender, "&cUnknown sub-command!");
}
| public void execute() throws CommandException {
final String sub = args.remove(0).trim().toLowerCase(Locale.ENGLISH);
// bcast
if (sub.equals("bcast") && args.size() > 0) {
Util.broadcastMessage(StrUtil.join(args, " "));
return;
}
// item
if (sub.equals("item") && isPlayer && args.size() > 0){
final String action = args.remove(0).trim().toLowerCase(Locale.ENGLISH);
final String str = (args.size() > 0) ? Util.coloring(StrUtil.join(args, " ")) : null;
ItemStack is = player.getItemInHand();
if (is == null || is.getType() == Material.AIR){
throw new CommandException("&c手にアイテムを持っていません!");
}
ItemMeta meta = is.getItemMeta();
if (action.equals("name")){
if (str == null){
throw new CommandException("&cメッセージが入力されていません!");
}
meta.setDisplayName(str);
}else if (action.equals("add")){
if (str == null){
throw new CommandException("&cメッセージが入力されていません!");
}
List<String> lores = meta.getLore();
if (lores == null){
lores = new ArrayList<String>();
}
lores.add(str);
meta.setLore(lores);
}else if (action.equals("clear")){
meta.setLore(null);
}else{
throw new CommandException("&c指定したNBT編集アクションは存在しません!");
}
is.setItemMeta(meta);
player.setItemInHand(is);
Util.message(sender, "&aNBTを編集しました!");
return;
}
// head
if (sub.equals("head") && isPlayer && args.size() > 0){
final String name = args.get(0).trim();
if (!StrUtil.isValidName(name)){
throw new CommandException("&cプレイヤー名が不正です!");
}
ItemStack is = player.getItemInHand();
if(is == null || is.getType() != Material.SKULL_ITEM){
throw new CommandException("&cプレイヤーヘッドを持っていません!");
}
is.setDurability((short) 3);
SkullMeta meta = (SkullMeta) is.getItemMeta();
meta.setOwner(name);
is.setItemMeta(meta);
player.setItemInHand(is);
Util.message(sender, "&aプレイヤーヘッドを " + name + " に変更しました!");
return;
}
Util.message(sender, "&cUnknown sub-command!");
}
|
diff --git a/ide-test/org.codehaus.groovy.eclipse.codeassist.completion.test/src/org/codehaus/groovy/eclipse/codeassist/tests/GuessingCompletionTests.java b/ide-test/org.codehaus.groovy.eclipse.codeassist.completion.test/src/org/codehaus/groovy/eclipse/codeassist/tests/GuessingCompletionTests.java
index 4f160f000..56587a58c 100644
--- a/ide-test/org.codehaus.groovy.eclipse.codeassist.completion.test/src/org/codehaus/groovy/eclipse/codeassist/tests/GuessingCompletionTests.java
+++ b/ide-test/org.codehaus.groovy.eclipse.codeassist.completion.test/src/org/codehaus/groovy/eclipse/codeassist/tests/GuessingCompletionTests.java
@@ -1,79 +1,79 @@
/*******************************************************************************
* Copyright (c) 2011 SpringSource 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:
* Andrew Eisenberg - initial API and implementation
*******************************************************************************/
package org.codehaus.groovy.eclipse.codeassist.tests;
/**
* @author Andrew Eisenberg
* @created Sep 9, 2011
*
*/
public class GuessingCompletionTests extends CompletionTestCase {
public GuessingCompletionTests() {
super("Parameter guessing test cases");
}
public void testParamGuessing1() throws Exception {
String contents = "String yyy\n" +
"def xxx(String x) { }\n" +
"xxx";
String[][] expectedChoices = new String[][] { new String[] { "yyy", "\"\"" } };
checkProposalChoices(contents, "xxx", "xxx(yyy)", expectedChoices);
}
public void testParamGuessing2() throws Exception {
String contents =
"String yyy\n" +
"int zzz\n" +
"def xxx(String x, int z) { }\n" +
"xxx";
String[][] expectedChoices = new String[][] { new String[] { "yyy", "\"\"" }, new String[] { "zzz", "0" } };
checkProposalChoices(contents, "xxx", "xxx(yyy, zzz)", expectedChoices);
}
public void testParamGuessing3() throws Exception {
String contents =
"String yyy\n" +
"Integer zzz\n" +
"boolean aaa\n" +
"def xxx(String x, int z, boolean a) { }\n" +
"xxx";
String[][] expectedChoices = new String[][] { new String[] { "yyy", "\"\"" }, new String[] { "zzz", "0" }, new String[] { "aaa", "false", "true" } };
checkProposalChoices(contents, "xxx", "xxx(yyy, zzz, aaa)", expectedChoices);
}
// GRECLIPSE-1268 This test may fail in some environments since the ordering of
// guessed parameters is not based on actual source location. Need a way to map
// from variable name to local variable declaration in GroovyExtendedCompletionContext.computeVisibleElements(String)
public void testParamGuessing4() throws Exception {
String contents =
"Closure yyy\n" +
"def zzz = { }\n" +
"def xxx(Closure c) { }\n" +
"xxx";
- String[][] expectedChoices = new String[][] { new String[] { "zzz", "yyy", "{" } };
+ String[][] expectedChoices = new String[][] { new String[] { "zzz", "yyy", "{ }" } };
try {
checkProposalChoices(contents, "xxx", "xxx {", expectedChoices);
} catch (AssertionError e) {
try {
checkProposalChoices(contents, "xxx", "xxx zzz", expectedChoices);
} catch (AssertionError e2) {
// this version is also a correct result
checkProposalChoices(contents, "xxx", "xxx yyy", expectedChoices);
}
}
}
}
| true | true | public void testParamGuessing4() throws Exception {
String contents =
"Closure yyy\n" +
"def zzz = { }\n" +
"def xxx(Closure c) { }\n" +
"xxx";
String[][] expectedChoices = new String[][] { new String[] { "zzz", "yyy", "{" } };
try {
checkProposalChoices(contents, "xxx", "xxx {", expectedChoices);
} catch (AssertionError e) {
try {
checkProposalChoices(contents, "xxx", "xxx zzz", expectedChoices);
} catch (AssertionError e2) {
// this version is also a correct result
checkProposalChoices(contents, "xxx", "xxx yyy", expectedChoices);
}
}
}
| public void testParamGuessing4() throws Exception {
String contents =
"Closure yyy\n" +
"def zzz = { }\n" +
"def xxx(Closure c) { }\n" +
"xxx";
String[][] expectedChoices = new String[][] { new String[] { "zzz", "yyy", "{ }" } };
try {
checkProposalChoices(contents, "xxx", "xxx {", expectedChoices);
} catch (AssertionError e) {
try {
checkProposalChoices(contents, "xxx", "xxx zzz", expectedChoices);
} catch (AssertionError e2) {
// this version is also a correct result
checkProposalChoices(contents, "xxx", "xxx yyy", expectedChoices);
}
}
}
|
diff --git a/cmds/monkey/src/com/android/commands/monkey/Monkey.java b/cmds/monkey/src/com/android/commands/monkey/Monkey.java
index 43103236..bb0663fd 100644
--- a/cmds/monkey/src/com/android/commands/monkey/Monkey.java
+++ b/cmds/monkey/src/com/android/commands/monkey/Monkey.java
@@ -1,992 +1,992 @@
/*
* Copyright 2007, 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.commands.monkey;
import android.app.ActivityManagerNative;
import android.app.IActivityManager;
import android.app.IActivityController;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.IPackageManager;
import android.content.pm.ResolveInfo;
import android.os.Debug;
import android.os.Process;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.server.data.CrashData;
import android.view.IWindowManager;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
/**
* Application that injects random key events and other actions into the system.
*/
public class Monkey {
/**
* Monkey Debugging/Dev Support
* <p>
* All values should be zero when checking in.
*/
private final static int DEBUG_ALLOW_ANY_STARTS = 0;
private final static int DEBUG_ALLOW_ANY_RESTARTS = 0;
private IActivityManager mAm;
private IWindowManager mWm;
private IPackageManager mPm;
/** Command line arguments */
private String[] mArgs;
/** Current argument being parsed */
private int mNextArg;
/** Data of current argument */
private String mCurArgData;
/** Running in verbose output mode? 1= verbose, 2=very verbose */
private int mVerbose;
/** Ignore any application crashes while running? */
private boolean mIgnoreCrashes;
/** Ignore any not responding timeouts while running? */
private boolean mIgnoreTimeouts;
/** Ignore security exceptions when launching activities */
/** (The activity launch still fails, but we keep pluggin' away) */
private boolean mIgnoreSecurityExceptions;
/** Monitor /data/tombstones and stop the monkey if new files appear. */
private boolean mMonitorNativeCrashes;
/** Send no events. Use with long throttle-time to watch user operations */
private boolean mSendNoEvents;
/** This is set when we would like to abort the running of the monkey. */
private boolean mAbort;
/**
* Count each event as a cycle. Set to false for scripts so that each time
* through the script increments the count.
*/
private boolean mCountEvents = true;
/**
* This is set by the ActivityController thread to request collection of ANR
* trace files
*/
private boolean mRequestAnrTraces = false;
/**
* This is set by the ActivityController thread to request a
* "dumpsys meminfo"
*/
private boolean mRequestDumpsysMemInfo = false;
/** Kill the process after a timeout or crash. */
private boolean mKillProcessAfterError;
/** Generate hprof reports before/after monkey runs */
private boolean mGenerateHprof;
/** Packages we are allowed to run, or empty if no restriction. */
private HashSet<String> mValidPackages = new HashSet<String>();
/** Categories we are allowed to launch **/
private ArrayList<String> mMainCategories = new ArrayList<String>();
/** Applications we can switch to. */
private ArrayList<ComponentName> mMainApps = new ArrayList<ComponentName>();
/** The delay between event inputs **/
long mThrottle = 0;
/** The number of iterations **/
int mCount = 1000;
/** The random number seed **/
long mSeed = 0;
/** Dropped-event statistics **/
long mDroppedKeyEvents = 0;
long mDroppedPointerEvents = 0;
long mDroppedTrackballEvents = 0;
long mDroppedFlipEvents = 0;
/** a filename to the setup script (if any) */
private String mSetupFileName = null;
/** filenames of the script (if any) */
private ArrayList<String> mScriptFileNames = new ArrayList<String>();
/** a TCP port to listen on for remote commands. */
private int mServerPort = -1;
private static final File TOMBSTONES_PATH = new File("/data/tombstones");
private HashSet<String> mTombstones = null;
float[] mFactors = new float[MonkeySourceRandom.FACTORZ_COUNT];
MonkeyEventSource mEventSource;
private MonkeyNetworkMonitor mNetworkMonitor = new MonkeyNetworkMonitor();
// information on the current activity.
public static Intent currentIntent;
public static String currentPackage;
/**
* Monitor operations happening in the system.
*/
private class ActivityController extends IActivityController.Stub {
public boolean activityStarting(Intent intent, String pkg) {
boolean allow = checkEnteringPackage(pkg) || (DEBUG_ALLOW_ANY_STARTS != 0);
if (mVerbose > 0) {
System.out.println(" // " + (allow ? "Allowing" : "Rejecting") + " start of "
+ intent + " in package " + pkg);
}
currentPackage = pkg;
currentIntent = intent;
return allow;
}
public boolean activityResuming(String pkg) {
System.out.println(" // activityResuming(" + pkg + ")");
boolean allow = checkEnteringPackage(pkg) || (DEBUG_ALLOW_ANY_RESTARTS != 0);
if (!allow) {
if (mVerbose > 0) {
System.out.println(" // " + (allow ? "Allowing" : "Rejecting")
+ " resume of package " + pkg);
}
}
currentPackage = pkg;
return allow;
}
private boolean checkEnteringPackage(String pkg) {
if (pkg == null) {
return true;
}
// preflight the hash lookup to avoid the cost of hash key
// generation
if (mValidPackages.size() == 0) {
return true;
} else {
return mValidPackages.contains(pkg);
}
}
public boolean appCrashed(String processName, int pid, String shortMsg, String longMsg,
byte[] crashData) {
System.err.println("// CRASH: " + processName + " (pid " + pid + ")");
System.err.println("// Short Msg: " + shortMsg);
System.err.println("// Long Msg: " + longMsg);
if (crashData != null) {
try {
CrashData cd = new CrashData(new DataInputStream(new ByteArrayInputStream(
crashData)));
System.err.println("// Build Label: " + cd.getBuildData().getFingerprint());
System.err.println("// Build Changelist: "
+ cd.getBuildData().getIncrementalVersion());
System.err.println("// Build Time: " + cd.getBuildData().getTime());
System.err.println("// ID: " + cd.getId());
System.err.println("// Tag: " + cd.getActivity());
System.err.println(cd.getThrowableData().toString("// "));
} catch (IOException e) {
System.err.println("// BAD STACK CRAWL");
}
}
if (!mIgnoreCrashes) {
synchronized (Monkey.this) {
mAbort = true;
}
return !mKillProcessAfterError;
}
return false;
}
public int appNotResponding(String processName, int pid, String processStats) {
System.err.println("// NOT RESPONDING: " + processName + " (pid " + pid + ")");
System.err.println(processStats);
reportProcRank();
synchronized (Monkey.this) {
mRequestAnrTraces = true;
mRequestDumpsysMemInfo = true;
}
if (!mIgnoreTimeouts) {
synchronized (Monkey.this) {
mAbort = true;
}
return (mKillProcessAfterError) ? -1 : 1;
}
return 1;
}
}
/**
* Run the procrank tool to insert system status information into the debug
* report.
*/
private void reportProcRank() {
commandLineReport("procrank", "procrank");
}
/**
* Run "cat /data/anr/traces.txt". Wait about 5 seconds first, to let the
* asynchronous report writing complete.
*/
private void reportAnrTraces() {
try {
Thread.sleep(5 * 1000);
} catch (InterruptedException e) {
}
commandLineReport("anr traces", "cat /data/anr/traces.txt");
}
/**
* Run "dumpsys meminfo"
* <p>
* NOTE: You cannot perform a dumpsys call from the ActivityController
* callback, as it will deadlock. This should only be called from the main
* loop of the monkey.
*/
private void reportDumpsysMemInfo() {
commandLineReport("meminfo", "dumpsys meminfo");
}
/**
* Print report from a single command line.
* <p>
* TODO: Use ProcessBuilder & redirectErrorStream(true) to capture both
* streams (might be important for some command lines)
*
* @param reportName Simple tag that will print before the report and in
* various annotations.
* @param command Command line to execute.
*/
private void commandLineReport(String reportName, String command) {
System.err.println(reportName + ":");
Runtime rt = Runtime.getRuntime();
try {
// Process must be fully qualified here because android.os.Process
// is used elsewhere
java.lang.Process p = Runtime.getRuntime().exec(command);
// pipe everything from process stdout -> System.err
InputStream inStream = p.getInputStream();
InputStreamReader inReader = new InputStreamReader(inStream);
BufferedReader inBuffer = new BufferedReader(inReader);
String s;
while ((s = inBuffer.readLine()) != null) {
System.err.println(s);
}
int status = p.waitFor();
System.err.println("// " + reportName + " status was " + status);
} catch (Exception e) {
System.err.println("// Exception from " + reportName + ":");
System.err.println(e.toString());
}
}
/**
* Command-line entry point.
*
* @param args The command-line arguments
*/
public static void main(String[] args) {
int resultCode = (new Monkey()).run(args);
System.exit(resultCode);
}
/**
* Run the command!
*
* @param args The command-line arguments
* @return Returns a posix-style result code. 0 for no error.
*/
private int run(String[] args) {
// Super-early debugger wait
for (String s : args) {
if ("--wait-dbg".equals(s)) {
Debug.waitForDebugger();
}
}
// Default values for some command-line options
mVerbose = 0;
mCount = 1000;
mSeed = 0;
mThrottle = 0;
// prepare for command-line processing
mArgs = args;
mNextArg = 0;
// set a positive value, indicating none of the factors is provided yet
for (int i = 0; i < MonkeySourceRandom.FACTORZ_COUNT; i++) {
mFactors[i] = 1.0f;
}
if (!processOptions()) {
return -1;
}
// now set up additional data in preparation for launch
if (mMainCategories.size() == 0) {
mMainCategories.add(Intent.CATEGORY_LAUNCHER);
mMainCategories.add(Intent.CATEGORY_MONKEY);
}
if (mVerbose > 0) {
System.out.println(":Monkey: seed=" + mSeed + " count=" + mCount);
if (mValidPackages.size() > 0) {
Iterator<String> it = mValidPackages.iterator();
while (it.hasNext()) {
System.out.println(":AllowPackage: " + it.next());
}
}
if (mMainCategories.size() != 0) {
Iterator<String> it = mMainCategories.iterator();
while (it.hasNext()) {
System.out.println(":IncludeCategory: " + it.next());
}
}
}
if (!checkInternalConfiguration()) {
return -2;
}
if (!getSystemInterfaces()) {
return -3;
}
if (!getMainApps()) {
return -4;
}
if (mScriptFileNames != null && mScriptFileNames.size() == 1) {
// script mode, ignore other options
mEventSource = new MonkeySourceScript(mScriptFileNames.get(0), mThrottle);
mEventSource.setVerbose(mVerbose);
mCountEvents = false;
- } else if (mScriptFileNames != null) {
+ } else if (mScriptFileNames != null && mScriptFileNames.size() > 1) {
if (mSetupFileName != null) {
mEventSource = new MonkeySourceRandomScript(mSetupFileName, mScriptFileNames,
mThrottle, mSeed);
mCount++;
} else {
mEventSource = new MonkeySourceRandomScript(mScriptFileNames, mThrottle, mSeed);
}
mEventSource.setVerbose(mVerbose);
mCountEvents = false;
} else if (mServerPort != -1) {
try {
mEventSource = new MonkeySourceNetwork(mServerPort);
} catch (IOException e) {
System.out.println("Error binding to network socket.");
return -5;
}
mCount = Integer.MAX_VALUE;
} else {
// random source by default
if (mVerbose >= 2) { // check seeding performance
System.out.println("// Seeded: " + mSeed);
}
mEventSource = new MonkeySourceRandom(mSeed, mMainApps, mThrottle);
mEventSource.setVerbose(mVerbose);
// set any of the factors that has been set
for (int i = 0; i < MonkeySourceRandom.FACTORZ_COUNT; i++) {
if (mFactors[i] <= 0.0f) {
((MonkeySourceRandom) mEventSource).setFactors(i, mFactors[i]);
}
}
// in random mode, we start with a random activity
((MonkeySourceRandom) mEventSource).generateActivity();
}
// validate source generator
if (!mEventSource.validate()) {
return -5;
}
// If we're profiling, do it immediately before/after the main monkey
// loop
if (mGenerateHprof) {
signalPersistentProcesses();
}
mNetworkMonitor.start();
int crashedAtCycle = runMonkeyCycles();
mNetworkMonitor.stop();
synchronized (this) {
if (mRequestAnrTraces) {
reportAnrTraces();
mRequestAnrTraces = false;
}
if (mRequestDumpsysMemInfo) {
reportDumpsysMemInfo();
mRequestDumpsysMemInfo = false;
}
}
if (mGenerateHprof) {
signalPersistentProcesses();
if (mVerbose > 0) {
System.out.println("// Generated profiling reports in /data/misc");
}
}
try {
mAm.setActivityController(null);
mNetworkMonitor.unregister(mAm);
} catch (RemoteException e) {
// just in case this was latent (after mCount cycles), make sure
// we report it
if (crashedAtCycle >= mCount) {
crashedAtCycle = mCount - 1;
}
}
// report dropped event stats
if (mVerbose > 0) {
System.out.print(":Dropped: keys=");
System.out.print(mDroppedKeyEvents);
System.out.print(" pointers=");
System.out.print(mDroppedPointerEvents);
System.out.print(" trackballs=");
System.out.print(mDroppedTrackballEvents);
System.out.print(" flips=");
System.out.println(mDroppedFlipEvents);
}
// report network stats
mNetworkMonitor.dump();
if (crashedAtCycle < mCount - 1) {
System.err.println("** System appears to have crashed at event " + crashedAtCycle
+ " of " + mCount + " using seed " + mSeed);
return crashedAtCycle;
} else {
if (mVerbose > 0) {
System.out.println("// Monkey finished");
}
return 0;
}
}
/**
* Process the command-line options
*
* @return Returns true if options were parsed with no apparent errors.
*/
private boolean processOptions() {
// quick (throwaway) check for unadorned command
if (mArgs.length < 1) {
showUsage();
return false;
}
try {
String opt;
while ((opt = nextOption()) != null) {
if (opt.equals("-s")) {
mSeed = nextOptionLong("Seed");
} else if (opt.equals("-p")) {
mValidPackages.add(nextOptionData());
} else if (opt.equals("-c")) {
mMainCategories.add(nextOptionData());
} else if (opt.equals("-v")) {
mVerbose += 1;
} else if (opt.equals("--ignore-crashes")) {
mIgnoreCrashes = true;
} else if (opt.equals("--ignore-timeouts")) {
mIgnoreTimeouts = true;
} else if (opt.equals("--ignore-security-exceptions")) {
mIgnoreSecurityExceptions = true;
} else if (opt.equals("--monitor-native-crashes")) {
mMonitorNativeCrashes = true;
} else if (opt.equals("--kill-process-after-error")) {
mKillProcessAfterError = true;
} else if (opt.equals("--hprof")) {
mGenerateHprof = true;
} else if (opt.equals("--pct-touch")) {
int i = MonkeySourceRandom.FACTOR_TOUCH;
mFactors[i] = -nextOptionLong("touch events percentage");
} else if (opt.equals("--pct-motion")) {
int i = MonkeySourceRandom.FACTOR_MOTION;
mFactors[i] = -nextOptionLong("motion events percentage");
} else if (opt.equals("--pct-trackball")) {
int i = MonkeySourceRandom.FACTOR_TRACKBALL;
mFactors[i] = -nextOptionLong("trackball events percentage");
} else if (opt.equals("--pct-nav")) {
int i = MonkeySourceRandom.FACTOR_NAV;
mFactors[i] = -nextOptionLong("nav events percentage");
} else if (opt.equals("--pct-majornav")) {
int i = MonkeySourceRandom.FACTOR_MAJORNAV;
mFactors[i] = -nextOptionLong("major nav events percentage");
} else if (opt.equals("--pct-appswitch")) {
int i = MonkeySourceRandom.FACTOR_APPSWITCH;
mFactors[i] = -nextOptionLong("app switch events percentage");
} else if (opt.equals("--pct-flip")) {
int i = MonkeySourceRandom.FACTOR_FLIP;
mFactors[i] = -nextOptionLong("keyboard flip percentage");
} else if (opt.equals("--pct-anyevent")) {
int i = MonkeySourceRandom.FACTOR_ANYTHING;
mFactors[i] = -nextOptionLong("any events percentage");
} else if (opt.equals("--throttle")) {
mThrottle = nextOptionLong("delay (in milliseconds) to wait between events");
} else if (opt.equals("--wait-dbg")) {
// do nothing - it's caught at the very start of run()
} else if (opt.equals("--dbg-no-events")) {
mSendNoEvents = true;
} else if (opt.equals("--port")) {
mServerPort = (int) nextOptionLong("Server port to listen on for commands");
} else if (opt.equals("--setup")) {
mSetupFileName = nextOptionData();
} else if (opt.equals("-f")) {
mScriptFileNames.add(nextOptionData());
} else if (opt.equals("-h")) {
showUsage();
return false;
} else {
System.err.println("** Error: Unknown option: " + opt);
showUsage();
return false;
}
}
} catch (RuntimeException ex) {
System.err.println("** Error: " + ex.toString());
showUsage();
return false;
}
// If a server port hasn't been specified, we need to specify
// a count
if (mServerPort == -1) {
String countStr = nextArg();
if (countStr == null) {
System.err.println("** Error: Count not specified");
showUsage();
return false;
}
try {
mCount = Integer.parseInt(countStr);
} catch (NumberFormatException e) {
System.err.println("** Error: Count is not a number");
showUsage();
return false;
}
}
return true;
}
/**
* Check for any internal configuration (primarily build-time) errors.
*
* @return Returns true if ready to rock.
*/
private boolean checkInternalConfiguration() {
// Check KEYCODE name array, make sure it's up to date.
String lastKeyName = null;
try {
lastKeyName = MonkeySourceRandom.getLastKeyName();
} catch (RuntimeException e) {
}
if (!"TAG_LAST_KEYCODE".equals(lastKeyName)) {
System.err.println("** Error: Key names array malformed (internal error).");
return false;
}
return true;
}
/**
* Attach to the required system interfaces.
*
* @return Returns true if all system interfaces were available.
*/
private boolean getSystemInterfaces() {
mAm = ActivityManagerNative.getDefault();
if (mAm == null) {
System.err.println("** Error: Unable to connect to activity manager; is the system "
+ "running?");
return false;
}
mWm = IWindowManager.Stub.asInterface(ServiceManager.getService("window"));
if (mWm == null) {
System.err.println("** Error: Unable to connect to window manager; is the system "
+ "running?");
return false;
}
mPm = IPackageManager.Stub.asInterface(ServiceManager.getService("package"));
if (mPm == null) {
System.err.println("** Error: Unable to connect to package manager; is the system "
+ "running?");
return false;
}
try {
mAm.setActivityController(new ActivityController());
mNetworkMonitor.register(mAm);
} catch (RemoteException e) {
System.err.println("** Failed talking with activity manager!");
return false;
}
return true;
}
/**
* Using the restrictions provided (categories & packages), generate a list
* of activities that we can actually switch to.
*
* @return Returns true if it could successfully build a list of target
* activities
*/
private boolean getMainApps() {
try {
final int N = mMainCategories.size();
for (int i = 0; i < N; i++) {
Intent intent = new Intent(Intent.ACTION_MAIN);
String category = mMainCategories.get(i);
if (category.length() > 0) {
intent.addCategory(category);
}
List<ResolveInfo> mainApps = mPm.queryIntentActivities(intent, null, 0);
if (mainApps == null || mainApps.size() == 0) {
System.err.println("// Warning: no activities found for category " + category);
continue;
}
if (mVerbose >= 2) { // very verbose
System.out.println("// Selecting main activities from category " + category);
}
final int NA = mainApps.size();
for (int a = 0; a < NA; a++) {
ResolveInfo r = mainApps.get(a);
if (mValidPackages.size() == 0
|| mValidPackages.contains(r.activityInfo.applicationInfo.packageName)) {
if (mVerbose >= 2) { // very verbose
System.out.println("// + Using main activity " + r.activityInfo.name
+ " (from package "
+ r.activityInfo.applicationInfo.packageName + ")");
}
mMainApps.add(new ComponentName(r.activityInfo.applicationInfo.packageName,
r.activityInfo.name));
} else {
if (mVerbose >= 3) { // very very verbose
System.out.println("// - NOT USING main activity "
+ r.activityInfo.name + " (from package "
+ r.activityInfo.applicationInfo.packageName + ")");
}
}
}
}
} catch (RemoteException e) {
System.err.println("** Failed talking with package manager!");
return false;
}
if (mMainApps.size() == 0) {
System.out.println("** No activities found to run, monkey aborted.");
return false;
}
return true;
}
/**
* Run mCount cycles and see if we hit any crashers.
* <p>
* TODO: Meta state on keys
*
* @return Returns the last cycle which executed. If the value == mCount, no
* errors detected.
*/
private int runMonkeyCycles() {
int eventCounter = 0;
int cycleCounter = 0;
boolean systemCrashed = false;
while (!systemCrashed && cycleCounter < mCount) {
synchronized (this) {
if (mRequestAnrTraces) {
reportAnrTraces();
mRequestAnrTraces = false;
}
if (mRequestDumpsysMemInfo) {
reportDumpsysMemInfo();
mRequestDumpsysMemInfo = false;
}
if (mMonitorNativeCrashes) {
// first time through, when eventCounter == 0, just set up
// the watcher (ignore the error)
if (checkNativeCrashes() && (eventCounter > 0)) {
System.out.println("** New native crash detected.");
mAbort = mAbort || mKillProcessAfterError;
}
}
if (mAbort) {
System.out.println("** Monkey aborted due to error.");
System.out.println("Events injected: " + eventCounter);
return eventCounter;
}
}
// In this debugging mode, we never send any events. This is
// primarily here so you can manually test the package or category
// limits, while manually exercising the system.
if (mSendNoEvents) {
eventCounter++;
cycleCounter++;
continue;
}
if ((mVerbose > 0) && (eventCounter % 100) == 0 && eventCounter != 0) {
System.out.println(" // Sending event #" + eventCounter);
}
MonkeyEvent ev = mEventSource.getNextEvent();
if (ev != null) {
int injectCode = ev.injectEvent(mWm, mAm, mVerbose);
if (injectCode == MonkeyEvent.INJECT_FAIL) {
if (ev instanceof MonkeyKeyEvent) {
mDroppedKeyEvents++;
} else if (ev instanceof MonkeyMotionEvent) {
mDroppedPointerEvents++;
} else if (ev instanceof MonkeyFlipEvent) {
mDroppedFlipEvents++;
}
} else if (injectCode == MonkeyEvent.INJECT_ERROR_REMOTE_EXCEPTION) {
systemCrashed = true;
} else if (injectCode == MonkeyEvent.INJECT_ERROR_SECURITY_EXCEPTION) {
systemCrashed = !mIgnoreSecurityExceptions;
}
// Don't count throttling as an event.
if (!(ev instanceof MonkeyThrottleEvent)) {
eventCounter++;
if (mCountEvents) {
cycleCounter++;
}
}
} else {
if (!mCountEvents) {
cycleCounter++;
} else {
break;
}
}
}
// If we got this far, we succeeded!
return eventCounter;
}
/**
* Send SIGNAL_USR1 to all processes. This will generate large (5mb)
* profiling reports in data/misc, so use with care.
*/
private void signalPersistentProcesses() {
try {
mAm.signalPersistentProcesses(Process.SIGNAL_USR1);
synchronized (this) {
wait(2000);
}
} catch (RemoteException e) {
System.err.println("** Failed talking with activity manager!");
} catch (InterruptedException e) {
}
}
/**
* Watch for appearance of new tombstone files, which indicate native
* crashes.
*
* @return Returns true if new files have appeared in the list
*/
private boolean checkNativeCrashes() {
String[] tombstones = TOMBSTONES_PATH.list();
// shortcut path for usually empty directory, so we don't waste even
// more objects
if ((tombstones == null) || (tombstones.length == 0)) {
mTombstones = null;
return false;
}
// use set logic to look for new files
HashSet<String> newStones = new HashSet<String>();
for (String x : tombstones) {
newStones.add(x);
}
boolean result = (mTombstones == null) || !mTombstones.containsAll(newStones);
// keep the new list for the next time
mTombstones = newStones;
return result;
}
/**
* Return the next command line option. This has a number of special cases
* which closely, but not exactly, follow the POSIX command line options
* patterns:
*
* <pre>
* -- means to stop processing additional options
* -z means option z
* -z ARGS means option z with (non-optional) arguments ARGS
* -zARGS means option z with (optional) arguments ARGS
* --zz means option zz
* --zz ARGS means option zz with (non-optional) arguments ARGS
* </pre>
*
* Note that you cannot combine single letter options; -abc != -a -b -c
*
* @return Returns the option string, or null if there are no more options.
*/
private String nextOption() {
if (mNextArg >= mArgs.length) {
return null;
}
String arg = mArgs[mNextArg];
if (!arg.startsWith("-")) {
return null;
}
mNextArg++;
if (arg.equals("--")) {
return null;
}
if (arg.length() > 1 && arg.charAt(1) != '-') {
if (arg.length() > 2) {
mCurArgData = arg.substring(2);
return arg.substring(0, 2);
} else {
mCurArgData = null;
return arg;
}
}
mCurArgData = null;
return arg;
}
/**
* Return the next data associated with the current option.
*
* @return Returns the data string, or null of there are no more arguments.
*/
private String nextOptionData() {
if (mCurArgData != null) {
return mCurArgData;
}
if (mNextArg >= mArgs.length) {
return null;
}
String data = mArgs[mNextArg];
mNextArg++;
return data;
}
/**
* Returns a long converted from the next data argument, with error handling
* if not available.
*
* @param opt The name of the option.
* @return Returns a long converted from the argument.
*/
private long nextOptionLong(final String opt) {
long result;
try {
result = Long.parseLong(nextOptionData());
} catch (NumberFormatException e) {
System.err.println("** Error: " + opt + " is not a number");
throw e;
}
return result;
}
/**
* Return the next argument on the command line.
*
* @return Returns the argument string, or null if we have reached the end.
*/
private String nextArg() {
if (mNextArg >= mArgs.length) {
return null;
}
String arg = mArgs[mNextArg];
mNextArg++;
return arg;
}
/**
* Print how to use this command.
*/
private void showUsage() {
StringBuffer usage = new StringBuffer();
usage.append("usage: monkey [-p ALLOWED_PACKAGE [-p ALLOWED_PACKAGE] ...]\n");
usage.append(" [-c MAIN_CATEGORY [-c MAIN_CATEGORY] ...]\n");
usage.append(" [--ignore-crashes] [--ignore-timeouts]\n");
usage.append(" [--ignore-security-exceptions] [--monitor-native-crashes]\n");
usage.append(" [--kill-process-after-error] [--hprof]\n");
usage.append(" [--pct-touch PERCENT] [--pct-motion PERCENT]\n");
usage.append(" [--pct-trackball PERCENT] [--pct-syskeys PERCENT]\n");
usage.append(" [--pct-nav PERCENT] [--pct-majornav PERCENT]\n");
usage.append(" [--pct-appswitch PERCENT] [--pct-flip PERCENT]\n");
usage.append(" [--pct-anyevent PERCENT]\n");
usage.append(" [--wait-dbg] [--dbg-no-events]\n");
usage.append(" [--setup scriptfile] [-f scriptfile [-f scriptfile] ...]\n");
usage.append(" [--port port]\n");
usage.append(" [-s SEED] [-v [-v] ...] [--throttle MILLISEC]\n");
usage.append(" COUNT");
System.err.println(usage.toString());
}
}
| true | true | private int run(String[] args) {
// Super-early debugger wait
for (String s : args) {
if ("--wait-dbg".equals(s)) {
Debug.waitForDebugger();
}
}
// Default values for some command-line options
mVerbose = 0;
mCount = 1000;
mSeed = 0;
mThrottle = 0;
// prepare for command-line processing
mArgs = args;
mNextArg = 0;
// set a positive value, indicating none of the factors is provided yet
for (int i = 0; i < MonkeySourceRandom.FACTORZ_COUNT; i++) {
mFactors[i] = 1.0f;
}
if (!processOptions()) {
return -1;
}
// now set up additional data in preparation for launch
if (mMainCategories.size() == 0) {
mMainCategories.add(Intent.CATEGORY_LAUNCHER);
mMainCategories.add(Intent.CATEGORY_MONKEY);
}
if (mVerbose > 0) {
System.out.println(":Monkey: seed=" + mSeed + " count=" + mCount);
if (mValidPackages.size() > 0) {
Iterator<String> it = mValidPackages.iterator();
while (it.hasNext()) {
System.out.println(":AllowPackage: " + it.next());
}
}
if (mMainCategories.size() != 0) {
Iterator<String> it = mMainCategories.iterator();
while (it.hasNext()) {
System.out.println(":IncludeCategory: " + it.next());
}
}
}
if (!checkInternalConfiguration()) {
return -2;
}
if (!getSystemInterfaces()) {
return -3;
}
if (!getMainApps()) {
return -4;
}
if (mScriptFileNames != null && mScriptFileNames.size() == 1) {
// script mode, ignore other options
mEventSource = new MonkeySourceScript(mScriptFileNames.get(0), mThrottle);
mEventSource.setVerbose(mVerbose);
mCountEvents = false;
} else if (mScriptFileNames != null) {
if (mSetupFileName != null) {
mEventSource = new MonkeySourceRandomScript(mSetupFileName, mScriptFileNames,
mThrottle, mSeed);
mCount++;
} else {
mEventSource = new MonkeySourceRandomScript(mScriptFileNames, mThrottle, mSeed);
}
mEventSource.setVerbose(mVerbose);
mCountEvents = false;
} else if (mServerPort != -1) {
try {
mEventSource = new MonkeySourceNetwork(mServerPort);
} catch (IOException e) {
System.out.println("Error binding to network socket.");
return -5;
}
mCount = Integer.MAX_VALUE;
} else {
// random source by default
if (mVerbose >= 2) { // check seeding performance
System.out.println("// Seeded: " + mSeed);
}
mEventSource = new MonkeySourceRandom(mSeed, mMainApps, mThrottle);
mEventSource.setVerbose(mVerbose);
// set any of the factors that has been set
for (int i = 0; i < MonkeySourceRandom.FACTORZ_COUNT; i++) {
if (mFactors[i] <= 0.0f) {
((MonkeySourceRandom) mEventSource).setFactors(i, mFactors[i]);
}
}
// in random mode, we start with a random activity
((MonkeySourceRandom) mEventSource).generateActivity();
}
// validate source generator
if (!mEventSource.validate()) {
return -5;
}
// If we're profiling, do it immediately before/after the main monkey
// loop
if (mGenerateHprof) {
signalPersistentProcesses();
}
mNetworkMonitor.start();
int crashedAtCycle = runMonkeyCycles();
mNetworkMonitor.stop();
synchronized (this) {
if (mRequestAnrTraces) {
reportAnrTraces();
mRequestAnrTraces = false;
}
if (mRequestDumpsysMemInfo) {
reportDumpsysMemInfo();
mRequestDumpsysMemInfo = false;
}
}
if (mGenerateHprof) {
signalPersistentProcesses();
if (mVerbose > 0) {
System.out.println("// Generated profiling reports in /data/misc");
}
}
try {
mAm.setActivityController(null);
mNetworkMonitor.unregister(mAm);
} catch (RemoteException e) {
// just in case this was latent (after mCount cycles), make sure
// we report it
if (crashedAtCycle >= mCount) {
crashedAtCycle = mCount - 1;
}
}
// report dropped event stats
if (mVerbose > 0) {
System.out.print(":Dropped: keys=");
System.out.print(mDroppedKeyEvents);
System.out.print(" pointers=");
System.out.print(mDroppedPointerEvents);
System.out.print(" trackballs=");
System.out.print(mDroppedTrackballEvents);
System.out.print(" flips=");
System.out.println(mDroppedFlipEvents);
}
// report network stats
mNetworkMonitor.dump();
if (crashedAtCycle < mCount - 1) {
System.err.println("** System appears to have crashed at event " + crashedAtCycle
+ " of " + mCount + " using seed " + mSeed);
return crashedAtCycle;
} else {
if (mVerbose > 0) {
System.out.println("// Monkey finished");
}
return 0;
}
}
| private int run(String[] args) {
// Super-early debugger wait
for (String s : args) {
if ("--wait-dbg".equals(s)) {
Debug.waitForDebugger();
}
}
// Default values for some command-line options
mVerbose = 0;
mCount = 1000;
mSeed = 0;
mThrottle = 0;
// prepare for command-line processing
mArgs = args;
mNextArg = 0;
// set a positive value, indicating none of the factors is provided yet
for (int i = 0; i < MonkeySourceRandom.FACTORZ_COUNT; i++) {
mFactors[i] = 1.0f;
}
if (!processOptions()) {
return -1;
}
// now set up additional data in preparation for launch
if (mMainCategories.size() == 0) {
mMainCategories.add(Intent.CATEGORY_LAUNCHER);
mMainCategories.add(Intent.CATEGORY_MONKEY);
}
if (mVerbose > 0) {
System.out.println(":Monkey: seed=" + mSeed + " count=" + mCount);
if (mValidPackages.size() > 0) {
Iterator<String> it = mValidPackages.iterator();
while (it.hasNext()) {
System.out.println(":AllowPackage: " + it.next());
}
}
if (mMainCategories.size() != 0) {
Iterator<String> it = mMainCategories.iterator();
while (it.hasNext()) {
System.out.println(":IncludeCategory: " + it.next());
}
}
}
if (!checkInternalConfiguration()) {
return -2;
}
if (!getSystemInterfaces()) {
return -3;
}
if (!getMainApps()) {
return -4;
}
if (mScriptFileNames != null && mScriptFileNames.size() == 1) {
// script mode, ignore other options
mEventSource = new MonkeySourceScript(mScriptFileNames.get(0), mThrottle);
mEventSource.setVerbose(mVerbose);
mCountEvents = false;
} else if (mScriptFileNames != null && mScriptFileNames.size() > 1) {
if (mSetupFileName != null) {
mEventSource = new MonkeySourceRandomScript(mSetupFileName, mScriptFileNames,
mThrottle, mSeed);
mCount++;
} else {
mEventSource = new MonkeySourceRandomScript(mScriptFileNames, mThrottle, mSeed);
}
mEventSource.setVerbose(mVerbose);
mCountEvents = false;
} else if (mServerPort != -1) {
try {
mEventSource = new MonkeySourceNetwork(mServerPort);
} catch (IOException e) {
System.out.println("Error binding to network socket.");
return -5;
}
mCount = Integer.MAX_VALUE;
} else {
// random source by default
if (mVerbose >= 2) { // check seeding performance
System.out.println("// Seeded: " + mSeed);
}
mEventSource = new MonkeySourceRandom(mSeed, mMainApps, mThrottle);
mEventSource.setVerbose(mVerbose);
// set any of the factors that has been set
for (int i = 0; i < MonkeySourceRandom.FACTORZ_COUNT; i++) {
if (mFactors[i] <= 0.0f) {
((MonkeySourceRandom) mEventSource).setFactors(i, mFactors[i]);
}
}
// in random mode, we start with a random activity
((MonkeySourceRandom) mEventSource).generateActivity();
}
// validate source generator
if (!mEventSource.validate()) {
return -5;
}
// If we're profiling, do it immediately before/after the main monkey
// loop
if (mGenerateHprof) {
signalPersistentProcesses();
}
mNetworkMonitor.start();
int crashedAtCycle = runMonkeyCycles();
mNetworkMonitor.stop();
synchronized (this) {
if (mRequestAnrTraces) {
reportAnrTraces();
mRequestAnrTraces = false;
}
if (mRequestDumpsysMemInfo) {
reportDumpsysMemInfo();
mRequestDumpsysMemInfo = false;
}
}
if (mGenerateHprof) {
signalPersistentProcesses();
if (mVerbose > 0) {
System.out.println("// Generated profiling reports in /data/misc");
}
}
try {
mAm.setActivityController(null);
mNetworkMonitor.unregister(mAm);
} catch (RemoteException e) {
// just in case this was latent (after mCount cycles), make sure
// we report it
if (crashedAtCycle >= mCount) {
crashedAtCycle = mCount - 1;
}
}
// report dropped event stats
if (mVerbose > 0) {
System.out.print(":Dropped: keys=");
System.out.print(mDroppedKeyEvents);
System.out.print(" pointers=");
System.out.print(mDroppedPointerEvents);
System.out.print(" trackballs=");
System.out.print(mDroppedTrackballEvents);
System.out.print(" flips=");
System.out.println(mDroppedFlipEvents);
}
// report network stats
mNetworkMonitor.dump();
if (crashedAtCycle < mCount - 1) {
System.err.println("** System appears to have crashed at event " + crashedAtCycle
+ " of " + mCount + " using seed " + mSeed);
return crashedAtCycle;
} else {
if (mVerbose > 0) {
System.out.println("// Monkey finished");
}
return 0;
}
}
|
diff --git a/src/net/grinder/TCPProxy.java b/src/net/grinder/TCPProxy.java
index f88d1cf5..90b0867e 100755
--- a/src/net/grinder/TCPProxy.java
+++ b/src/net/grinder/TCPProxy.java
@@ -1,550 +1,550 @@
// Copyright (C) 2000 Phil Dawes
// Copyright (C) 2000, 2001, 2002, 2003 Philip Aston
// Copyright (C) 2001 Paddy Spencer
// Copyright (C) 2003 Bertrand Ave
// All rights reserved.
//
// This file is part of The Grinder software distribution. Refer to
// the file LICENSE which is part of The Grinder distribution for
// licensing details. The Grinder distribution is available on the
// Internet at http://grinder.sourceforge.net/
//
// 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
// REGENTS 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 net.grinder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import net.grinder.plugin.http.HTTPPluginTCPProxyFilter;
import net.grinder.plugin.http.HTTPPluginTCPProxyResponseFilter;
import net.grinder.tools.tcpproxy.CompositeTCPProxyFilter;
import net.grinder.tools.tcpproxy.ConnectionDetails;
import net.grinder.tools.tcpproxy.EchoFilter;
import net.grinder.tools.tcpproxy.EndPoint;
import net.grinder.tools.tcpproxy.HTTPProxyTCPProxyEngine;
import net.grinder.tools.tcpproxy.NullFilter;
import net.grinder.tools.tcpproxy.PortForwarderTCPProxyEngine;
import net.grinder.tools.tcpproxy.TCPProxyConsole;
import net.grinder.tools.tcpproxy.TCPProxyEngine;
import net.grinder.tools.tcpproxy.TCPProxyFilter;
import net.grinder.tools.tcpproxy.TCPProxySSLSocketFactory;
/**
* This is the entry point of The TCPProxy process.
*
* @author Phil Dawes
* @author Philip Aston
* @author Bertrand Ave
* @version $Revision$
*/
public final class TCPProxy {
private static final String SSL_SOCKET_FACTORY_CLASS =
"net.grinder.tools.tcpproxy.TCPProxySSLSocketFactoryImplementation";
/**
* Entry point.
*
* @param args Command line arguments.
*/
public static void main(String[] args) {
final TCPProxy tcpProxy = new TCPProxy(args);
tcpProxy.run();
}
private Error barfUsage() {
System.err.println(
"\n" +
"Usage: " +
"\n java " + TCPProxy.class + " <options>" +
"\n" +
"\n Commonly used options:" +
"\n [-requestfilter <filter>] Add a request filter" +
"\n [-responsefilter <filter>] Add a response filter" +
"\n [-httpplugin] See below" +
"\n [-properties <file>] Properties passed to the filters" +
"\n [-localhost <host name/ip>] Default is localhost" +
"\n [-localport <port>] Default is 8001" +
"\n [-ssl Use SSL" +
"\n [-keystore <file>] Key store details for" +
"\n [-keystorepassword <pass>] certificates." +
"\n [-keystoretype <type>] Default is JSSE dependent." +
"\n ]" +
"\n" +
"\n Other options:" +
"\n [-remotehost <host name>] Default is localhost" +
"\n [-remoteport <port>] Default is 7001" +
"\n [-timeout <seconds>] Proxy engine timeout" +
"\n [-colour] Be pretty on ANSI terminals" +
"\n [-console] Display the console" +
"\n [-httpproxy <host> <port>] Route via HTTP/HTTPS proxy" +
"\n [-httpsproxy <host> <port>] Override -httpproxy settings for" +
"\n HTTPS" +
"\n" +
"\n <filter> can be the name of a class that implements" +
"\n " + TCPProxyFilter.class.getName() + " or" +
"\n one of NONE, ECHO. Default is ECHO." +
"\n Multiple filters can be specified for each stream." +
"\n" +
"\n If neither -remotehost nor -remoteport is specified," +
"\n the TCPProxy listens as an HTTP Proxy on <localhost:localport>." +
"\n Specify -ssl for HTTPS proxy support." +
"\n" +
"\n If either -remotehost or -remoteport is specified," +
"\n the TCPProxy acts a simple port forwarder between" +
"\n <localhost:localport> and <remotehost:remoteport>." +
"\n Specify -ssl for SSL support." +
"\n" +
"\n -httpPlugin sets the request and response filters" +
"\n to produce a test script suitable for use with the" +
"\n HTTP plugin." +
"\n" +
"\n -timeout is how long the TCPProxy will wait for a request before" +
"\n timing out and freeing the local port. The TCPProxy will not time" +
"\n out if there are active connections." +
"\n" +
"\n -console displays a simple console that allows the TCPProxy" +
"\n to be shutdown cleanly." +
"\n" +
"\n -httpproxy and -httpsproxy allow output to be directed through" +
"\n another HTTP/HTTPS proxy; this may help you reach the Internet." +
"\n These options are not supported in port forwarding mode." +
"\n"
);
System.exit(1);
return null;
}
private Error barfUsage(String s) {
System.err.println("\n" + "Error: " + s);
throw barfUsage();
}
private TCPProxyEngine m_proxyEngine = null;
private TCPProxy(String[] args) {
final PrintWriter outputWriter = new PrintWriter(System.out);
// Default values.
TCPProxyFilter requestFilter = new EchoFilter(outputWriter);
TCPProxyFilter responseFilter = new EchoFilter(outputWriter);
int localPort = 8001;
String remoteHost = "localhost";
String localHost = "localhost";
int remotePort = 7001;
boolean useSSL = false;
File keyStoreFile = null;
char[] keyStorePassword = null;
String keyStoreType = null;
boolean isHTTPProxy = true;
boolean console = false;
EndPoint chainedHTTPProxy = null;
EndPoint chainedHTTPSProxy = null;
int timeout = 0;
boolean useColour = false;
try {
// Parse 1.
for (int i = 0; i < args.length; i++) {
if (args[i].equalsIgnoreCase("-properties")) {
final Properties properties = new Properties();
properties.load(new FileInputStream(new File(args[++i])));
System.getProperties().putAll(properties);
}
else if (args[i].equalsIgnoreCase("-initialtest")) {
final String argument = i + 1 < args.length ? args[++i] : "123";
barfUsage("-initialTest is no longer supported.\n\n" +
"Use -DHTTPPlugin.initialTest=" + argument +
" or the -properties option instead.");
}
}
// Parse 2.
for (int i = 0; i < args.length; i++) {
if (args[i].equalsIgnoreCase("-requestfilter")) {
requestFilter =
addFilter(requestFilter,
instantiateFilter(args[++i], outputWriter));
}
else if (args[i].equalsIgnoreCase("-responsefilter")) {
responseFilter =
addFilter(responseFilter,
instantiateFilter(args[++i], outputWriter));
}
else if (args[i].equalsIgnoreCase("-httpplugin")) {
requestFilter =
addFilter(requestFilter,
new HTTPPluginTCPProxyFilter(outputWriter));
responseFilter =
addFilter(responseFilter,
new HTTPPluginTCPProxyResponseFilter(outputWriter));
}
else if (args[i].equalsIgnoreCase("-localhost")) {
localHost = args[++i];
}
else if (args[i].equalsIgnoreCase("-localport")) {
localPort = Integer.parseInt(args[++i]);
}
else if (args[i].equalsIgnoreCase("-remotehost")) {
remoteHost = args[++i];
isHTTPProxy = false;
}
else if (args[i].equalsIgnoreCase("-remoteport")) {
remotePort = Integer.parseInt(args[++i]);
isHTTPProxy = false;
}
else if (args[i].equalsIgnoreCase("-ssl")) {
useSSL = true;
}
else if (args[i].equalsIgnoreCase("-keystore")) {
keyStoreFile = new File(args[++i]);
}
else if (args[i].equalsIgnoreCase("-keystorepassword") ||
args[i].equalsIgnoreCase("-storepass")) {
keyStorePassword = args[++i].toCharArray();
}
else if (args[i].equalsIgnoreCase("-keystoretype") ||
args[i].equalsIgnoreCase("-storetype")) {
keyStoreType = args[++i];
}
else if (args[i].equalsIgnoreCase("-timeout")) {
timeout = Integer.parseInt(args[++i]) * 1000;
}
else if (args[i].equalsIgnoreCase("-output")) {
// -output is used by the TCPProxy web app only
// and is not publicised, users are expected to
// use shell redirection.
final String outputFile = args[++i];
System.setOut(new PrintStream(
new FileOutputStream(outputFile + ".out"), true));
System.setErr(new PrintStream(
new FileOutputStream(outputFile + ".err"), true));
}
else if (args[i].equalsIgnoreCase("-console")) {
console = true;
}
else if (args[i].equalsIgnoreCase("-colour") ||
args[i].equalsIgnoreCase("-color")) {
useColour = true;
}
else if (args[i].equalsIgnoreCase("-properties")) {
/* Already handled */
++i;
}
- else if (args[i].equalsIgnoreCase("-httproxy")) {
+ else if (args[i].equalsIgnoreCase("-httpproxy")) {
chainedHTTPProxy =
new EndPoint(args[++i], Integer.parseInt(args[++i]));
}
else if (args[i].equalsIgnoreCase("-httpsproxy")) {
chainedHTTPSProxy =
new EndPoint(args[++i], Integer.parseInt(args[++i]));
}
else {
throw barfUsage();
}
}
}
catch (Exception e) {
throw barfUsage();
}
if (timeout < 0) {
throw barfUsage("Timeout must be non-negative.");
}
final EndPoint localEndPoint = new EndPoint(localHost, localPort);
final EndPoint remoteEndPoint = new EndPoint(remoteHost, remotePort);
if (chainedHTTPSProxy == null && chainedHTTPProxy != null) {
chainedHTTPSProxy = chainedHTTPProxy;
}
if (chainedHTTPSProxy != null && !isHTTPProxy) {
barfUsage("Routing through a HTTP/HTTPS proxy is not supported " +
"\nin port forwarding mode.");
}
final StringBuffer startMessage = new StringBuffer();
startMessage.append("Initialising as ");
if (isHTTPProxy) {
if (useSSL) {
startMessage.append("an HTTP/HTTPS proxy");
}
else {
startMessage.append("an HTTP proxy");
}
}
else {
if (useSSL) {
startMessage.append("an SSL port forwarder");
}
else {
startMessage.append("a TCP port forwarder");
}
}
startMessage.append(" with the parameters:");
startMessage.append("\n Request filters: ");
appendFilterList(startMessage, requestFilter);
startMessage.append("\n Response filters: ");
appendFilterList(startMessage, responseFilter);
startMessage.append("\n Local host: " + localHost);
startMessage.append("\n Local port: " + localPort);
if (!isHTTPProxy) {
startMessage.append("\n Remote host: " + remoteHost +
"\n Remote port: " + remotePort);
}
if (chainedHTTPProxy != null) {
startMessage.append("\n HTTP proxy: " + chainedHTTPProxy);
}
if (useSSL) {
if (chainedHTTPSProxy != null) {
startMessage.append("\n HTTPS proxy: " + chainedHTTPSProxy);
}
startMessage.append("\n Key store: ");
startMessage.append(keyStoreFile != null ?
keyStoreFile.toString() : "NOT SET");
// Key store password is optional.
if (keyStorePassword != null) {
startMessage.append("\n Key store password: ");
for (int i = 0; i < keyStorePassword.length; ++i) {
startMessage.append('*');
}
}
// Key store type can be null => use whatever
// KeyStore.getDefaultType() says (we can't print the default
// here without loading the JSSE).
if (keyStoreType != null) {
startMessage.append("\n Key store type: " + keyStoreType);
}
}
System.err.println(startMessage);
try {
final TCPProxySSLSocketFactory sslSocketFactory;
if (useSSL) {
try {
// TCPProxySSLSocketFactoryImplementation depends on JSSE,
// load dynamically.
final Class socketFactoryClass =
Class.forName(SSL_SOCKET_FACTORY_CLASS);
final Constructor socketFactoryConstructor =
socketFactoryClass.getConstructor(
new Class[] { File.class, new char[0].getClass(), String.class,
});
sslSocketFactory = (TCPProxySSLSocketFactory)
socketFactoryConstructor.newInstance(
new Object[] { keyStoreFile, keyStorePassword, keyStoreType, });
}
catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
else {
sslSocketFactory = null;
}
if (isHTTPProxy) {
m_proxyEngine =
new HTTPProxyTCPProxyEngine(
sslSocketFactory,
requestFilter,
responseFilter,
outputWriter,
localEndPoint,
useColour,
timeout,
chainedHTTPProxy,
chainedHTTPSProxy);
}
else {
if (useSSL) {
m_proxyEngine =
new PortForwarderTCPProxyEngine(
sslSocketFactory,
requestFilter,
responseFilter,
outputWriter,
new ConnectionDetails(localEndPoint, remoteEndPoint, useSSL),
useColour,
timeout);
}
else {
m_proxyEngine =
new PortForwarderTCPProxyEngine(
requestFilter,
responseFilter,
outputWriter,
new ConnectionDetails(localEndPoint, remoteEndPoint, useSSL),
useColour,
timeout);
}
}
if (console) {
new TCPProxyConsole(m_proxyEngine);
}
System.err.println("Engine initialised, listening on port " + localPort);
}
catch (Throwable e) {
System.err.println("Could not initialise engine:");
e.printStackTrace();
System.exit(2);
}
}
private TCPProxyFilter instantiateFilter(
String filterClassName, PrintWriter outputWriter) throws Exception {
if (filterClassName.equals("NONE")) {
return new NullFilter(outputWriter);
}
else if (filterClassName.equals("ECHO")) {
return new EchoFilter(outputWriter);
}
final Class filterClass;
try {
filterClass = Class.forName(filterClassName);
}
catch (ClassNotFoundException e) {
throw barfUsage("Class '" + filterClassName + "' not found.");
}
if (!TCPProxyFilter.class.isAssignableFrom(filterClass)) {
throw barfUsage("The specified filter class ('" + filterClass.getName() +
"') does not implement the interface: '" +
TCPProxyFilter.class.getName() + "'.");
}
// Instantiate a filter.
try {
final Constructor constructor =
filterClass.getConstructor(new Class[] {PrintWriter.class});
return (TCPProxyFilter)constructor.newInstance(
new Object[] {outputWriter});
}
catch (NoSuchMethodException e) {
throw barfUsage(
"The class '" + filterClass.getName() +
"' does not have a constructor that takes a PrintWriter.");
}
catch (IllegalAccessException e) {
throw barfUsage("The constructor of class '" + filterClass.getName() +
"' is not public.");
}
catch (InstantiationException e) {
throw barfUsage("The class '" + filterClass.getName() +
"' is abstract.");
}
}
private TCPProxyFilter addFilter(TCPProxyFilter existingFilter,
TCPProxyFilter newFilter) {
if (existingFilter instanceof CompositeTCPProxyFilter) {
((CompositeTCPProxyFilter) existingFilter).add(newFilter);
return existingFilter;
}
else {
// Discard the default filter.
final CompositeTCPProxyFilter result = new CompositeTCPProxyFilter();
result.add(newFilter);
return result;
}
}
private void appendFilterList(StringBuffer buffer, TCPProxyFilter filter) {
final TCPProxyFilter[] filters =
(TCPProxyFilter[]) getFilterList(filter).toArray(new TCPProxyFilter[0]);
for (int i = 0; i < filters.length; ++i) {
if (i != 0) {
buffer.append(", ");
}
final String fullName = filters[i].getClass().getName();
final int lastDot = fullName.lastIndexOf(".");
final String shortName =
lastDot > 0 ? fullName.substring(lastDot + 1) : fullName;
buffer.append(shortName);
}
}
private List getFilterList(TCPProxyFilter filter) {
if (filter instanceof CompositeTCPProxyFilter) {
final List result = new ArrayList();
final Iterator iterator =
((CompositeTCPProxyFilter)filter).getFilters().iterator();
while (iterator.hasNext()) {
result.addAll(getFilterList((TCPProxyFilter) iterator.next()));
}
return result;
}
else {
return Collections.singletonList(filter);
}
}
private void run() {
Runtime.getRuntime().addShutdownHook(
new Thread() {
public void run() { m_proxyEngine.stop(); }
});
m_proxyEngine.run();
System.err.println("Engine exited");
System.exit(0);
}
}
| true | true | private TCPProxy(String[] args) {
final PrintWriter outputWriter = new PrintWriter(System.out);
// Default values.
TCPProxyFilter requestFilter = new EchoFilter(outputWriter);
TCPProxyFilter responseFilter = new EchoFilter(outputWriter);
int localPort = 8001;
String remoteHost = "localhost";
String localHost = "localhost";
int remotePort = 7001;
boolean useSSL = false;
File keyStoreFile = null;
char[] keyStorePassword = null;
String keyStoreType = null;
boolean isHTTPProxy = true;
boolean console = false;
EndPoint chainedHTTPProxy = null;
EndPoint chainedHTTPSProxy = null;
int timeout = 0;
boolean useColour = false;
try {
// Parse 1.
for (int i = 0; i < args.length; i++) {
if (args[i].equalsIgnoreCase("-properties")) {
final Properties properties = new Properties();
properties.load(new FileInputStream(new File(args[++i])));
System.getProperties().putAll(properties);
}
else if (args[i].equalsIgnoreCase("-initialtest")) {
final String argument = i + 1 < args.length ? args[++i] : "123";
barfUsage("-initialTest is no longer supported.\n\n" +
"Use -DHTTPPlugin.initialTest=" + argument +
" or the -properties option instead.");
}
}
// Parse 2.
for (int i = 0; i < args.length; i++) {
if (args[i].equalsIgnoreCase("-requestfilter")) {
requestFilter =
addFilter(requestFilter,
instantiateFilter(args[++i], outputWriter));
}
else if (args[i].equalsIgnoreCase("-responsefilter")) {
responseFilter =
addFilter(responseFilter,
instantiateFilter(args[++i], outputWriter));
}
else if (args[i].equalsIgnoreCase("-httpplugin")) {
requestFilter =
addFilter(requestFilter,
new HTTPPluginTCPProxyFilter(outputWriter));
responseFilter =
addFilter(responseFilter,
new HTTPPluginTCPProxyResponseFilter(outputWriter));
}
else if (args[i].equalsIgnoreCase("-localhost")) {
localHost = args[++i];
}
else if (args[i].equalsIgnoreCase("-localport")) {
localPort = Integer.parseInt(args[++i]);
}
else if (args[i].equalsIgnoreCase("-remotehost")) {
remoteHost = args[++i];
isHTTPProxy = false;
}
else if (args[i].equalsIgnoreCase("-remoteport")) {
remotePort = Integer.parseInt(args[++i]);
isHTTPProxy = false;
}
else if (args[i].equalsIgnoreCase("-ssl")) {
useSSL = true;
}
else if (args[i].equalsIgnoreCase("-keystore")) {
keyStoreFile = new File(args[++i]);
}
else if (args[i].equalsIgnoreCase("-keystorepassword") ||
args[i].equalsIgnoreCase("-storepass")) {
keyStorePassword = args[++i].toCharArray();
}
else if (args[i].equalsIgnoreCase("-keystoretype") ||
args[i].equalsIgnoreCase("-storetype")) {
keyStoreType = args[++i];
}
else if (args[i].equalsIgnoreCase("-timeout")) {
timeout = Integer.parseInt(args[++i]) * 1000;
}
else if (args[i].equalsIgnoreCase("-output")) {
// -output is used by the TCPProxy web app only
// and is not publicised, users are expected to
// use shell redirection.
final String outputFile = args[++i];
System.setOut(new PrintStream(
new FileOutputStream(outputFile + ".out"), true));
System.setErr(new PrintStream(
new FileOutputStream(outputFile + ".err"), true));
}
else if (args[i].equalsIgnoreCase("-console")) {
console = true;
}
else if (args[i].equalsIgnoreCase("-colour") ||
args[i].equalsIgnoreCase("-color")) {
useColour = true;
}
else if (args[i].equalsIgnoreCase("-properties")) {
/* Already handled */
++i;
}
else if (args[i].equalsIgnoreCase("-httproxy")) {
chainedHTTPProxy =
new EndPoint(args[++i], Integer.parseInt(args[++i]));
}
else if (args[i].equalsIgnoreCase("-httpsproxy")) {
chainedHTTPSProxy =
new EndPoint(args[++i], Integer.parseInt(args[++i]));
}
else {
throw barfUsage();
}
}
}
catch (Exception e) {
throw barfUsage();
}
if (timeout < 0) {
throw barfUsage("Timeout must be non-negative.");
}
final EndPoint localEndPoint = new EndPoint(localHost, localPort);
final EndPoint remoteEndPoint = new EndPoint(remoteHost, remotePort);
if (chainedHTTPSProxy == null && chainedHTTPProxy != null) {
chainedHTTPSProxy = chainedHTTPProxy;
}
if (chainedHTTPSProxy != null && !isHTTPProxy) {
barfUsage("Routing through a HTTP/HTTPS proxy is not supported " +
"\nin port forwarding mode.");
}
final StringBuffer startMessage = new StringBuffer();
startMessage.append("Initialising as ");
if (isHTTPProxy) {
if (useSSL) {
startMessage.append("an HTTP/HTTPS proxy");
}
else {
startMessage.append("an HTTP proxy");
}
}
else {
if (useSSL) {
startMessage.append("an SSL port forwarder");
}
else {
startMessage.append("a TCP port forwarder");
}
}
startMessage.append(" with the parameters:");
startMessage.append("\n Request filters: ");
appendFilterList(startMessage, requestFilter);
startMessage.append("\n Response filters: ");
appendFilterList(startMessage, responseFilter);
startMessage.append("\n Local host: " + localHost);
startMessage.append("\n Local port: " + localPort);
if (!isHTTPProxy) {
startMessage.append("\n Remote host: " + remoteHost +
"\n Remote port: " + remotePort);
}
if (chainedHTTPProxy != null) {
startMessage.append("\n HTTP proxy: " + chainedHTTPProxy);
}
if (useSSL) {
if (chainedHTTPSProxy != null) {
startMessage.append("\n HTTPS proxy: " + chainedHTTPSProxy);
}
startMessage.append("\n Key store: ");
startMessage.append(keyStoreFile != null ?
keyStoreFile.toString() : "NOT SET");
// Key store password is optional.
if (keyStorePassword != null) {
startMessage.append("\n Key store password: ");
for (int i = 0; i < keyStorePassword.length; ++i) {
startMessage.append('*');
}
}
// Key store type can be null => use whatever
// KeyStore.getDefaultType() says (we can't print the default
// here without loading the JSSE).
if (keyStoreType != null) {
startMessage.append("\n Key store type: " + keyStoreType);
}
}
System.err.println(startMessage);
try {
final TCPProxySSLSocketFactory sslSocketFactory;
if (useSSL) {
try {
// TCPProxySSLSocketFactoryImplementation depends on JSSE,
// load dynamically.
final Class socketFactoryClass =
Class.forName(SSL_SOCKET_FACTORY_CLASS);
final Constructor socketFactoryConstructor =
socketFactoryClass.getConstructor(
new Class[] { File.class, new char[0].getClass(), String.class,
});
sslSocketFactory = (TCPProxySSLSocketFactory)
socketFactoryConstructor.newInstance(
new Object[] { keyStoreFile, keyStorePassword, keyStoreType, });
}
catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
else {
sslSocketFactory = null;
}
if (isHTTPProxy) {
m_proxyEngine =
new HTTPProxyTCPProxyEngine(
sslSocketFactory,
requestFilter,
responseFilter,
outputWriter,
localEndPoint,
useColour,
timeout,
chainedHTTPProxy,
chainedHTTPSProxy);
}
else {
if (useSSL) {
m_proxyEngine =
new PortForwarderTCPProxyEngine(
sslSocketFactory,
requestFilter,
responseFilter,
outputWriter,
new ConnectionDetails(localEndPoint, remoteEndPoint, useSSL),
useColour,
timeout);
}
else {
m_proxyEngine =
new PortForwarderTCPProxyEngine(
requestFilter,
responseFilter,
outputWriter,
new ConnectionDetails(localEndPoint, remoteEndPoint, useSSL),
useColour,
timeout);
}
}
if (console) {
new TCPProxyConsole(m_proxyEngine);
}
System.err.println("Engine initialised, listening on port " + localPort);
}
catch (Throwable e) {
System.err.println("Could not initialise engine:");
e.printStackTrace();
System.exit(2);
}
}
| private TCPProxy(String[] args) {
final PrintWriter outputWriter = new PrintWriter(System.out);
// Default values.
TCPProxyFilter requestFilter = new EchoFilter(outputWriter);
TCPProxyFilter responseFilter = new EchoFilter(outputWriter);
int localPort = 8001;
String remoteHost = "localhost";
String localHost = "localhost";
int remotePort = 7001;
boolean useSSL = false;
File keyStoreFile = null;
char[] keyStorePassword = null;
String keyStoreType = null;
boolean isHTTPProxy = true;
boolean console = false;
EndPoint chainedHTTPProxy = null;
EndPoint chainedHTTPSProxy = null;
int timeout = 0;
boolean useColour = false;
try {
// Parse 1.
for (int i = 0; i < args.length; i++) {
if (args[i].equalsIgnoreCase("-properties")) {
final Properties properties = new Properties();
properties.load(new FileInputStream(new File(args[++i])));
System.getProperties().putAll(properties);
}
else if (args[i].equalsIgnoreCase("-initialtest")) {
final String argument = i + 1 < args.length ? args[++i] : "123";
barfUsage("-initialTest is no longer supported.\n\n" +
"Use -DHTTPPlugin.initialTest=" + argument +
" or the -properties option instead.");
}
}
// Parse 2.
for (int i = 0; i < args.length; i++) {
if (args[i].equalsIgnoreCase("-requestfilter")) {
requestFilter =
addFilter(requestFilter,
instantiateFilter(args[++i], outputWriter));
}
else if (args[i].equalsIgnoreCase("-responsefilter")) {
responseFilter =
addFilter(responseFilter,
instantiateFilter(args[++i], outputWriter));
}
else if (args[i].equalsIgnoreCase("-httpplugin")) {
requestFilter =
addFilter(requestFilter,
new HTTPPluginTCPProxyFilter(outputWriter));
responseFilter =
addFilter(responseFilter,
new HTTPPluginTCPProxyResponseFilter(outputWriter));
}
else if (args[i].equalsIgnoreCase("-localhost")) {
localHost = args[++i];
}
else if (args[i].equalsIgnoreCase("-localport")) {
localPort = Integer.parseInt(args[++i]);
}
else if (args[i].equalsIgnoreCase("-remotehost")) {
remoteHost = args[++i];
isHTTPProxy = false;
}
else if (args[i].equalsIgnoreCase("-remoteport")) {
remotePort = Integer.parseInt(args[++i]);
isHTTPProxy = false;
}
else if (args[i].equalsIgnoreCase("-ssl")) {
useSSL = true;
}
else if (args[i].equalsIgnoreCase("-keystore")) {
keyStoreFile = new File(args[++i]);
}
else if (args[i].equalsIgnoreCase("-keystorepassword") ||
args[i].equalsIgnoreCase("-storepass")) {
keyStorePassword = args[++i].toCharArray();
}
else if (args[i].equalsIgnoreCase("-keystoretype") ||
args[i].equalsIgnoreCase("-storetype")) {
keyStoreType = args[++i];
}
else if (args[i].equalsIgnoreCase("-timeout")) {
timeout = Integer.parseInt(args[++i]) * 1000;
}
else if (args[i].equalsIgnoreCase("-output")) {
// -output is used by the TCPProxy web app only
// and is not publicised, users are expected to
// use shell redirection.
final String outputFile = args[++i];
System.setOut(new PrintStream(
new FileOutputStream(outputFile + ".out"), true));
System.setErr(new PrintStream(
new FileOutputStream(outputFile + ".err"), true));
}
else if (args[i].equalsIgnoreCase("-console")) {
console = true;
}
else if (args[i].equalsIgnoreCase("-colour") ||
args[i].equalsIgnoreCase("-color")) {
useColour = true;
}
else if (args[i].equalsIgnoreCase("-properties")) {
/* Already handled */
++i;
}
else if (args[i].equalsIgnoreCase("-httpproxy")) {
chainedHTTPProxy =
new EndPoint(args[++i], Integer.parseInt(args[++i]));
}
else if (args[i].equalsIgnoreCase("-httpsproxy")) {
chainedHTTPSProxy =
new EndPoint(args[++i], Integer.parseInt(args[++i]));
}
else {
throw barfUsage();
}
}
}
catch (Exception e) {
throw barfUsage();
}
if (timeout < 0) {
throw barfUsage("Timeout must be non-negative.");
}
final EndPoint localEndPoint = new EndPoint(localHost, localPort);
final EndPoint remoteEndPoint = new EndPoint(remoteHost, remotePort);
if (chainedHTTPSProxy == null && chainedHTTPProxy != null) {
chainedHTTPSProxy = chainedHTTPProxy;
}
if (chainedHTTPSProxy != null && !isHTTPProxy) {
barfUsage("Routing through a HTTP/HTTPS proxy is not supported " +
"\nin port forwarding mode.");
}
final StringBuffer startMessage = new StringBuffer();
startMessage.append("Initialising as ");
if (isHTTPProxy) {
if (useSSL) {
startMessage.append("an HTTP/HTTPS proxy");
}
else {
startMessage.append("an HTTP proxy");
}
}
else {
if (useSSL) {
startMessage.append("an SSL port forwarder");
}
else {
startMessage.append("a TCP port forwarder");
}
}
startMessage.append(" with the parameters:");
startMessage.append("\n Request filters: ");
appendFilterList(startMessage, requestFilter);
startMessage.append("\n Response filters: ");
appendFilterList(startMessage, responseFilter);
startMessage.append("\n Local host: " + localHost);
startMessage.append("\n Local port: " + localPort);
if (!isHTTPProxy) {
startMessage.append("\n Remote host: " + remoteHost +
"\n Remote port: " + remotePort);
}
if (chainedHTTPProxy != null) {
startMessage.append("\n HTTP proxy: " + chainedHTTPProxy);
}
if (useSSL) {
if (chainedHTTPSProxy != null) {
startMessage.append("\n HTTPS proxy: " + chainedHTTPSProxy);
}
startMessage.append("\n Key store: ");
startMessage.append(keyStoreFile != null ?
keyStoreFile.toString() : "NOT SET");
// Key store password is optional.
if (keyStorePassword != null) {
startMessage.append("\n Key store password: ");
for (int i = 0; i < keyStorePassword.length; ++i) {
startMessage.append('*');
}
}
// Key store type can be null => use whatever
// KeyStore.getDefaultType() says (we can't print the default
// here without loading the JSSE).
if (keyStoreType != null) {
startMessage.append("\n Key store type: " + keyStoreType);
}
}
System.err.println(startMessage);
try {
final TCPProxySSLSocketFactory sslSocketFactory;
if (useSSL) {
try {
// TCPProxySSLSocketFactoryImplementation depends on JSSE,
// load dynamically.
final Class socketFactoryClass =
Class.forName(SSL_SOCKET_FACTORY_CLASS);
final Constructor socketFactoryConstructor =
socketFactoryClass.getConstructor(
new Class[] { File.class, new char[0].getClass(), String.class,
});
sslSocketFactory = (TCPProxySSLSocketFactory)
socketFactoryConstructor.newInstance(
new Object[] { keyStoreFile, keyStorePassword, keyStoreType, });
}
catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
else {
sslSocketFactory = null;
}
if (isHTTPProxy) {
m_proxyEngine =
new HTTPProxyTCPProxyEngine(
sslSocketFactory,
requestFilter,
responseFilter,
outputWriter,
localEndPoint,
useColour,
timeout,
chainedHTTPProxy,
chainedHTTPSProxy);
}
else {
if (useSSL) {
m_proxyEngine =
new PortForwarderTCPProxyEngine(
sslSocketFactory,
requestFilter,
responseFilter,
outputWriter,
new ConnectionDetails(localEndPoint, remoteEndPoint, useSSL),
useColour,
timeout);
}
else {
m_proxyEngine =
new PortForwarderTCPProxyEngine(
requestFilter,
responseFilter,
outputWriter,
new ConnectionDetails(localEndPoint, remoteEndPoint, useSSL),
useColour,
timeout);
}
}
if (console) {
new TCPProxyConsole(m_proxyEngine);
}
System.err.println("Engine initialised, listening on port " + localPort);
}
catch (Throwable e) {
System.err.println("Could not initialise engine:");
e.printStackTrace();
System.exit(2);
}
}
|
diff --git a/src/org/broad/igv/feature/tribble/CodecFactory.java b/src/org/broad/igv/feature/tribble/CodecFactory.java
index 572e08fa..5ada9d59 100644
--- a/src/org/broad/igv/feature/tribble/CodecFactory.java
+++ b/src/org/broad/igv/feature/tribble/CodecFactory.java
@@ -1,147 +1,147 @@
/*
* Copyright (c) 2007-2011 by The Broad Institute of MIT and Harvard. All Rights Reserved.
*
* This software is licensed under the terms of the GNU Lesser General Public License (LGPL),
* Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php.
*
* THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR
* WARRANTES OF ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, WHETHER
* OR NOT DISCOVERABLE. IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR RESPECTIVE
* TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES
* OF ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
* ECONOMIC DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER
* THE BROAD OR MIT SHALL BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT
* SHALL KNOW OF THE POSSIBILITY OF THE FOREGOING.
*/
package org.broad.igv.feature.tribble;
import org.apache.log4j.Logger;
import org.broad.igv.exceptions.DataLoadException;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.peaks.PeakCodec;
import org.broad.igv.util.ParsingUtils;
import org.broad.tribble.FeatureCodec;
import org.broad.tribble.util.BlockCompressedInputStream;
import org.broad.tribble.util.SeekableStreamFactory;
import org.broadinstitute.sting.utils.codecs.vcf.VCF3Codec;
import org.broadinstitute.sting.utils.codecs.vcf.VCFCodec;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* A factory class for Tribble codecs. implements a single, static, public method to return a codec given a
* path to a feature file (bed, gff, vcf, etc).
*/
public class CodecFactory {
private static Logger log = Logger.getLogger(CodecFactory.class);
/**
* Return a tribble codec to decode the supplied file.
*
* @param path the path (file or URL) to the feature rile.
*/
public static FeatureCodec getCodec(String path) {
return getCodec(path, null);
}
public static FeatureCodec getCodec(String path, Genome genome) {
String fn = path.toLowerCase();
if (fn.endsWith(".gz")) {
int l = fn.length() - 3;
fn = fn.substring(0, l);
}
if (fn.endsWith(".vcf4")) {
return new VCFWrapperCodec(new VCFCodec());
} else if (fn.endsWith(".vcf")) {
return new VCFWrapperCodec(getVCFCodec(path));
} else if (fn.endsWith(".bed")) {
return new IGVBEDCodec();
} else if (fn.contains("refflat")) {
return new UCSCGeneTableCodec(genome, UCSCGeneTableCodec.Type.REFFLAT);
} else if (fn.contains("genepred") || fn.contains("ensgene") || fn.contains("refgene")) {
return new UCSCGeneTableCodec(genome, UCSCGeneTableCodec.Type.GENEPRED);
} else if (fn.contains("ucscgene")) {
return new UCSCGeneTableCodec(genome, UCSCGeneTableCodec.Type.UCSCGENE);
} else if (fn.endsWith(".repmask")) {
return new REPMaskCodec();
} else if (fn.endsWith(".gff3") || fn.endsWith(".gvf")) {
return new GFFCodec(GFFCodec.Version.GFF3);
} else if (fn.endsWith(".gff") || fn.endsWith(".gtf")) {
return new GFFCodec();
//} else if (fn.endsWith(".sam")) {
//return new SAMCodec();
} else if (fn.endsWith(".psl") || fn.endsWith(".pslx")) {
return new PSLCodec();
} else if (fn.endsWith(".peak")) {
return new PeakCodec();
} else {
return null;
}
}
/**
* Return the appropriate VCFCodec based on the version tag.
* <p/>
* e.g. ##fileformat=VCFv4.1
*
* @param path Path to the VCF file. Can be a file path, or URL
* @return
*/
private static FeatureCodec getVCFCodec(String path) {
BufferedReader reader = null;
try {
// If the file ends with ".gz" assume it is a tabix indexed file
if (path.toLowerCase().endsWith(".gz")) {
reader = new BufferedReader(new InputStreamReader(new BlockCompressedInputStream(
- ParsingUtils.openInputStream(path))));
+ org.broad.tribble.util.ParsingUtils.openInputStream(path))));
} else {
reader = ParsingUtils.openBufferedReader(path);
}
// Look for fileformat directive. This should be the first line, but just in case check the first 20
int lineCount = 0;
String formatLine;
while ((formatLine = reader.readLine()) != null && lineCount < 20) {
if (formatLine.toLowerCase().startsWith("##fileformat")) {
String[] tmp = formatLine.split("=");
if (tmp.length > 1) {
String version = tmp[1].toLowerCase();
if (version.startsWith("vcfv3")) {
return new VCF3Codec();
} else {
return new VCFCodec();
}
}
}
lineCount++;
}
} catch (IOException e) {
log.error("Error checking VCF Version");
} finally {
if (reader != null) try {
reader.close();
} catch (IOException e) {
}
}
// Should never get here, but as a last resort assume this is a VCF 4.x file.
return new VCFCodec();
}
}
| true | true | private static FeatureCodec getVCFCodec(String path) {
BufferedReader reader = null;
try {
// If the file ends with ".gz" assume it is a tabix indexed file
if (path.toLowerCase().endsWith(".gz")) {
reader = new BufferedReader(new InputStreamReader(new BlockCompressedInputStream(
ParsingUtils.openInputStream(path))));
} else {
reader = ParsingUtils.openBufferedReader(path);
}
// Look for fileformat directive. This should be the first line, but just in case check the first 20
int lineCount = 0;
String formatLine;
while ((formatLine = reader.readLine()) != null && lineCount < 20) {
if (formatLine.toLowerCase().startsWith("##fileformat")) {
String[] tmp = formatLine.split("=");
if (tmp.length > 1) {
String version = tmp[1].toLowerCase();
if (version.startsWith("vcfv3")) {
return new VCF3Codec();
} else {
return new VCFCodec();
}
}
}
lineCount++;
}
} catch (IOException e) {
log.error("Error checking VCF Version");
} finally {
if (reader != null) try {
reader.close();
} catch (IOException e) {
}
}
// Should never get here, but as a last resort assume this is a VCF 4.x file.
return new VCFCodec();
}
| private static FeatureCodec getVCFCodec(String path) {
BufferedReader reader = null;
try {
// If the file ends with ".gz" assume it is a tabix indexed file
if (path.toLowerCase().endsWith(".gz")) {
reader = new BufferedReader(new InputStreamReader(new BlockCompressedInputStream(
org.broad.tribble.util.ParsingUtils.openInputStream(path))));
} else {
reader = ParsingUtils.openBufferedReader(path);
}
// Look for fileformat directive. This should be the first line, but just in case check the first 20
int lineCount = 0;
String formatLine;
while ((formatLine = reader.readLine()) != null && lineCount < 20) {
if (formatLine.toLowerCase().startsWith("##fileformat")) {
String[] tmp = formatLine.split("=");
if (tmp.length > 1) {
String version = tmp[1].toLowerCase();
if (version.startsWith("vcfv3")) {
return new VCF3Codec();
} else {
return new VCFCodec();
}
}
}
lineCount++;
}
} catch (IOException e) {
log.error("Error checking VCF Version");
} finally {
if (reader != null) try {
reader.close();
} catch (IOException e) {
}
}
// Should never get here, but as a last resort assume this is a VCF 4.x file.
return new VCFCodec();
}
|
diff --git a/src/net/rptools/maptool/client/ui/MapToolFrame.java b/src/net/rptools/maptool/client/ui/MapToolFrame.java
index e2aa7ee3..d94c5450 100644
--- a/src/net/rptools/maptool/client/ui/MapToolFrame.java
+++ b/src/net/rptools/maptool/client/ui/MapToolFrame.java
@@ -1,1463 +1,1457 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.rptools.maptool.client.ui;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.border.BevelBorder;
import javax.swing.filechooser.FileFilter;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import javax.xml.parsers.ParserConfigurationException;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Observer;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import com.jidesoft.docking.DefaultDockableHolder;
import com.jidesoft.docking.DockableFrame;
import net.rptools.lib.AppEvent;
import net.rptools.lib.AppEventListener;
import net.rptools.lib.FileUtil;
import net.rptools.lib.MD5Key;
import net.rptools.lib.image.ImageUtil;
import net.rptools.lib.swing.AboutDialog;
import net.rptools.lib.swing.ColorPicker;
import net.rptools.lib.swing.PositionalLayout;
import net.rptools.lib.swing.SwingUtil;
import net.rptools.lib.swing.preference.FramePreferences;
import net.rptools.maptool.client.AppActions;
import net.rptools.maptool.client.AppConstants;
import net.rptools.maptool.client.AppPreferences;
import net.rptools.maptool.client.AppState;
import net.rptools.maptool.client.AppStyle;
import net.rptools.maptool.client.AppUtil;
import net.rptools.maptool.client.MapTool;
import net.rptools.maptool.client.ServerDisconnectHandler;
import net.rptools.maptool.client.swing.CoordinateStatusBar;
import net.rptools.maptool.client.swing.GlassPane;
import net.rptools.maptool.client.swing.ImageChooserDialog;
import net.rptools.maptool.client.swing.MemoryStatusBar;
import net.rptools.maptool.client.swing.ProgressStatusBar;
import net.rptools.maptool.client.swing.SpacerStatusBar;
import net.rptools.maptool.client.swing.StatusPanel;
import net.rptools.maptool.client.swing.ZoomStatusBar;
import net.rptools.maptool.client.tool.PointerTool;
import net.rptools.maptool.client.tool.StampTool;
import net.rptools.maptool.client.ui.assetpanel.AssetDirectory;
import net.rptools.maptool.client.ui.assetpanel.AssetPanel;
import net.rptools.maptool.client.ui.commandpanel.CommandPanel;
import net.rptools.maptool.client.ui.lookuptable.LookupTablePanel;
import net.rptools.maptool.client.ui.macrobuttons.buttons.MacroButton;
import net.rptools.maptool.client.ui.macrobuttons.panels.CampaignPanel;
import net.rptools.maptool.client.ui.macrobuttons.panels.GlobalPanel;
import net.rptools.maptool.client.ui.macrobuttons.panels.ImpersonatePanel;
import net.rptools.maptool.client.ui.macrobuttons.panels.SelectionPanel;
import net.rptools.maptool.client.ui.macrobuttons.panels.Tab;
import net.rptools.maptool.client.ui.token.EditTokenDialog;
import net.rptools.maptool.client.ui.tokenpanel.InitiativePanel;
import net.rptools.maptool.client.ui.tokenpanel.TokenPanelTreeCellRenderer;
import net.rptools.maptool.client.ui.tokenpanel.TokenPanelTreeModel;
import net.rptools.maptool.client.ui.zone.PointerOverlay;
import net.rptools.maptool.client.ui.zone.ZoneMiniMapPanel;
import net.rptools.maptool.client.ui.zone.ZoneRenderer;
import net.rptools.maptool.model.Asset;
import net.rptools.maptool.model.AssetAvailableListener;
import net.rptools.maptool.model.AssetManager;
import net.rptools.maptool.model.GUID;
import net.rptools.maptool.model.InitiativeList;
import net.rptools.maptool.model.ObservableList;
import net.rptools.maptool.model.TextMessage;
import net.rptools.maptool.model.Token;
import net.rptools.maptool.model.Zone;
import net.rptools.maptool.model.ZoneFactory;
import net.rptools.maptool.model.ZonePoint;
import net.rptools.maptool.model.drawing.DrawableColorPaint;
import net.rptools.maptool.model.drawing.DrawablePaint;
import net.rptools.maptool.model.drawing.DrawableTexturePaint;
import net.rptools.maptool.model.drawing.Pen;
import net.rptools.maptool.util.ImageManager;
import org.xml.sax.SAXException;
/**
*/
public class MapToolFrame extends DefaultDockableHolder implements WindowListener, AppEventListener {
private static final long serialVersionUID = 3905523813025329458L;
// TODO: parameterize this (or make it a preference)
private static final int WINDOW_WIDTH = 800;
private static final int WINDOW_HEIGHT = 600;
private static final String DOCKING_PROFILE_NAME = "maptoolDocking";
private Pen pen = new Pen(Pen.DEFAULT);
/**
* Are the drawing measurements being painted?
*/
private boolean paintDrawingMeasurement = true;
private Map<MTFrame, DockableFrame> frameMap = new HashMap<MTFrame, DockableFrame>();
private ImageChooserDialog imageChooserDialog;
// Components
private ZoneRenderer currentRenderer;
private AssetPanel assetPanel;
private ClientConnectionPanel connectionPanel;
private InitiativePanel initiativePanel;
private PointerOverlay pointerOverlay;
private CommandPanel commandPanel;
private AboutDialog aboutDialog;
private ColorPicker colorPicker;
private Toolbox toolbox;
private ZoneMiniMapPanel zoneMiniMapPanel;
private JPanel zoneRendererPanel;
private JPanel visibleControlPanel;
private FullScreenFrame fullScreenFrame;
private JPanel rendererBorderPanel;
private List<ZoneRenderer> zoneRendererList;
private JMenuBar menuBar;
private StatusPanel statusPanel;
private ActivityMonitorPanel activityMonitor = new ActivityMonitorPanel();
private ProgressStatusBar progressBar = new ProgressStatusBar();
private ConnectionStatusPanel connectionStatusPanel = new ConnectionStatusPanel();
private CoordinateStatusBar coordinateStatusBar;
private ZoomStatusBar zoomStatusBar;
private JLabel chatActionLabel;
private GlassPane glassPane;
private TextureChooserPanel textureChooserPanel;
private LookupTablePanel lookupTablePanel;
// Components
private JFileChooser loadPropsFileChooser;
private JFileChooser loadFileChooser;
private JFileChooser saveCmpgnFileChooser;
private JFileChooser savePropsFileChooser;
private JFileChooser saveFileChooser;
private FileFilter campaignFilter = new MTFileFilter("cmpgn", "MapTool Campaign");
private FileFilter propertiesFilter = new MTFileFilter("mtprops", "MapTool Properties");
private EditTokenDialog tokenPropertiesDialog;
private CampaignPanel campaignPanel = new CampaignPanel();
private GlobalPanel globalPanel = new GlobalPanel();
private SelectionPanel selectionPanel = new SelectionPanel();
private ImpersonatePanel impersonatePanel = new ImpersonatePanel();
public MapToolFrame() {
// Set up the frame
super(AppConstants.APP_NAME);
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(this);
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
SwingUtil.centerOnScreen(this);
setFocusTraversalPolicy(new MapToolFocusTraversalPolicy());
try {
setIconImage(ImageUtil.getImage("net/rptools/maptool/client/image/minilogo.png"));
} catch (IOException ioe) {
System.err.println ("Could not load icon image");
}
// Components
glassPane = new GlassPane();
assetPanel = createAssetPanel();
connectionPanel = createConnectionPanel();
toolbox = new Toolbox();
initiativePanel = createInitiativePanel();
zoneRendererList = new CopyOnWriteArrayList<ZoneRenderer>();
pointerOverlay = new PointerOverlay();
colorPicker = new ColorPicker(this);
textureChooserPanel = new TextureChooserPanel(colorPicker.getPaintChooser(), assetPanel.getModel(), "imageExplorerTextureChooser");
colorPicker.getPaintChooser().addPaintChooser(textureChooserPanel);
String credits = "";
String version = "";
Image logo = null;
try {
credits = new String(FileUtil
.loadResource("net/rptools/maptool/client/credits.html"));
version = MapTool.getVersion();
credits = credits.replace("%VERSION%", version);
logo = ImageUtil.getImage("net/rptools/maptool/client/image/maptool-logo.png");
} catch (Exception ioe) {
System.err.println("Unable to load credits or version");
}
aboutDialog = new AboutDialog(this, logo, credits);
aboutDialog.setSize(354, 400);
statusPanel = new StatusPanel();
statusPanel.addPanel(getCoordinateStatusBar());
statusPanel.addPanel(getZoomStatusBar());
statusPanel.addPanel(new MemoryStatusBar());
// statusPanel.addPanel(progressBar);
statusPanel.addPanel(connectionStatusPanel);
statusPanel.addPanel(activityMonitor);
statusPanel.addPanel(new SpacerStatusBar(25));
zoneMiniMapPanel = new ZoneMiniMapPanel();
zoneMiniMapPanel.setSize(100, 100);
zoneRendererPanel = new JPanel(new PositionalLayout(5));
zoneRendererPanel.setBackground(Color.black);
// zoneRendererPanel.add(zoneMiniMapPanel, PositionalLayout.Position.SE);
zoneRendererPanel.add(getChatActionLabel(), PositionalLayout.Position.SW);
commandPanel = new CommandPanel();
MapTool.getMessageList().addObserver(commandPanel);
MapTool.getMessageList().addObserver(createChatIconMessageObserver());
rendererBorderPanel = new JPanel(new GridLayout());
rendererBorderPanel.setBorder(BorderFactory.createLineBorder(Color.darkGray));
rendererBorderPanel.add(zoneRendererPanel);
// Put it all together
menuBar = new AppMenuBar();
setJMenuBar(menuBar);
add(BorderLayout.NORTH, new ToolbarPanel(toolbox));
add(BorderLayout.SOUTH, statusPanel);
setGlassPane(glassPane);
removeWindowsF10();
MapTool.getEventDispatcher().addListener(this, MapTool.ZoneEvent.Activated);
new FramePreferences(AppConstants.APP_NAME, "mainFrame", this);
restorePreferences();
updateKeyStrokes();
// This will cause the frame to be set to visible (BAD jide, BAD! No cookie for you!)
configureDocking();
}
public ImageChooserDialog getImageChooserDialog() {
if (imageChooserDialog == null) {
imageChooserDialog = new ImageChooserDialog(this);
}
return imageChooserDialog;
}
public enum MTFrame {
CONNECTIONS("Connections"),
TOKEN_TREE("Map Explorer"),
INITIATIVE("Initiative"),
IMAGE_EXPLORER("Library"),
CHAT("Chat"),
LOOKUP_TABLES("Tables"),
GLOBAL("Global"),
CAMPAIGN("Campaign"),
SELECTION("Selected"),
IMPERSONATED("Impersonate");
private String displayName;
private MTFrame(String displayName) {
this.displayName = displayName;
}
public String toString() {
return displayName;
}
}
private void configureDocking() {
initializeFrames();
getDockingManager().setProfileKey(DOCKING_PROFILE_NAME);
getDockingManager().setOutlineMode(com.jidesoft.docking.DockingManager.PARTIAL_OUTLINE_MODE);
getDockingManager().setUsePref(false);
getDockingManager().getWorkspace().setAcceptDockableFrame(false);
// Main panel
getDockingManager().getWorkspace().add(rendererBorderPanel);
// Docked frames
getDockingManager().addFrame(getFrame(MTFrame.CONNECTIONS));
getDockingManager().addFrame(getFrame(MTFrame.TOKEN_TREE));
getDockingManager().addFrame(getFrame(MTFrame.INITIATIVE));
getDockingManager().addFrame(getFrame(MTFrame.IMAGE_EXPLORER));
getDockingManager().addFrame(getFrame(MTFrame.CHAT));
getDockingManager().addFrame(getFrame(MTFrame.LOOKUP_TABLES));
getDockingManager().addFrame(getFrame(MTFrame.GLOBAL));
getDockingManager().addFrame(getFrame(MTFrame.CAMPAIGN));
getDockingManager().addFrame(getFrame(MTFrame.SELECTION));
getDockingManager().addFrame(getFrame(MTFrame.IMPERSONATED));
try {
getDockingManager().loadInitialLayout(MapToolFrame.class.getClassLoader().getResourceAsStream("net/rptools/maptool/client/ui/ilayout.xml"));
} catch (ParserConfigurationException e) {
MapTool.showError("Could not parse the layout file");
e.printStackTrace();
} catch (SAXException e) {
MapTool.showError("Could not parse the layout file");
e.printStackTrace();
} catch (IOException e) {
MapTool.showError("Could not load the layout file");
e.printStackTrace();
}
getDockingManager().loadLayoutDataFromFile(AppUtil.getAppHome("config").getAbsolutePath()+"/layout.dat");
}
public DockableFrame getFrame(MTFrame frame) {
return frameMap.get(frame);
}
private void initializeFrames() {
frameMap.put(MTFrame.CONNECTIONS,createDockingFrame(MTFrame.CONNECTIONS, new JScrollPane(connectionPanel), new ImageIcon(AppStyle.connectionsImage)));
frameMap.put(MTFrame.TOKEN_TREE, createDockingFrame(MTFrame.TOKEN_TREE, new JScrollPane(createTokenTreePanel()), new ImageIcon(AppStyle.mapExplorerImage)));
frameMap.put(MTFrame.IMAGE_EXPLORER, createDockingFrame(MTFrame.IMAGE_EXPLORER, assetPanel, new ImageIcon(AppStyle.resourceLibraryImage)));
frameMap.put(MTFrame.CHAT, createDockingFrame(MTFrame.CHAT, commandPanel, new ImageIcon(AppStyle.chatPanelImage)));
frameMap.put(MTFrame.LOOKUP_TABLES, createDockingFrame(MTFrame.LOOKUP_TABLES, getLookupTablePanel(), new ImageIcon(AppStyle.tablesPanelImage)));
frameMap.put(MTFrame.INITIATIVE, createDockingFrame(MTFrame.INITIATIVE, initiativePanel, new ImageIcon(AppStyle.initiativePanelImage)));
JScrollPane campaign = scrollPaneFactory(campaignPanel);
JScrollPane global = scrollPaneFactory(globalPanel);
JScrollPane selection = scrollPaneFactory(selectionPanel);
JScrollPane impersonate = scrollPaneFactory(impersonatePanel);
frameMap.put(MTFrame.GLOBAL, createDockingFrame(MTFrame.GLOBAL, global, new ImageIcon(AppStyle.globalPanelImage)));
frameMap.put(MTFrame.CAMPAIGN, createDockingFrame(MTFrame.CAMPAIGN, campaign, new ImageIcon(AppStyle.campaignPanelImage)));
frameMap.put(MTFrame.SELECTION, createDockingFrame(MTFrame.SELECTION, selection, new ImageIcon(AppStyle.selectionPanelImage)));
frameMap.put(MTFrame.IMPERSONATED, createDockingFrame(MTFrame.IMPERSONATED, impersonate, new ImageIcon(AppStyle.impersonatePanelImage)));
}
private JScrollPane scrollPaneFactory(JPanel panel) {
JScrollPane pane = new JScrollPane(panel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
pane.getViewport().setBorder(null);
return pane;
}
private static DockableFrame createDockingFrame(MTFrame mtFrame, Component component, Icon icon) {
DockableFrame frame = new DockableFrame(mtFrame.name(), icon);
frame.add(component);
return frame;
}
public LookupTablePanel getLookupTablePanel() {
if (lookupTablePanel == null) {
lookupTablePanel = new LookupTablePanel();
}
return lookupTablePanel;
}
public EditTokenDialog getTokenPropertiesDialog() {
if (tokenPropertiesDialog == null) {
tokenPropertiesDialog = new EditTokenDialog();
}
return tokenPropertiesDialog;
}
public void refresh() {
if (getCurrentZoneRenderer() != null) {
getCurrentZoneRenderer().repaint();
}
}
private class MTFileFilter extends FileFilter {
private String extension;
private String description;
MTFileFilter(String exten, String desc){
super();
extension = exten;
description = desc;
}
//Accept directories and files matching extension
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
String ext = getExtension(f);
if (ext != null) {
if (ext.equals(extension)){
return true;
} else {
return false;
}
}
return false;
}
public String getDescription() {
return description;
}
public String getExtension(File f) {
String ext = null;
String s = f.getName();
int i = s.lastIndexOf('.');
if (i > 0 && i < s.length() - 1) {
ext = s.substring(i+1).toLowerCase();
}
return ext;
}
}
public FileFilter getCmpgnFileFilter() {
return campaignFilter;
}
public JFileChooser getLoadPropsFileChooser() {
if (loadPropsFileChooser == null) {
loadPropsFileChooser = new JFileChooser();
loadPropsFileChooser.setCurrentDirectory(AppPreferences.getLoadDir());
loadPropsFileChooser.addChoosableFileFilter(propertiesFilter);
loadPropsFileChooser.setDialogTitle("Import Properties");
}
loadPropsFileChooser.setFileFilter(propertiesFilter);
return loadPropsFileChooser;
}
public JFileChooser getLoadFileChooser() {
if (loadFileChooser == null) {
loadFileChooser = new JFileChooser();
loadFileChooser.setCurrentDirectory(AppPreferences.getLoadDir());
}
return loadFileChooser;
}
public JFileChooser getSaveCmpgnFileChooser() {
if (saveCmpgnFileChooser == null) {
saveCmpgnFileChooser = new JFileChooser();
saveCmpgnFileChooser.setCurrentDirectory(AppPreferences.getSaveDir());
saveCmpgnFileChooser.addChoosableFileFilter(campaignFilter);
saveCmpgnFileChooser.setDialogTitle("Save Campaign");
}
saveCmpgnFileChooser.setAcceptAllFileFilterUsed(true);
return saveCmpgnFileChooser;
}
public JFileChooser getSavePropsFileChooser() {
if (savePropsFileChooser == null) {
savePropsFileChooser = new JFileChooser();
savePropsFileChooser.setCurrentDirectory(AppPreferences.getSaveDir());
savePropsFileChooser.addChoosableFileFilter(propertiesFilter);
savePropsFileChooser.setDialogTitle("Export Properties");
}
savePropsFileChooser.setAcceptAllFileFilterUsed(true);
return savePropsFileChooser;
}
public JFileChooser getSaveFileChooser() {
if (saveFileChooser == null) {
saveFileChooser = new JFileChooser();
saveFileChooser.setCurrentDirectory(AppPreferences.getSaveDir());
}
return saveFileChooser;
}
public void showControlPanel(JPanel... panels) {
JPanel layoutPanel = new JPanel(new GridBagLayout());
layoutPanel.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
int i = 0;
for (JPanel panel : panels) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = i;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.BOTH;
layoutPanel.add(panel, gbc);
i++;
}
layoutPanel.setSize(layoutPanel.getPreferredSize());
zoneRendererPanel.add(layoutPanel, PositionalLayout.Position.NE);
zoneRendererPanel.setComponentZOrder(layoutPanel, 0);
zoneRendererPanel.revalidate();
zoneRendererPanel.repaint();
visibleControlPanel = layoutPanel;
}
public ZoomStatusBar getZoomStatusBar() {
if (zoomStatusBar == null) {
zoomStatusBar = new ZoomStatusBar();
}
return zoomStatusBar;
}
public CoordinateStatusBar getCoordinateStatusBar() {
if (coordinateStatusBar == null) {
coordinateStatusBar = new CoordinateStatusBar();
}
return coordinateStatusBar;
}
public void hideControlPanel() {
if (visibleControlPanel != null) {
if (zoneRendererPanel != null) {
zoneRendererPanel.remove(visibleControlPanel);
}
visibleControlPanel = null;
refresh();
}
}
public void showNonModalGlassPane(JComponent component, int x, int y) {
showGlassPane(component, x, y, false);
}
public void showModalGlassPane(JComponent component, int x, int y) {
showGlassPane(component, x, y, true);
}
private void showGlassPane(JComponent component, int x, int y, boolean modal) {
component.setSize(component.getPreferredSize());
component.setLocation(x, y);
glassPane.setLayout(null);
glassPane.add(component);
glassPane.setModel(modal);
glassPane.setVisible(true);
}
public void showFilledGlassPane(JComponent component) {
glassPane.setLayout(new GridLayout());
glassPane.add(component);
glassPane.setVisible(true);
}
public void hideGlassPane() {
glassPane.removeAll();
glassPane.setVisible(false);
}
public JLabel getChatActionLabel() {
if (chatActionLabel == null) {
chatActionLabel = new JLabel(new ImageIcon(AppStyle.chatImage));
chatActionLabel.setSize(chatActionLabel.getPreferredSize());
chatActionLabel.setVisible(false);
chatActionLabel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
showCommandPanel();
}
});
}
return chatActionLabel;
}
private Observer createChatIconMessageObserver() {
return new Observer() {
public void update(java.util.Observable o, Object arg) {
ObservableList<TextMessage> textList = MapTool.getMessageList();
ObservableList.Event event = (ObservableList.Event) arg;
// if (rightSplitPane.isBottomHidden() && event ==
// ObservableList.Event.append) {
//
// getChatActionLabel().setVisible(true);
// }
}
};
}
public boolean isCommandPanelVisible() {
return getFrame(MTFrame.CHAT).isShowing();
}
public void showCommandPanel() {
chatActionLabel.setVisible(false);
getDockingManager().showFrame(MTFrame.CHAT.name());
commandPanel.requestFocus();
}
public void hideCommandPanel() {
getDockingManager().hideFrame(MTFrame.CHAT.name());
}
public ColorPicker getColorPicker() {
return colorPicker;
}
public void showAboutDialog() {
aboutDialog.setVisible(true);
}
public ConnectionStatusPanel getConnectionStatusPanel() {
return connectionStatusPanel;
}
private void restorePreferences() {
List<File> assetRootList = AppPreferences.getAssetRoots();
for (File file : assetRootList) {
addAssetRoot(file);
}
}
private TokenPanelTreeModel tokenPanelTreeModel;
private JComponent createTokenTreePanel() {
final JTree tree = new JTree();
tokenPanelTreeModel = new TokenPanelTreeModel(tree);
tree.setModel(tokenPanelTreeModel);
tree.setCellRenderer(new TokenPanelTreeCellRenderer());
tree.getSelectionModel().setSelectionMode(
TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
tree.addMouseListener(new MouseAdapter() {
// TODO: Make this a handler class, not an aic
@Override
public void mousePressed(MouseEvent e) {
// tree.setSelectionPath(tree.getPathForLocation(e.getX(),
// e.getY()));
TreePath path = tree.getPathForLocation(e.getX(), e.getY());
if (path == null) {
return;
}
Object row = path.getLastPathComponent();
int rowIndex = tree.getRowForLocation(e.getX(), e.getY());
if (SwingUtilities.isLeftMouseButton(e)) {
if (!SwingUtil.isShiftDown(e)) {
tree.clearSelection();
}
tree.addSelectionInterval(rowIndex, rowIndex);
if (row instanceof Token) {
if (e.getClickCount() == 2) {
Token token = (Token) row;
getCurrentZoneRenderer().clearSelectedTokens();
getCurrentZoneRenderer().centerOn(
new ZonePoint(token.getX(), token.getY()));
// Pick an appropriate tool
- if (token.isToken()) {
- getToolbox().setSelectedTool(PointerTool.class);
- } else {
- getCurrentZoneRenderer().setActiveLayer(
- token.isObjectStamp() ? Zone.Layer.OBJECT
- : Zone.Layer.BACKGROUND);
- getToolbox().setSelectedTool(StampTool.class);
- }
+ getToolbox().setSelectedTool(token.isToken() ? PointerTool.class : StampTool.class);
+ getCurrentZoneRenderer().setActiveLayer(token.getLayer());
getCurrentZoneRenderer().selectToken(token.getId());
getCurrentZoneRenderer().requestFocusInWindow();
}
}
}
if (SwingUtilities.isRightMouseButton(e)) {
if (!isRowSelected(tree.getSelectionRows(), rowIndex)
&& !SwingUtil.isShiftDown(e)) {
tree.clearSelection();
tree.addSelectionInterval(rowIndex, rowIndex);
}
final int x = e.getX();
final int y = e.getY();
EventQueue.invokeLater(new Runnable() {
public void run() {
Token firstToken = null;
Set<GUID> selectedTokenSet = new HashSet<GUID>();
for (TreePath path : tree.getSelectionPaths()) {
if (path.getLastPathComponent() instanceof Token) {
Token token = (Token) path
.getLastPathComponent();
if (firstToken == null) {
firstToken = token;
}
if (AppUtil.playerOwns(token)) {
selectedTokenSet.add(token.getId());
}
}
}
if (selectedTokenSet.size() > 0) {
if (firstToken.isStamp()) {
new StampPopupMenu(selectedTokenSet, x, y,
getCurrentZoneRenderer(),
firstToken).showPopup(tree);
} else {
new TokenPopupMenu(selectedTokenSet, x, y,
getCurrentZoneRenderer(),
firstToken).showPopup(tree);
}
}
}
});
}
}
});
MapTool.getEventDispatcher().addListener(new AppEventListener() {
public void handleAppEvent(AppEvent event) {
tokenPanelTreeModel.setZone((Zone) event.getNewValue());
}
}, MapTool.ZoneEvent.Activated);
return tree;
}
public void clearTokenTree() {
if (tokenPanelTreeModel != null) {
tokenPanelTreeModel.setZone(null);
}
if (initiativePanel != null) {
initiativePanel.clearTokens();
}
}
public void updateTokenTree() {
if (tokenPanelTreeModel != null) {
tokenPanelTreeModel.update();
}
if (initiativePanel != null) {
initiativePanel.update();
}
}
private boolean isRowSelected(int[] selectedRows, int row) {
if (selectedRows == null) {
return false;
}
for (int selectedRow : selectedRows) {
if (row == selectedRow) {
return true;
}
}
return false;
}
private ClientConnectionPanel createConnectionPanel() {
final ClientConnectionPanel panel = new ClientConnectionPanel();
return panel;
}
private InitiativePanel createInitiativePanel() {
MapTool.getEventDispatcher().addListener(new AppEventListener() {
public void handleAppEvent(AppEvent event) {
initiativePanel.setZone((Zone)event.getNewValue());
}
}, MapTool.ZoneEvent.Activated);
return new InitiativePanel();
}
private AssetPanel createAssetPanel() {
final AssetPanel panel = new AssetPanel("mainAssetPanel");
panel.addImagePanelMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
// // TODO use for real popup logic
// if (SwingUtilities.isLeftMouseButton(e)) {
// if (e.getClickCount() == 2) {
//
// List<Object> idList = panel.getSelectedIds();
// if (idList == null || idList.size() == 0) {
// return;
// }
//
// final int index = (Integer) idList.get(0);
// createZone(panel.getAsset(index));
// }
// }
//
if (SwingUtilities.isRightMouseButton(e) && MapTool.getPlayer().isGM()) {
List<Object> idList = panel.getSelectedIds();
if (idList == null || idList.size() == 0) {
return;
}
final int index = (Integer) idList.get(0);
JPopupMenu menu = new JPopupMenu();
menu.add(new JMenuItem(new AbstractAction() {
{
putValue(NAME, "New Map");
}
public void actionPerformed(ActionEvent e) {
createZone(panel.getAsset(index));
}
}));
panel.showImagePanelPopup(menu, e.getX(), e.getY());
}
}
private void createZone(Asset asset) {
Zone zone = ZoneFactory.createZone();
zone.setName(asset.getName());
BufferedImage image = ImageManager.getImageAndWait(asset);
if (image.getWidth() < 200 || image.getHeight() < 200) {
zone.setBackgroundPaint(new DrawableTexturePaint(asset));
} else {
zone.setMapAsset(asset.getId());
zone.setBackgroundPaint(new DrawableColorPaint(Color.black));
}
MapPropertiesDialog newMapDialog = new MapPropertiesDialog(MapTool.getFrame());
newMapDialog.setZone(zone);
newMapDialog.setVisible(true);
if (newMapDialog.getStatus() == MapPropertiesDialog.Status.OK) {
MapTool.addZone(zone);
}
}
});
return panel;
}
public PointerOverlay getPointerOverlay() {
return pointerOverlay;
}
public void setStatusMessage(final String message) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
statusPanel.setStatus(" " + message);
}
});
}
public ActivityMonitorPanel getActivityMonitor() {
return activityMonitor;
}
public void startIndeterminateAction() {
progressBar.startIndeterminate();
}
public void endIndeterminateAction() {
progressBar.endIndeterminate();
}
public void startDeterminateAction(int totalWork) {
progressBar.startDeterminate(totalWork);
}
public void updateDeterminateActionProgress(int additionalWorkCompleted) {
progressBar.updateDeterminateProgress(additionalWorkCompleted);
}
public void endDeterminateAction() {
progressBar.endDeterminate();
}
public ZoneMiniMapPanel getZoneMiniMapPanel() {
return zoneMiniMapPanel;
}
// /////////////////////////////////////////////////////////////////////////
// static methods
// /////////////////////////////////////////////////////////////////////////
public CommandPanel getCommandPanel() {
return commandPanel;
}
public ClientConnectionPanel getConnectionPanel() {
return connectionPanel;
}
public AssetPanel getAssetPanel() {
return assetPanel;
}
public void addAssetRoot(File rootDir) {
assetPanel.addAssetRoot(new AssetDirectory(rootDir,
AppConstants.IMAGE_FILE_FILTER));
// if (mainSplitPane.isLeftHidden()) {
// mainSplitPane.showLeft();
// }
}
public Pen getPen() {
pen.setPaint(DrawablePaint.convertPaint(colorPicker.getForegroundPaint()));
pen.setBackgroundPaint(DrawablePaint.convertPaint(colorPicker.getBackgroundPaint()));
pen.setThickness(colorPicker.getStrokeWidth());
pen.setOpacity(colorPicker.getOpacity());
pen.setThickness(colorPicker.getStrokeWidth());
return pen;
}
public List<ZoneRenderer> getZoneRenderers() {
// TODO: This should prob be immutable
return zoneRendererList;
}
public ZoneRenderer getCurrentZoneRenderer() {
return currentRenderer;
}
public void addZoneRenderer(ZoneRenderer renderer) {
zoneRendererList.add(renderer);
}
public void removeZoneRenderer(ZoneRenderer renderer) {
boolean isCurrent = renderer == getCurrentZoneRenderer();
zoneRendererList.remove(renderer);
if (isCurrent) {
boolean rendererSet = false;
for (ZoneRenderer currRenderer : zoneRendererList) {
if (MapTool.getPlayer().isGM() || currRenderer.getZone().isVisible()) {
setCurrentZoneRenderer(currRenderer);
rendererSet = true;
break;
}
}
if (!rendererSet) {
setCurrentZoneRenderer(null);
}
}
zoneMiniMapPanel.flush();
zoneMiniMapPanel.repaint();
}
public void clearZoneRendererList() {
zoneRendererList.clear();
zoneMiniMapPanel.flush();
zoneMiniMapPanel.repaint();
}
public void setCurrentZoneRenderer(ZoneRenderer renderer) {
// Handle new renderers
// TODO: should this be here ?
if (renderer != null && !zoneRendererList.contains(renderer)) {
zoneRendererList.add(renderer);
}
if (currentRenderer != null) {
currentRenderer.flush();
zoneRendererPanel.remove(currentRenderer);
}
if (renderer != null) {
zoneRendererPanel.add(renderer, PositionalLayout.Position.CENTER);
zoneRendererPanel.doLayout();
}
currentRenderer = renderer;
initiativePanel.update();
toolbox.setTargetRenderer(renderer);
if (renderer != null) {
MapTool.getEventDispatcher().fireEvent(MapTool.ZoneEvent.Activated, this, null, renderer.getZone());
renderer.requestFocusInWindow();
}
AppActions.updateActions();
repaint();
setTitleViaRenderer(renderer);
getZoomStatusBar().update();
}
public void setTitleViaRenderer(ZoneRenderer renderer) {
String campaignName = " - [Default] ";
if (AppState.getCampaignFile() != null) {
String s = AppState.getCampaignFile().getName();
// remove the file extension of the campaign file name
s = s.substring(0, s.length() - AppConstants.CAMPAIGN_FILE_EXTENSION.length());
campaignName = " - [" + s + "]";
}
setTitle(AppConstants.APP_NAME + campaignName + (renderer != null ? " - " + renderer.getZone().getName() : ""));
}
public Toolbox getToolbox() {
return toolbox;
}
public ZoneRenderer getZoneRenderer(Zone zone) {
for (ZoneRenderer renderer : zoneRendererList) {
if (zone == renderer.getZone()) {
return renderer;
}
}
return null;
}
public ZoneRenderer getZoneRenderer(GUID zoneGUID) {
for (ZoneRenderer renderer : zoneRendererList) {
if (zoneGUID.equals(renderer.getZone().getId())) {
return renderer;
}
}
return null;
}
/**
* Get the paintDrawingMeasurements for this MapToolClient.
*
* @return Returns the current value of paintDrawingMeasurements.
*/
public boolean isPaintDrawingMeasurement() {
return paintDrawingMeasurement;
}
/**
* Set the value of paintDrawingMeasurements for this MapToolClient.
*
* @param aPaintDrawingMeasurements
* The paintDrawingMeasurements to set.
*/
public void setPaintDrawingMeasurement(boolean aPaintDrawingMeasurements) {
paintDrawingMeasurement = aPaintDrawingMeasurements;
}
public void showFullScreen() {
GraphicsConfiguration graphicsConfig = getGraphicsConfiguration();
GraphicsDevice device = graphicsConfig.getDevice();
Rectangle bounds = graphicsConfig.getBounds();
fullScreenFrame = new FullScreenFrame();
fullScreenFrame.add(zoneRendererPanel);
fullScreenFrame.setBounds(bounds.x, bounds.y, bounds.width,
bounds.height);
fullScreenFrame.setJMenuBar(menuBar);
menuBar.setVisible(false);
fullScreenFrame.setVisible(true);
this.setVisible(false);
}
public boolean isFullScreen() {
return fullScreenFrame != null;
}
public void showWindowed() {
if (fullScreenFrame == null) {
return;
}
rendererBorderPanel.add(zoneRendererPanel);
setJMenuBar(menuBar);
menuBar.setVisible(true);
this.setVisible(true);
fullScreenFrame.dispose();
fullScreenFrame = null;
}
public class FullScreenFrame extends JFrame {
public FullScreenFrame() {
setUndecorated(true);
}
}
////
// APP EVENT LISTENER
public void handleAppEvent(AppEvent evt) {
if (evt.getId() != MapTool.ZoneEvent.Activated) {
return;
}
final Zone zone = (Zone)evt.getNewValue();
AssetAvailableListener listener = new AssetAvailableListener() {
public void assetAvailable(net.rptools.lib.MD5Key key) {
ZoneRenderer renderer = getCurrentZoneRenderer();
if (renderer.getZone() == zone) {
ImageManager.getImage(AssetManager.getAsset(key),
renderer);
}
}
};
// Let's add all the assets, starting with the backgrounds
for (Token token : zone.getBackgroundStamps()) {
MD5Key key = token.getImageAssetId();
if (AssetManager.hasAsset(key)) {
ImageManager.getImage(AssetManager.getAsset(key));
} else {
if (!AssetManager.isAssetRequested(key)) {
AssetManager.addAssetListener(token.getImageAssetId(),
listener);
// This will force a server request if we don't already
// have it
AssetManager.getAsset(token.getImageAssetId());
}
}
}
// Now the stamps
for (Token token : zone.getStampTokens()) {
MD5Key key = token.getImageAssetId();
if (AssetManager.hasAsset(key)) {
ImageManager.getImage(AssetManager.getAsset(key));
} else {
if (!AssetManager.isAssetRequested(key)) {
AssetManager.addAssetListener(token.getImageAssetId(),
listener);
// This will force a server request if we don't already
// have it
AssetManager.getAsset(token.getImageAssetId());
}
}
}
// Now add the rest
for (Token token : zone.getAllTokens()) {
MD5Key key = token.getImageAssetId();
if (AssetManager.hasAsset(key)) {
ImageManager.getImage(AssetManager.getAsset(key));
} else {
if (!AssetManager.isAssetRequested(key)) {
AssetManager.addAssetListener(key, listener);
// This will force a server request if we don't already
// have it
AssetManager.getAsset(token.getImageAssetId());
}
}
}
}
// //
// WINDOW LISTENER
public void windowOpened(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
if (!confirmClose()) {
return;
}
closingMaintenance();
}
public boolean confirmClose() {
if (MapTool.isHostingServer()) {
if (!MapTool.confirm("You are hosting a server. Shutting down will disconnect all players. Are you sure?")) {
return false;
}
}
return true;
}
public void closingMaintenance() {
if (AppPreferences.getSaveReminder()) {
if (MapTool.getPlayer().isGM()) {
int result = JOptionPane.showConfirmDialog(
MapTool.getFrame(),
"Would you like to save your campaign before you exit?",
"Save Reminder",
JOptionPane.YES_NO_CANCEL_OPTION);
if (result == JOptionPane.CANCEL_OPTION) {
return;
}
if(result == JOptionPane.YES_OPTION) {
AppActions.SAVE_CAMPAIGN.actionPerformed(null);
}
} else {
if (!MapTool.confirm("You will be disconnected. Are you sure you want to exit?")) {
return;
}
}
}
ServerDisconnectHandler.disconnectExpected = true;
MapTool.disconnect();
getDockingManager().saveLayoutDataToFile(AppUtil.getAppHome("config").getAbsolutePath()+"/layout.dat");
// If closing cleanly, then remove the autosave file
MapTool.getAutoSaveManager().purge();
setVisible(false);
dispose();
}
public void windowClosed(WindowEvent e) {
System.exit(0);
}
public void windowIconified(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
//Windows OS defaults F10 to the menubar, noooooo!! We want for macro buttons
private void removeWindowsF10() {
InputMap imap = menuBar.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
Object action = imap.get(KeyStroke.getKeyStroke("F10"));
ActionMap amap = menuBar.getActionMap();
amap.getParent().remove(action);
}
public void updateKeyStrokes() {
updateKeyStrokes(menuBar);
for (MTFrame frame : frameMap.keySet()) {
updateKeyStrokes(frameMap.get(frame));
}
}
private void updateKeyStrokes(JComponent c) {
c.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).clear();
Map<KeyStroke, MacroButton> keyStrokeMap = MacroButtonHotKeyManager.getKeyStrokeMap();
for (KeyStroke keyStroke : keyStrokeMap.keySet()) {
final MacroButton button = keyStrokeMap.get(keyStroke);
c.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, button);
c.getActionMap().put(button, new AbstractAction() {
public void actionPerformed(ActionEvent event) {
button.getProperties().executeMacro();
}
});
}
}
public CampaignPanel getCampaignPanel() {
return campaignPanel;
}
public GlobalPanel getGlobalPanel() {
return globalPanel;
}
public ImpersonatePanel getImpersonatePanel() {
return impersonatePanel;
}
public SelectionPanel getSelectionPanel() {
return selectionPanel;
}
public void resetTokenPanels(){
impersonatePanel.reset();
selectionPanel.reset();
}
// currently only used after loading a campaign
public void resetPanels() {
MacroButtonHotKeyManager.clearKeyStrokes();
campaignPanel.reset();
globalPanel.reset();
impersonatePanel.reset();
selectionPanel.reset();
updateKeyStrokes();
}
/** @return Getter for initiativePanel */
public InitiativePanel getInitiativePanel() {
return initiativePanel;
}
// Macro import/export support
private FileFilter macroFilter = new MTFileFilter("mtmacro", "MapTool Macro");
private FileFilter macroSetFilter = new MTFileFilter("mtmacset", "MapTool Macro Set");
private JFileChooser saveMacroFileChooser;
private JFileChooser saveMacroSetFileChooser;
public JFileChooser getSaveMacroFileChooser() {
if (saveMacroFileChooser == null) {
saveMacroFileChooser = new JFileChooser();
saveMacroFileChooser.setCurrentDirectory(AppPreferences.getSaveDir());
saveMacroFileChooser.addChoosableFileFilter(macroFilter);
saveMacroFileChooser.setDialogTitle("Export Macro");
}
saveMacroFileChooser.setAcceptAllFileFilterUsed(true);
return saveMacroFileChooser;
}
public JFileChooser getSaveMacroSetFileChooser() {
if (saveMacroSetFileChooser == null) {
saveMacroSetFileChooser = new JFileChooser();
saveMacroSetFileChooser.setCurrentDirectory(AppPreferences.getSaveDir());
saveMacroSetFileChooser.addChoosableFileFilter(macroSetFilter);
saveMacroSetFileChooser.setDialogTitle("Export Macro Set");
}
saveMacroSetFileChooser.setAcceptAllFileFilterUsed(true);
return saveMacroSetFileChooser;
}
private JFileChooser loadMacroFileChooser;
private JFileChooser loadMacroSetFileChooser;
public JFileChooser getLoadMacroFileChooser() {
if (loadMacroFileChooser == null) {
loadMacroFileChooser = new JFileChooser();
loadMacroFileChooser.setCurrentDirectory(AppPreferences.getLoadDir());
loadMacroFileChooser.addChoosableFileFilter(macroFilter);
loadMacroFileChooser.setDialogTitle("Import Macro");
}
loadMacroFileChooser.setFileFilter(macroFilter);
return loadMacroFileChooser;
}
public JFileChooser getLoadMacroSetFileChooser() {
if (loadMacroSetFileChooser == null) {
loadMacroSetFileChooser = new JFileChooser();
loadMacroSetFileChooser.setCurrentDirectory(AppPreferences.getLoadDir());
loadMacroSetFileChooser.addChoosableFileFilter(macroSetFilter);
loadMacroSetFileChooser.setDialogTitle("Import Macro Set");
}
loadMacroSetFileChooser.setFileFilter(macroSetFilter);
return loadMacroSetFileChooser;
}
// end of Macro import/export support
// Table import/export support
private FileFilter tableFilter = new MTFileFilter("mttable", "MapTool Table");
private JFileChooser saveTableFileChooser;
public JFileChooser getSaveTableFileChooser() {
if (saveTableFileChooser == null) {
saveTableFileChooser = new JFileChooser();
saveTableFileChooser.setCurrentDirectory(AppPreferences.getSaveDir());
saveTableFileChooser.addChoosableFileFilter(tableFilter);
saveTableFileChooser.setDialogTitle("Export Table");
}
saveTableFileChooser.setAcceptAllFileFilterUsed(true);
return saveTableFileChooser;
}
private JFileChooser loadTableFileChooser;
public JFileChooser getLoadTableFileChooser() {
if (loadTableFileChooser == null) {
loadTableFileChooser = new JFileChooser();
loadTableFileChooser.setCurrentDirectory(AppPreferences.getLoadDir());
loadTableFileChooser.addChoosableFileFilter(tableFilter);
loadTableFileChooser.setDialogTitle("Import Table");
}
loadTableFileChooser.setFileFilter(tableFilter);
return loadTableFileChooser;
}
// end of Table import/export support
}
| false | true | private JComponent createTokenTreePanel() {
final JTree tree = new JTree();
tokenPanelTreeModel = new TokenPanelTreeModel(tree);
tree.setModel(tokenPanelTreeModel);
tree.setCellRenderer(new TokenPanelTreeCellRenderer());
tree.getSelectionModel().setSelectionMode(
TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
tree.addMouseListener(new MouseAdapter() {
// TODO: Make this a handler class, not an aic
@Override
public void mousePressed(MouseEvent e) {
// tree.setSelectionPath(tree.getPathForLocation(e.getX(),
// e.getY()));
TreePath path = tree.getPathForLocation(e.getX(), e.getY());
if (path == null) {
return;
}
Object row = path.getLastPathComponent();
int rowIndex = tree.getRowForLocation(e.getX(), e.getY());
if (SwingUtilities.isLeftMouseButton(e)) {
if (!SwingUtil.isShiftDown(e)) {
tree.clearSelection();
}
tree.addSelectionInterval(rowIndex, rowIndex);
if (row instanceof Token) {
if (e.getClickCount() == 2) {
Token token = (Token) row;
getCurrentZoneRenderer().clearSelectedTokens();
getCurrentZoneRenderer().centerOn(
new ZonePoint(token.getX(), token.getY()));
// Pick an appropriate tool
if (token.isToken()) {
getToolbox().setSelectedTool(PointerTool.class);
} else {
getCurrentZoneRenderer().setActiveLayer(
token.isObjectStamp() ? Zone.Layer.OBJECT
: Zone.Layer.BACKGROUND);
getToolbox().setSelectedTool(StampTool.class);
}
getCurrentZoneRenderer().selectToken(token.getId());
getCurrentZoneRenderer().requestFocusInWindow();
}
}
}
if (SwingUtilities.isRightMouseButton(e)) {
if (!isRowSelected(tree.getSelectionRows(), rowIndex)
&& !SwingUtil.isShiftDown(e)) {
tree.clearSelection();
tree.addSelectionInterval(rowIndex, rowIndex);
}
final int x = e.getX();
final int y = e.getY();
EventQueue.invokeLater(new Runnable() {
public void run() {
Token firstToken = null;
Set<GUID> selectedTokenSet = new HashSet<GUID>();
for (TreePath path : tree.getSelectionPaths()) {
if (path.getLastPathComponent() instanceof Token) {
Token token = (Token) path
.getLastPathComponent();
if (firstToken == null) {
firstToken = token;
}
if (AppUtil.playerOwns(token)) {
selectedTokenSet.add(token.getId());
}
}
}
if (selectedTokenSet.size() > 0) {
if (firstToken.isStamp()) {
new StampPopupMenu(selectedTokenSet, x, y,
getCurrentZoneRenderer(),
firstToken).showPopup(tree);
} else {
new TokenPopupMenu(selectedTokenSet, x, y,
getCurrentZoneRenderer(),
firstToken).showPopup(tree);
}
}
}
});
}
}
});
MapTool.getEventDispatcher().addListener(new AppEventListener() {
public void handleAppEvent(AppEvent event) {
tokenPanelTreeModel.setZone((Zone) event.getNewValue());
}
}, MapTool.ZoneEvent.Activated);
return tree;
}
| private JComponent createTokenTreePanel() {
final JTree tree = new JTree();
tokenPanelTreeModel = new TokenPanelTreeModel(tree);
tree.setModel(tokenPanelTreeModel);
tree.setCellRenderer(new TokenPanelTreeCellRenderer());
tree.getSelectionModel().setSelectionMode(
TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
tree.addMouseListener(new MouseAdapter() {
// TODO: Make this a handler class, not an aic
@Override
public void mousePressed(MouseEvent e) {
// tree.setSelectionPath(tree.getPathForLocation(e.getX(),
// e.getY()));
TreePath path = tree.getPathForLocation(e.getX(), e.getY());
if (path == null) {
return;
}
Object row = path.getLastPathComponent();
int rowIndex = tree.getRowForLocation(e.getX(), e.getY());
if (SwingUtilities.isLeftMouseButton(e)) {
if (!SwingUtil.isShiftDown(e)) {
tree.clearSelection();
}
tree.addSelectionInterval(rowIndex, rowIndex);
if (row instanceof Token) {
if (e.getClickCount() == 2) {
Token token = (Token) row;
getCurrentZoneRenderer().clearSelectedTokens();
getCurrentZoneRenderer().centerOn(
new ZonePoint(token.getX(), token.getY()));
// Pick an appropriate tool
getToolbox().setSelectedTool(token.isToken() ? PointerTool.class : StampTool.class);
getCurrentZoneRenderer().setActiveLayer(token.getLayer());
getCurrentZoneRenderer().selectToken(token.getId());
getCurrentZoneRenderer().requestFocusInWindow();
}
}
}
if (SwingUtilities.isRightMouseButton(e)) {
if (!isRowSelected(tree.getSelectionRows(), rowIndex)
&& !SwingUtil.isShiftDown(e)) {
tree.clearSelection();
tree.addSelectionInterval(rowIndex, rowIndex);
}
final int x = e.getX();
final int y = e.getY();
EventQueue.invokeLater(new Runnable() {
public void run() {
Token firstToken = null;
Set<GUID> selectedTokenSet = new HashSet<GUID>();
for (TreePath path : tree.getSelectionPaths()) {
if (path.getLastPathComponent() instanceof Token) {
Token token = (Token) path
.getLastPathComponent();
if (firstToken == null) {
firstToken = token;
}
if (AppUtil.playerOwns(token)) {
selectedTokenSet.add(token.getId());
}
}
}
if (selectedTokenSet.size() > 0) {
if (firstToken.isStamp()) {
new StampPopupMenu(selectedTokenSet, x, y,
getCurrentZoneRenderer(),
firstToken).showPopup(tree);
} else {
new TokenPopupMenu(selectedTokenSet, x, y,
getCurrentZoneRenderer(),
firstToken).showPopup(tree);
}
}
}
});
}
}
});
MapTool.getEventDispatcher().addListener(new AppEventListener() {
public void handleAppEvent(AppEvent event) {
tokenPanelTreeModel.setZone((Zone) event.getNewValue());
}
}, MapTool.ZoneEvent.Activated);
return tree;
}
|
diff --git a/activiti-webapp-rest/src/main/java/org/activiti/rest/api/cycle/ContentRepresentationGet.java b/activiti-webapp-rest/src/main/java/org/activiti/rest/api/cycle/ContentRepresentationGet.java
index 9a43cd332..b827e2762 100644
--- a/activiti-webapp-rest/src/main/java/org/activiti/rest/api/cycle/ContentRepresentationGet.java
+++ b/activiti-webapp-rest/src/main/java/org/activiti/rest/api/cycle/ContentRepresentationGet.java
@@ -1,67 +1,68 @@
package org.activiti.rest.api.cycle;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URLEncoder;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpSession;
import org.activiti.cycle.ContentRepresentation;
import org.activiti.cycle.RepositoryArtifact;
import org.activiti.cycle.RepositoryConnector;
import org.activiti.rest.util.ActivitiRequest;
import org.activiti.rest.util.ActivitiWebScript;
import org.springframework.extensions.webscripts.Cache;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.WebScriptRequest;
public class ContentRepresentationGet extends ActivitiWebScript {
private static Logger log = Logger.getLogger(ContentRepresentationGet.class.getName());
@Override
protected void executeWebScript(ActivitiRequest req, Status status, Cache cache, Map<String, Object> model) {
String cuid = req.getCurrentUserId();
WebScriptRequest wsReq = req.getWebScriptRequest();
HttpSession session = req.getHttpServletRequest().getSession(true);
RepositoryConnector conn = SessionUtil.getRepositoryConnector(cuid, session);
String artifactId = req.getString("artifactId");
String representationId = req.getString("representationId");
+ String restProxyUri = req.getString("restProxyUri");
RepositoryArtifact artifact = conn.getRepositoryArtifact(artifactId);
// Get representation by id to determine whether it is an image...
try {
for (ContentRepresentation contentRepresentation : artifact.getArtifactType().getContentRepresentations()) {
if (contentRepresentation.getId().equals(representationId)) {
if (contentRepresentation.getMimeType().startsWith("image/")) {
- String imageUrl = wsReq.getServerPath() + wsReq.getContextPath() + "/service/content?artifactId=" + URLEncoder.encode(artifactId, "UTF-8")
+ String imageUrl = restProxyUri + "/content?artifactId=" + URLEncoder.encode(artifactId, "UTF-8")
+ "&content-type=" + URLEncoder.encode(contentRepresentation.getMimeType(), "UTF-8");
model.put("imageUrl", imageUrl);
} else {
String content = conn.getContent(artifactId, contentRepresentation.getId()).asString();
model.put("content", content);
}
model.put("id", contentRepresentation.getId());
break;
}
}
} catch (Exception ex) {
// we had a problem with a content representation log and go on,
// that this will not prevent other representations to be shown
log.log(Level.WARNING, "Exception while loading content representation", ex);
// TODO:Better concept how this is handled in the GUI
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
String stackTrace = "Exception while accessing content. Details:\n\n" + sw.toString();
model.put("exception", stackTrace);
}
}
}
| false | true | protected void executeWebScript(ActivitiRequest req, Status status, Cache cache, Map<String, Object> model) {
String cuid = req.getCurrentUserId();
WebScriptRequest wsReq = req.getWebScriptRequest();
HttpSession session = req.getHttpServletRequest().getSession(true);
RepositoryConnector conn = SessionUtil.getRepositoryConnector(cuid, session);
String artifactId = req.getString("artifactId");
String representationId = req.getString("representationId");
RepositoryArtifact artifact = conn.getRepositoryArtifact(artifactId);
// Get representation by id to determine whether it is an image...
try {
for (ContentRepresentation contentRepresentation : artifact.getArtifactType().getContentRepresentations()) {
if (contentRepresentation.getId().equals(representationId)) {
if (contentRepresentation.getMimeType().startsWith("image/")) {
String imageUrl = wsReq.getServerPath() + wsReq.getContextPath() + "/service/content?artifactId=" + URLEncoder.encode(artifactId, "UTF-8")
+ "&content-type=" + URLEncoder.encode(contentRepresentation.getMimeType(), "UTF-8");
model.put("imageUrl", imageUrl);
} else {
String content = conn.getContent(artifactId, contentRepresentation.getId()).asString();
model.put("content", content);
}
model.put("id", contentRepresentation.getId());
break;
}
}
} catch (Exception ex) {
// we had a problem with a content representation log and go on,
// that this will not prevent other representations to be shown
log.log(Level.WARNING, "Exception while loading content representation", ex);
// TODO:Better concept how this is handled in the GUI
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
String stackTrace = "Exception while accessing content. Details:\n\n" + sw.toString();
model.put("exception", stackTrace);
}
}
| protected void executeWebScript(ActivitiRequest req, Status status, Cache cache, Map<String, Object> model) {
String cuid = req.getCurrentUserId();
WebScriptRequest wsReq = req.getWebScriptRequest();
HttpSession session = req.getHttpServletRequest().getSession(true);
RepositoryConnector conn = SessionUtil.getRepositoryConnector(cuid, session);
String artifactId = req.getString("artifactId");
String representationId = req.getString("representationId");
String restProxyUri = req.getString("restProxyUri");
RepositoryArtifact artifact = conn.getRepositoryArtifact(artifactId);
// Get representation by id to determine whether it is an image...
try {
for (ContentRepresentation contentRepresentation : artifact.getArtifactType().getContentRepresentations()) {
if (contentRepresentation.getId().equals(representationId)) {
if (contentRepresentation.getMimeType().startsWith("image/")) {
String imageUrl = restProxyUri + "/content?artifactId=" + URLEncoder.encode(artifactId, "UTF-8")
+ "&content-type=" + URLEncoder.encode(contentRepresentation.getMimeType(), "UTF-8");
model.put("imageUrl", imageUrl);
} else {
String content = conn.getContent(artifactId, contentRepresentation.getId()).asString();
model.put("content", content);
}
model.put("id", contentRepresentation.getId());
break;
}
}
} catch (Exception ex) {
// we had a problem with a content representation log and go on,
// that this will not prevent other representations to be shown
log.log(Level.WARNING, "Exception while loading content representation", ex);
// TODO:Better concept how this is handled in the GUI
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
String stackTrace = "Exception while accessing content. Details:\n\n" + sw.toString();
model.put("exception", stackTrace);
}
}
|
diff --git a/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/perf/BenchMiscWorkspace.java b/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/perf/BenchMiscWorkspace.java
index 14fdf8016..8c804bc6b 100644
--- a/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/perf/BenchMiscWorkspace.java
+++ b/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/perf/BenchMiscWorkspace.java
@@ -1,63 +1,67 @@
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.core.tests.resources.perf;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.tests.harness.PerformanceTestRunner;
import org.eclipse.core.tests.resources.ResourceTest;
public class BenchMiscWorkspace extends ResourceTest {
public static Test suite() {
return new TestSuite(BenchMiscWorkspace.class);
// TestSuite suite = new TestSuite(BenchMiscWorkspace.class.getName());
// suite.addTest(new BenchMiscWorkspace("benchNoOp"));
// return suite;
}
/**
* Constructor for BenchMiscWorkspace.
*/
public BenchMiscWorkspace() {
super();
}
/**
* Constructor for BenchMiscWorkspace.
* @param name
*/
public BenchMiscWorkspace(String name) {
super(name);
}
/**
* Benchmarks performing many empty operations.
*/
public void testNoOp() throws Exception {
final IWorkspace ws = ResourcesPlugin.getWorkspace();
final IWorkspaceRunnable noop = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) {
}
};
+ //run a first operation to make sure no other jobs are running before starting timer
+ ws.run(noop,null);
+ waitForBuild();
+ //now start the test
new PerformanceTestRunner() {
protected void test() {
try {
ws.run(noop, null);
} catch (CoreException e) {
fail("0.0", e);
}
}
}.run(this, 10, 100000);
}
}
| true | true | public void testNoOp() throws Exception {
final IWorkspace ws = ResourcesPlugin.getWorkspace();
final IWorkspaceRunnable noop = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) {
}
};
new PerformanceTestRunner() {
protected void test() {
try {
ws.run(noop, null);
} catch (CoreException e) {
fail("0.0", e);
}
}
}.run(this, 10, 100000);
}
| public void testNoOp() throws Exception {
final IWorkspace ws = ResourcesPlugin.getWorkspace();
final IWorkspaceRunnable noop = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) {
}
};
//run a first operation to make sure no other jobs are running before starting timer
ws.run(noop,null);
waitForBuild();
//now start the test
new PerformanceTestRunner() {
protected void test() {
try {
ws.run(noop, null);
} catch (CoreException e) {
fail("0.0", e);
}
}
}.run(this, 10, 100000);
}
|
diff --git a/serenity-app/src/main/java/us/nineworlds/serenity/core/services/EpisodeRetrievalIntentService.java b/serenity-app/src/main/java/us/nineworlds/serenity/core/services/EpisodeRetrievalIntentService.java
index fa256c64..f486194c 100644
--- a/serenity-app/src/main/java/us/nineworlds/serenity/core/services/EpisodeRetrievalIntentService.java
+++ b/serenity-app/src/main/java/us/nineworlds/serenity/core/services/EpisodeRetrievalIntentService.java
@@ -1,270 +1,272 @@
/**
* The MIT License (MIT)
* Copyright (c) 2012 David Carver
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
* OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package us.nineworlds.serenity.core.services;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import us.nineworlds.plex.rest.model.impl.Director;
import us.nineworlds.plex.rest.model.impl.Genre;
import us.nineworlds.plex.rest.model.impl.Media;
import us.nineworlds.plex.rest.model.impl.MediaContainer;
import us.nineworlds.plex.rest.model.impl.Part;
import us.nineworlds.plex.rest.model.impl.Video;
import us.nineworlds.plex.rest.model.impl.Writer;
import us.nineworlds.serenity.R;
import us.nineworlds.serenity.SerenityApplication;
import us.nineworlds.serenity.core.model.VideoContentInfo;
import us.nineworlds.serenity.core.model.impl.EpisodePosterInfo;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
/**
* @author dcarver
*
*/
public class EpisodeRetrievalIntentService extends
AbstractPlexRESTIntentService {
protected List<VideoContentInfo> posterList = null;
protected String key;
private static final Pattern season = Pattern.compile("S\\d+");
private static final Pattern episode = Pattern.compile("E\\d+");
public EpisodeRetrievalIntentService() {
super("EpisodeRetrievalIntentService");
posterList = new ArrayList<VideoContentInfo>();
}
@Override
public void sendMessageResults(Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
Messenger messenger = (Messenger) extras.get("MESSENGER");
Message msg = Message.obtain();
msg.obj = posterList;
try {
messenger.send(msg);
} catch (RemoteException ex) {
Log.e(getClass().getName(), "Unable to send message", ex);
}
}
}
@Override
protected void onHandleIntent(Intent intent) {
key = intent.getExtras().getString("key", "");
createPosters();
sendMessageResults(intent);
}
protected void createPosters() {
MediaContainer mc = null;
try {
factory = SerenityApplication.getPlexFactory();
mc = retrieveVideos();
} catch (IOException ex) {
Log.e(getClass().getName(), "Unable to talk to server: ", ex);
} catch (Exception e) {
Log.e(getClass().getName(), "Oops.", e);
}
if (mc != null && mc.getSize() > 0) {
createVideoContent(mc);
}
}
/**
*
* @return A media container with episodes or videos
*
* @throws Exception
*/
protected MediaContainer retrieveVideos() throws Exception {
MediaContainer mc;
mc = factory.retrieveEpisodes(key);
return mc;
}
/**
* @param mc
* @param baseUrl
*/
protected void createVideoContent(MediaContainer mc) {
String baseUrl = factory.baseURL();
String parentPosterURL = null;
- if (mc.getParentPosterURL() != null) {
+ if (mc.getParentPosterURL() != null && !mc.getParentPosterURL().contains("shows")) {
parentPosterURL = baseUrl + mc.getParentPosterURL().substring(1);
}
List<Video> videos = mc.getVideos();
for (Video episode : videos) {
VideoContentInfo epi = new EpisodePosterInfo();
- epi.setParentPosterURL(parentPosterURL);
+ if (parentPosterURL != null) {
+ epi.setParentPosterURL(parentPosterURL);
+ }
epi.setId(episode.getRatingKey());
epi.setPlotSummary(episode.getSummary());
epi.setViewCount(episode.getViewCount());
epi.setResumeOffset(Long.valueOf(episode.getViewOffset())
.intValue());
epi.setDuration(Long.valueOf(episode.getDuration()).intValue());
epi.setOriginalAirDate(episode.getOriginallyAvailableDate());
if (episode.getParentThumbNailImageKey() != null) {
epi.setParentPosterURL(baseUrl
+ episode.getParentThumbNailImageKey().substring(1));
}
String burl = factory.baseURL() + ":/resources/show-fanart.jpg";
if (episode.getBackgroundImageKey() != null) {
burl = baseUrl
+ episode.getBackgroundImageKey().replaceFirst("/", "");
} else if (mc.getArt() != null) {
burl = baseUrl + mc.getArt().replaceFirst("/", "");
}
epi.setBackgroundURL(burl);
String turl = "";
if (episode.getThumbNailImageKey() != null) {
turl = baseUrl
+ episode.getThumbNailImageKey().replaceFirst("/", "");
}
epi.setPosterURL(turl);
epi.setTitle(episode.getTitle());
epi.setContentRating(episode.getContentRating());
List<Media> mediacont = episode.getMedias();
if (mediacont != null && !mediacont.isEmpty()) {
// We grab the first media container until we know more about
// why there can be multiples.
Media media = mediacont.get(0);
epi.setContainer(media.getContainer());
List<Part> parts = media.getVideoPart();
Part part = parts.get(0);
setSeasonEpisode(epi, part);
epi.setAudioCodec(media.getAudioCodec());
epi.setVideoCodec(media.getVideoCodec());
epi.setVideoResolution(media.getVideoResolution());
epi.setAspectRatio(media.getAspectRatio());
epi.setAudioChannels(media.getAudioChannels());
String directPlayUrl = factory.baseURL()
+ part.getKey().replaceFirst("/", "");
epi.setDirectPlayUrl(directPlayUrl);
}
createVideoDetails(episode, epi);
epi.setCastInfo("");
posterList.add(epi);
}
}
protected void setSeasonEpisode(VideoContentInfo epi, Part part) {
if (part == null) {
return;
}
String filename = part.getFilename();
if (filename == null) {
epi.setSeason(getString(R.string.unknown));
epi.setEpisodeNumber(getString(R.string.unknown));
}
Matcher mseason = season.matcher(filename);
Matcher mepisode = episode.matcher(filename);
if (mseason.find()) {
String sn = mseason.group();
String number = sn.substring(1);
String season = getString(R.string.season_)
+ Integer.toString(Integer.parseInt(number));
epi.setSeason(season);
}
if (mepisode.find()) {
String en = mepisode.group();
String number = en.substring(1);
String episode = getString(R.string.episode_)
+ Integer.toString(Integer.parseInt(number));
epi.setEpisodeNumber(episode);
}
}
/**
* @param video
* @param videoContentInfo
* @return
*/
protected void createVideoDetails(Video video,
VideoContentInfo videoContentInfo) {
if (video.getYear() != null) {
videoContentInfo.setYear(video.getYear());
}
if (video.getGenres() != null && video.getGenres().size() > 0) {
ArrayList<String> g = new ArrayList<String>();
for (Genre genre : video.getGenres()) {
g.add(genre.getTag());
}
videoContentInfo.setGenres(g);
}
if (video.getWriters() != null && video.getWriters().size() > 0) {
ArrayList<String> w = new ArrayList<String>();
for (Writer writer : video.getWriters()) {
w.add(writer.getTag());
}
videoContentInfo.setWriters(w);
}
if (video.getDirectors() != null && video.getDirectors().size() > 0) {
ArrayList<String> d = new ArrayList<String>();
for (Director director : video.getDirectors()) {
d.add(director.getTag());
}
videoContentInfo.setDirectors(d);
}
}
}
| false | true | protected void createVideoContent(MediaContainer mc) {
String baseUrl = factory.baseURL();
String parentPosterURL = null;
if (mc.getParentPosterURL() != null) {
parentPosterURL = baseUrl + mc.getParentPosterURL().substring(1);
}
List<Video> videos = mc.getVideos();
for (Video episode : videos) {
VideoContentInfo epi = new EpisodePosterInfo();
epi.setParentPosterURL(parentPosterURL);
epi.setId(episode.getRatingKey());
epi.setPlotSummary(episode.getSummary());
epi.setViewCount(episode.getViewCount());
epi.setResumeOffset(Long.valueOf(episode.getViewOffset())
.intValue());
epi.setDuration(Long.valueOf(episode.getDuration()).intValue());
epi.setOriginalAirDate(episode.getOriginallyAvailableDate());
if (episode.getParentThumbNailImageKey() != null) {
epi.setParentPosterURL(baseUrl
+ episode.getParentThumbNailImageKey().substring(1));
}
String burl = factory.baseURL() + ":/resources/show-fanart.jpg";
if (episode.getBackgroundImageKey() != null) {
burl = baseUrl
+ episode.getBackgroundImageKey().replaceFirst("/", "");
} else if (mc.getArt() != null) {
burl = baseUrl + mc.getArt().replaceFirst("/", "");
}
epi.setBackgroundURL(burl);
String turl = "";
if (episode.getThumbNailImageKey() != null) {
turl = baseUrl
+ episode.getThumbNailImageKey().replaceFirst("/", "");
}
epi.setPosterURL(turl);
epi.setTitle(episode.getTitle());
epi.setContentRating(episode.getContentRating());
List<Media> mediacont = episode.getMedias();
if (mediacont != null && !mediacont.isEmpty()) {
// We grab the first media container until we know more about
// why there can be multiples.
Media media = mediacont.get(0);
epi.setContainer(media.getContainer());
List<Part> parts = media.getVideoPart();
Part part = parts.get(0);
setSeasonEpisode(epi, part);
epi.setAudioCodec(media.getAudioCodec());
epi.setVideoCodec(media.getVideoCodec());
epi.setVideoResolution(media.getVideoResolution());
epi.setAspectRatio(media.getAspectRatio());
epi.setAudioChannels(media.getAudioChannels());
String directPlayUrl = factory.baseURL()
+ part.getKey().replaceFirst("/", "");
epi.setDirectPlayUrl(directPlayUrl);
}
createVideoDetails(episode, epi);
epi.setCastInfo("");
posterList.add(epi);
}
}
| protected void createVideoContent(MediaContainer mc) {
String baseUrl = factory.baseURL();
String parentPosterURL = null;
if (mc.getParentPosterURL() != null && !mc.getParentPosterURL().contains("shows")) {
parentPosterURL = baseUrl + mc.getParentPosterURL().substring(1);
}
List<Video> videos = mc.getVideos();
for (Video episode : videos) {
VideoContentInfo epi = new EpisodePosterInfo();
if (parentPosterURL != null) {
epi.setParentPosterURL(parentPosterURL);
}
epi.setId(episode.getRatingKey());
epi.setPlotSummary(episode.getSummary());
epi.setViewCount(episode.getViewCount());
epi.setResumeOffset(Long.valueOf(episode.getViewOffset())
.intValue());
epi.setDuration(Long.valueOf(episode.getDuration()).intValue());
epi.setOriginalAirDate(episode.getOriginallyAvailableDate());
if (episode.getParentThumbNailImageKey() != null) {
epi.setParentPosterURL(baseUrl
+ episode.getParentThumbNailImageKey().substring(1));
}
String burl = factory.baseURL() + ":/resources/show-fanart.jpg";
if (episode.getBackgroundImageKey() != null) {
burl = baseUrl
+ episode.getBackgroundImageKey().replaceFirst("/", "");
} else if (mc.getArt() != null) {
burl = baseUrl + mc.getArt().replaceFirst("/", "");
}
epi.setBackgroundURL(burl);
String turl = "";
if (episode.getThumbNailImageKey() != null) {
turl = baseUrl
+ episode.getThumbNailImageKey().replaceFirst("/", "");
}
epi.setPosterURL(turl);
epi.setTitle(episode.getTitle());
epi.setContentRating(episode.getContentRating());
List<Media> mediacont = episode.getMedias();
if (mediacont != null && !mediacont.isEmpty()) {
// We grab the first media container until we know more about
// why there can be multiples.
Media media = mediacont.get(0);
epi.setContainer(media.getContainer());
List<Part> parts = media.getVideoPart();
Part part = parts.get(0);
setSeasonEpisode(epi, part);
epi.setAudioCodec(media.getAudioCodec());
epi.setVideoCodec(media.getVideoCodec());
epi.setVideoResolution(media.getVideoResolution());
epi.setAspectRatio(media.getAspectRatio());
epi.setAudioChannels(media.getAudioChannels());
String directPlayUrl = factory.baseURL()
+ part.getKey().replaceFirst("/", "");
epi.setDirectPlayUrl(directPlayUrl);
}
createVideoDetails(episode, epi);
epi.setCastInfo("");
posterList.add(epi);
}
}
|
diff --git a/SpagoBIMobileEngine/src/it/eng/spagobi/engine/mobile/table/serializer/MobileDatasetTableSerializer.java b/SpagoBIMobileEngine/src/it/eng/spagobi/engine/mobile/table/serializer/MobileDatasetTableSerializer.java
index 9b07f913d..a37e92b0f 100644
--- a/SpagoBIMobileEngine/src/it/eng/spagobi/engine/mobile/table/serializer/MobileDatasetTableSerializer.java
+++ b/SpagoBIMobileEngine/src/it/eng/spagobi/engine/mobile/table/serializer/MobileDatasetTableSerializer.java
@@ -1,75 +1,75 @@
/* SpagoBI, the Open Source Business Intelligence suite
* Copyright (C) 2012 Engineering Ingegneria Informatica S.p.A. - SpagoBI Competency Center
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0, without the "Incompatible With Secondary Licenses" notice.
* If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package it.eng.spagobi.engine.mobile.table.serializer;
import it.eng.spagobi.tools.dataset.common.datastore.IDataStore;
import it.eng.spagobi.tools.dataset.common.datastore.IField;
import it.eng.spagobi.tools.dataset.common.datastore.IRecord;
import it.eng.spagobi.tools.dataset.common.metadata.IFieldMetaData;
import java.util.Iterator;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MobileDatasetTableSerializer {
private static final String MODEL_ERROR = "error";
public static transient Logger logger = Logger.getLogger(MobileDatasetTableSerializer.class);
public Object write(IDataStore dataStore, JSONObject features) throws RuntimeException {
JSONObject result = null;
int recNo;
IRecord record;
JSONObject recordJSON;
try {
result = new JSONObject();
- result.put(MODEL_ERROR, false);
+ result.put(MODEL_ERROR, "false");
// put udpValues assocated to ModelInstance Node
JSONArray dsValuesJSON = new JSONArray();
// records
recNo = 0;
Iterator records = dataStore.iterator();
while(records.hasNext()) {
record = (IRecord)records.next();
recordJSON = new JSONObject();
for(int i = 0; i < dataStore.getMetaData().getFieldCount(); i++) {
IFieldMetaData fieldMetaData = dataStore.getMetaData().getFieldMeta(i);
String key = fieldMetaData.getAlias() != null ? fieldMetaData.getAlias() : fieldMetaData.getName();
IField field = record.getFieldAt( dataStore.getMetaData().getFieldIndex( key ) );
String fieldValue = "";
if(field.getValue() != null) {
fieldValue = field.getValue().toString();
}
recordJSON.put(key, fieldValue);
}
dsValuesJSON.put(recordJSON);
recNo++;
}
result.put("values", dsValuesJSON);
result.put("features", features);
result.put("total", recNo);
} catch (JSONException e) {
logger.error(e);
} finally {
logger.debug("OUT");
}
return result;
}
}
| true | true | public Object write(IDataStore dataStore, JSONObject features) throws RuntimeException {
JSONObject result = null;
int recNo;
IRecord record;
JSONObject recordJSON;
try {
result = new JSONObject();
result.put(MODEL_ERROR, false);
// put udpValues assocated to ModelInstance Node
JSONArray dsValuesJSON = new JSONArray();
// records
recNo = 0;
Iterator records = dataStore.iterator();
while(records.hasNext()) {
record = (IRecord)records.next();
recordJSON = new JSONObject();
for(int i = 0; i < dataStore.getMetaData().getFieldCount(); i++) {
IFieldMetaData fieldMetaData = dataStore.getMetaData().getFieldMeta(i);
String key = fieldMetaData.getAlias() != null ? fieldMetaData.getAlias() : fieldMetaData.getName();
IField field = record.getFieldAt( dataStore.getMetaData().getFieldIndex( key ) );
String fieldValue = "";
if(field.getValue() != null) {
fieldValue = field.getValue().toString();
}
recordJSON.put(key, fieldValue);
}
dsValuesJSON.put(recordJSON);
recNo++;
}
result.put("values", dsValuesJSON);
result.put("features", features);
result.put("total", recNo);
} catch (JSONException e) {
logger.error(e);
} finally {
logger.debug("OUT");
}
return result;
}
| public Object write(IDataStore dataStore, JSONObject features) throws RuntimeException {
JSONObject result = null;
int recNo;
IRecord record;
JSONObject recordJSON;
try {
result = new JSONObject();
result.put(MODEL_ERROR, "false");
// put udpValues assocated to ModelInstance Node
JSONArray dsValuesJSON = new JSONArray();
// records
recNo = 0;
Iterator records = dataStore.iterator();
while(records.hasNext()) {
record = (IRecord)records.next();
recordJSON = new JSONObject();
for(int i = 0; i < dataStore.getMetaData().getFieldCount(); i++) {
IFieldMetaData fieldMetaData = dataStore.getMetaData().getFieldMeta(i);
String key = fieldMetaData.getAlias() != null ? fieldMetaData.getAlias() : fieldMetaData.getName();
IField field = record.getFieldAt( dataStore.getMetaData().getFieldIndex( key ) );
String fieldValue = "";
if(field.getValue() != null) {
fieldValue = field.getValue().toString();
}
recordJSON.put(key, fieldValue);
}
dsValuesJSON.put(recordJSON);
recNo++;
}
result.put("values", dsValuesJSON);
result.put("features", features);
result.put("total", recNo);
} catch (JSONException e) {
logger.error(e);
} finally {
logger.debug("OUT");
}
return result;
}
|
diff --git a/src/main/java/org/jvnet/hudson/plugins/m2release/M2ReleaseBuildWrapper.java b/src/main/java/org/jvnet/hudson/plugins/m2release/M2ReleaseBuildWrapper.java
index ed23717..69f57f4 100644
--- a/src/main/java/org/jvnet/hudson/plugins/m2release/M2ReleaseBuildWrapper.java
+++ b/src/main/java/org/jvnet/hudson/plugins/m2release/M2ReleaseBuildWrapper.java
@@ -1,515 +1,522 @@
/*
* The MIT License
*
* Copyright (c) 2010, NDS Group Ltd., James Nord
*
* 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.jvnet.hudson.plugins.m2release;
import hudson.Extension;
import hudson.Launcher;
import hudson.Util;
import hudson.maven.AbstractMavenProject;
import hudson.maven.MavenBuild;
import hudson.maven.MavenModule;
import hudson.maven.MavenModuleSet;
import hudson.maven.MavenModuleSetBuild;
import hudson.model.Action;
import hudson.model.BuildListener;
import hudson.model.Result;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Descriptor;
import hudson.model.Hudson;
import hudson.model.Item;
import hudson.model.Run;
import hudson.security.Permission;
import hudson.security.PermissionGroup;
import hudson.tasks.BuildWrapper;
import hudson.tasks.BuildWrapperDescriptor;
import hudson.tasks.Builder;
import hudson.util.FormValidation;
import hudson.util.RunList;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import javax.servlet.ServletException;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.jvnet.hudson.plugins.m2release.nexus.Stage;
import org.jvnet.hudson.plugins.m2release.nexus.StageClient;
import org.jvnet.hudson.plugins.m2release.nexus.StageException;
import org.jvnet.localizer.Localizable;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Wraps a {@link MavenBuild} to be able to run the <a
* href="http://maven.apache.org/plugins/maven-release-plugin/">maven release plugin</a> on demand, with the
* ability to auto close a Nexus Pro Staging Repo
*
* @author James Nord
* @author Dominik Bartholdi
* @version 0.3
* @since 0.1
*/
public class M2ReleaseBuildWrapper extends BuildWrapper {
private transient Logger log = LoggerFactory.getLogger(M2ReleaseBuildWrapper.class);
/** For backwards compatibility with older configurations. @deprecated */
@Deprecated
public transient boolean defaultVersioningMode;
private String scmUserEnvVar = "";
private String scmPasswordEnvVar = "";
private String releaseEnvVar = DescriptorImpl.DEFAULT_RELEASE_ENVVAR;
private String releaseGoals = DescriptorImpl.DEFAULT_RELEASE_GOALS;
private String dryRunGoals = DescriptorImpl.DEFAULT_DRYRUN_GOALS;
public boolean selectCustomScmCommentPrefix = DescriptorImpl.DEFAULT_SELECT_CUSTOM_SCM_COMMENT_PREFIX;
public boolean selectAppendHudsonUsername = DescriptorImpl.DEFAULT_SELECT_APPEND_HUDSON_USERNAME;
public boolean selectScmCredentials = DescriptorImpl.DEFAULT_SELECT_SCM_CREDENTIALS;
@DataBoundConstructor
public M2ReleaseBuildWrapper(String releaseGoals, String dryRunGoals, boolean selectCustomScmCommentPrefix, boolean selectAppendHudsonUsername, boolean selectScmCredentials, String releaseEnvVar, String scmUserEnvVar, String scmPasswordEnvVar) {
super();
this.releaseGoals = releaseGoals;
this.dryRunGoals = dryRunGoals;
this.selectCustomScmCommentPrefix = selectCustomScmCommentPrefix;
this.selectAppendHudsonUsername = selectAppendHudsonUsername;
this.selectScmCredentials = selectScmCredentials;
this.releaseEnvVar = releaseEnvVar;
this.scmUserEnvVar = scmUserEnvVar;
this.scmPasswordEnvVar = scmPasswordEnvVar;
}
@Override
public Environment setUp(@SuppressWarnings("rawtypes") AbstractBuild build, Launcher launcher, final BuildListener listener)
throws IOException,
InterruptedException {
if (!isReleaseBuild(build)) {
// we are not performing a release so don't need a custom tearDown.
return new Environment() {
/** intentionally blank */
@Override
public void buildEnvVars(Map<String, String> env) {
if (StringUtils.isNotBlank(releaseEnvVar)) {
// inform others that we are NOT doing a release build
env.put(releaseEnvVar, "false");
}
}
};
}
// we are a release build
M2ReleaseArgumentsAction args = build.getAction(M2ReleaseArgumentsAction.class);
StringBuilder buildGoals = new StringBuilder();
buildGoals.append("-DdevelopmentVersion=").append(args.getDevelopmentVersion()).append(' ');
buildGoals.append("-DreleaseVersion=").append(args.getReleaseVersion()).append(' ');
if (args.getScmUsername() != null) {
buildGoals.append("-Dusername=").append(args.getScmUsername()).append(' ');
}
if (args.getScmPassword() != null) {
buildGoals.append("-Dpassword=").append(args.getScmPassword()).append(' ');
}
if (args.getScmCommentPrefix() != null) {
buildGoals.append("\"-DscmCommentPrefix=");
buildGoals.append(args.getScmCommentPrefix());
if (args.isAppendHusonUserName()) {
buildGoals.append(String.format("(%s)", args.getHudsonUserName()));
}
buildGoals.append("\" ");
}
if (args.getScmTagName() != null) {
buildGoals.append("-Dtag=").append(args.getScmTagName()).append(' ');
}
if (args.isDryRun()) {
buildGoals.append(getDryRunGoals());
}
else {
buildGoals.append(getReleaseGoals());
}
build.addAction(new M2ReleaseArgumentInterceptorAction(buildGoals.toString()));
build.addAction(new M2ReleaseBadgeAction(args.getReleaseVersion(), args.isDryRun()));
return new Environment() {
@Override
public void buildEnvVars(Map<String, String> env) {
if (StringUtils.isNotBlank(releaseEnvVar)) {
// inform others that we are doing a release build
env.put(releaseEnvVar, "true");
}
}
@Override
public boolean tearDown(@SuppressWarnings("rawtypes") AbstractBuild bld, BuildListener lstnr)
throws IOException, InterruptedException {
boolean retVal = true;
final MavenModuleSet mmSet = getModuleSet(bld);
M2ReleaseArgumentsAction args = bld.getAction(M2ReleaseArgumentsAction.class);
if (args.isDryRun()) {
lstnr.getLogger().println("[M2Release] its only a dryRun, no need to mark it for keep");
}
if (bld.getResult() != null && bld.getResult().isBetterOrEqualTo(Result.SUCCESS) && !args.isDryRun()) {
// keep this build.
lstnr.getLogger().println("[M2Release] marking build to keep until the next release build");
bld.keepLog();
for (Run run : (RunList<? extends Run>) (bld.getProject().getBuilds())) {
M2ReleaseBadgeAction a = run.getAction(M2ReleaseBadgeAction.class);
if (a != null && run.getResult() == Result.SUCCESS && !a.isDryRun()) {
if (bld.getNumber() != run.getNumber()) {
lstnr.getLogger().println(
"[M2Release] removing keep build from build " + run.getNumber());
run.keepLog(false);
break;
}
}
}
}
if (args.isCloseNexusStage() && !args.isDryRun()) {
StageClient client = new StageClient(new URL(getDescriptor().getNexusURL()), getDescriptor()
.getNexusUser(), getDescriptor().getNexusPassword());
try {
MavenModule rootModule = mmSet.getRootModule();
// TODO grab the version that we have just released...
Stage stage = client.getOpenStageID(rootModule.getModuleName().groupId,
rootModule.getModuleName().artifactId, args.getReleaseVersion());
if (stage != null) {
- lstnr.getLogger().println("[M2Release] Closing repository " + stage);
- client.closeStage(stage, args.getRepoDescription());
- lstnr.getLogger().println("[M2Release] Closed staging repository.");
+ if (bld.getResult() != null && bld.getResult().isBetterOrEqualTo(Result.SUCCESS)) {
+ lstnr.getLogger().println("[M2Release] Closing repository " + stage);
+ client.closeStage(stage, args.getRepoDescription());
+ lstnr.getLogger().println("[M2Release] Closed staging repository.");
+ }
+ else {
+ lstnr.getLogger().println("[M2Release] Dropping repository " + stage);
+ client.closeStage(stage, args.getRepoDescription());
+ lstnr.getLogger().println("[M2Release] Dropped staging repository.");
+ }
}
else {
retVal = false;
lstnr.fatalError("[M2Release] Could not find nexus stage repository for project.\n");
}
}
catch (StageException ex) {
lstnr.fatalError("[M2Release] Could not close repository , %s\n", ex.toString());
log.error("[M2Release] Could not close repository", ex);
retVal = false;
}
}
return retVal;
}
};
}
public boolean isSelectCustomScmCommentPrefix() {
return selectCustomScmCommentPrefix;
}
public void setSelectCustomScmCommentPrefix(boolean selectCustomScmCommentPrefix) {
this.selectCustomScmCommentPrefix = selectCustomScmCommentPrefix;
}
public boolean isSelectAppendHudsonUsername() {
return selectAppendHudsonUsername;
}
public void setSelectAppendHudsonUsername(boolean selectAppendHudsonUsername) {
this.selectAppendHudsonUsername = selectAppendHudsonUsername;
}
private MavenModuleSet getModuleSet(AbstractBuild<?,?> build) {
if (build instanceof MavenBuild) {
MavenBuild m2Build = (MavenBuild) build;
MavenModule mm = m2Build.getProject();
MavenModuleSet mmSet = mm.getParent();
return mmSet;
}
else if (build instanceof MavenModuleSetBuild) {
MavenModuleSetBuild m2moduleSetBuild = (MavenModuleSetBuild) build;
MavenModuleSet mmSet = m2moduleSetBuild.getProject();
return mmSet;
}
else {
return null;
}
}
@Override
public Action getProjectAction(@SuppressWarnings("rawtypes") AbstractProject job) {
return new M2ReleaseAction((MavenModuleSet) job, selectCustomScmCommentPrefix, selectAppendHudsonUsername, selectScmCredentials);
}
public static boolean hasReleasePermission(@SuppressWarnings("rawtypes") AbstractProject job) {
return job.hasPermission(DescriptorImpl.CREATE_RELEASE);
}
public static void checkReleasePermission(@SuppressWarnings("rawtypes") AbstractProject job) {
job.checkPermission(DescriptorImpl.CREATE_RELEASE);
}
public String getReleaseEnvVar() {
return releaseEnvVar;
}
public String getScmUserEnvVar() {
return scmUserEnvVar;
}
public String getScmPasswordEnvVar() {
return scmPasswordEnvVar;
}
public String getReleaseGoals() {
return StringUtils.isBlank(releaseGoals) ? DescriptorImpl.DEFAULT_RELEASE_GOALS : releaseGoals;
}
public String getDryRunGoals() {
return StringUtils.isBlank(dryRunGoals) ? DescriptorImpl.DEFAULT_DRYRUN_GOALS : dryRunGoals;
}
/**
* Hudson defines a method {@link Builder#getDescriptor()}, which returns the corresponding
* {@link Descriptor} object. Since we know that it's actually {@link DescriptorImpl}, override the method
* and give a better return type, so that we can access {@link DescriptorImpl} methods more easily. This is
* not necessary, but just a coding style preference.
*/
@Override
public DescriptorImpl getDescriptor() {
// see Descriptor javadoc for more about what a descriptor is.
return (DescriptorImpl) super.getDescriptor();
}
@Extension
public static class DescriptorImpl extends BuildWrapperDescriptor {
//public static final PermissionGroup PERMISSIONS = new PermissionGroup(M2ReleaseBuildWrapper.class, Messages._PermissionGroup_Title());
public static final Permission CREATE_RELEASE;
static {
Permission tmpPerm = null;
try {
// Jenkins changed the security model in a non backward compatible way :-(
// JENKINS-10661
Class<?> permissionScopeClass = Class.forName("hudson.security.PermissionScope");
Object psArr = Array.newInstance(permissionScopeClass, 2);
Field f;
f = permissionScopeClass.getDeclaredField("JENKINS");
Array.set(psArr, 0, f.get(null));
f = permissionScopeClass.getDeclaredField("ITEM");
Array.set(psArr, 1, f.get(null));
Constructor<Permission> ctor = Permission.class.getConstructor(PermissionGroup.class,
String.class,
Localizable.class,
Permission.class,
// boolean.class,
permissionScopeClass);
//permissionScopes.getClass());
tmpPerm = ctor.newInstance(Item.PERMISSIONS,
"Release",
Messages._CreateReleasePermission_Description(),
Hudson.ADMINISTER,
// true,
f.get(null));
LoggerFactory.getLogger(M2ReleaseBuildWrapper.class).info("Using new style Permission with PermissionScope");
}
// all these exceptions are Jenkins < 1.421 or Hudson
// wouldn't multicatch be nice!
catch (NoSuchMethodException ex) {
LoggerFactory.getLogger(M2ReleaseBuildWrapper.class).warn("Using Legacy Permission as new PermissionScope not detected. {}", ex.getMessage());
}
catch (InvocationTargetException ex) {
LoggerFactory.getLogger(M2ReleaseBuildWrapper.class).warn("Using Legacy Permission as new PermissionScope not detected. {}", ex.getMessage());
}
catch (IllegalArgumentException ex) {
LoggerFactory.getLogger(M2ReleaseBuildWrapper.class).warn("Using Legacy Permission as new PermissionScope not detected. {}", ex.getMessage());
}
catch (IllegalAccessException ex) {
LoggerFactory.getLogger(M2ReleaseBuildWrapper.class).warn("Using Legacy Permission as new PermissionScope not detected. {}", ex.getMessage());
}
catch (InstantiationException ex) {
LoggerFactory.getLogger(M2ReleaseBuildWrapper.class).warn("Using Legacy Permission as new PermissionScope not detected. {}", ex.getMessage());
}
catch (NoSuchFieldException ex) {
LoggerFactory.getLogger(M2ReleaseBuildWrapper.class).warn("Using Legacy Permission as new PermissionScope not detected. {}", ex.getMessage());
}
catch (ClassNotFoundException ex) {
LoggerFactory.getLogger(M2ReleaseBuildWrapper.class).warn("Using Legacy Permission as new PermissionScope not detected. {}", ex.getMessage());
}
if (tmpPerm == null) {
LoggerFactory.getLogger(M2ReleaseBuildWrapper.class).warn("Using Legacy Permission as new style permission with PermissionScope failed");
tmpPerm = new Permission(Item.PERMISSIONS,
"Release", //$NON-NLS-1$
Messages._CreateReleasePermission_Description(),
Hudson.ADMINISTER);
}
CREATE_RELEASE = tmpPerm;
}
public static final String DEFAULT_RELEASE_GOALS = "-Dresume=false release:prepare release:perform"; //$NON-NLS-1$
public static final String DEFAULT_DRYRUN_GOALS = "-Dresume=false -DdryRun=true release:prepare"; //$NON-NLS-1$
public static final String DEFAULT_RELEASE_ENVVAR = "IS_M2RELEASEBUILD"; //$NON-NLS-1$
public static final String DEFAULT_RELEASE_VERSION_ENVVAR = "MVN_RELEASE_VERSION"; //$NON-NLS-1$
public static final String DEFAULT_DEV_VERSION_ENVVAR = "MVN_DEV_VERSION"; //$NON-NLS-1$
public static final String DEFAULT_DRYRUN_ENVVAR = "MVN_ISDRYRUN"; //$NON-NLS-1$
public static final boolean DEFAULT_SELECT_CUSTOM_SCM_COMMENT_PREFIX = false;
public static final boolean DEFAULT_SELECT_APPEND_HUDSON_USERNAME = false;
public static final boolean DEFAULT_SELECT_SCM_CREDENTIALS = false;
private boolean nexusSupport = false;
private String nexusURL = null;
private String nexusUser = "deployment"; //$NON-NLS-1$
private String nexusPassword = "deployment123"; //$NON-NLS-1$
public DescriptorImpl() {
super(M2ReleaseBuildWrapper.class);
load();
}
@Override
public boolean isApplicable(AbstractProject<?, ?> item) {
return (item instanceof AbstractMavenProject);
}
@Override
public boolean configure(StaplerRequest staplerRequest, JSONObject json) throws FormException {
nexusSupport = json.containsKey("nexusSupport"); //$NON-NLS-1$
if (nexusSupport) {
JSONObject nexusParams = json.getJSONObject("nexusSupport"); //$NON-NLS-1$
nexusURL = Util.fixEmpty(nexusParams.getString("nexusURL")); //$NON-NLS-1$
if (nexusURL != null && nexusURL.endsWith("/")) { //$NON-NLS-1$
nexusURL = nexusURL.substring(0, nexusURL.length() - 1);
}
nexusUser = Util.fixEmpty(nexusParams.getString("nexusUser")); //$NON-NLS-1$
nexusPassword = nexusParams.getString("nexusPassword"); //$NON-NLS-1$
}
save();
return true; // indicate that everything is good so far
}
@Override
public String getDisplayName() {
return Messages.Wrapper_DisplayName();
}
public String getNexusURL() {
return nexusURL;
}
public String getNexusUser() {
return nexusUser;
}
public String getNexusPassword() {
return nexusPassword;
}
public boolean isNexusSupport() {
return nexusSupport;
}
/**
* Checks if the Nexus URL exists and we can authenticate against it.
*/
public FormValidation doUrlCheck(@QueryParameter String urlValue,
final @QueryParameter String usernameValue,
final @QueryParameter String passwordValue) throws IOException,
ServletException {
// this method can be used to check if a file exists anywhere in the file system,
// so it should be protected.
if (!Hudson.getInstance().hasPermission(Hudson.ADMINISTER)) {
return FormValidation.ok();
}
urlValue = Util.fixEmptyAndTrim(urlValue);
if (urlValue == null) {
return FormValidation.ok();
}
final String testURL;
if (urlValue.endsWith("/")) {
testURL = urlValue.substring(0, urlValue.length() - 1);
}
else {
testURL = urlValue;
}
URL url = null;
try {
url = new URL(testURL);
if (!(url.getProtocol().equals("http") || url.getProtocol().equals("https"))) {
return FormValidation.error("protocol must be http or https");
}
StageClient client = new StageClient(new URL(testURL), usernameValue, passwordValue);
client.checkAuthentication();
}
catch (MalformedURLException ex) {
return FormValidation.error(url + " is not a valid URL");
}
catch (StageException ex) {
FormValidation stageError = FormValidation.error(ex.getMessage());
stageError.initCause(ex);
return stageError;
}
return FormValidation.ok();
}
}
/**
* Evaluate if the current build should be a release build.
* @return <code>true</code> if this build is a release build.
*/
private boolean isReleaseBuild(@SuppressWarnings("rawtypes") AbstractBuild build) {
return (build.getCause(ReleaseCause.class) != null);
}
}
| true | true | public Environment setUp(@SuppressWarnings("rawtypes") AbstractBuild build, Launcher launcher, final BuildListener listener)
throws IOException,
InterruptedException {
if (!isReleaseBuild(build)) {
// we are not performing a release so don't need a custom tearDown.
return new Environment() {
/** intentionally blank */
@Override
public void buildEnvVars(Map<String, String> env) {
if (StringUtils.isNotBlank(releaseEnvVar)) {
// inform others that we are NOT doing a release build
env.put(releaseEnvVar, "false");
}
}
};
}
// we are a release build
M2ReleaseArgumentsAction args = build.getAction(M2ReleaseArgumentsAction.class);
StringBuilder buildGoals = new StringBuilder();
buildGoals.append("-DdevelopmentVersion=").append(args.getDevelopmentVersion()).append(' ');
buildGoals.append("-DreleaseVersion=").append(args.getReleaseVersion()).append(' ');
if (args.getScmUsername() != null) {
buildGoals.append("-Dusername=").append(args.getScmUsername()).append(' ');
}
if (args.getScmPassword() != null) {
buildGoals.append("-Dpassword=").append(args.getScmPassword()).append(' ');
}
if (args.getScmCommentPrefix() != null) {
buildGoals.append("\"-DscmCommentPrefix=");
buildGoals.append(args.getScmCommentPrefix());
if (args.isAppendHusonUserName()) {
buildGoals.append(String.format("(%s)", args.getHudsonUserName()));
}
buildGoals.append("\" ");
}
if (args.getScmTagName() != null) {
buildGoals.append("-Dtag=").append(args.getScmTagName()).append(' ');
}
if (args.isDryRun()) {
buildGoals.append(getDryRunGoals());
}
else {
buildGoals.append(getReleaseGoals());
}
build.addAction(new M2ReleaseArgumentInterceptorAction(buildGoals.toString()));
build.addAction(new M2ReleaseBadgeAction(args.getReleaseVersion(), args.isDryRun()));
return new Environment() {
@Override
public void buildEnvVars(Map<String, String> env) {
if (StringUtils.isNotBlank(releaseEnvVar)) {
// inform others that we are doing a release build
env.put(releaseEnvVar, "true");
}
}
@Override
public boolean tearDown(@SuppressWarnings("rawtypes") AbstractBuild bld, BuildListener lstnr)
throws IOException, InterruptedException {
boolean retVal = true;
final MavenModuleSet mmSet = getModuleSet(bld);
M2ReleaseArgumentsAction args = bld.getAction(M2ReleaseArgumentsAction.class);
if (args.isDryRun()) {
lstnr.getLogger().println("[M2Release] its only a dryRun, no need to mark it for keep");
}
if (bld.getResult() != null && bld.getResult().isBetterOrEqualTo(Result.SUCCESS) && !args.isDryRun()) {
// keep this build.
lstnr.getLogger().println("[M2Release] marking build to keep until the next release build");
bld.keepLog();
for (Run run : (RunList<? extends Run>) (bld.getProject().getBuilds())) {
M2ReleaseBadgeAction a = run.getAction(M2ReleaseBadgeAction.class);
if (a != null && run.getResult() == Result.SUCCESS && !a.isDryRun()) {
if (bld.getNumber() != run.getNumber()) {
lstnr.getLogger().println(
"[M2Release] removing keep build from build " + run.getNumber());
run.keepLog(false);
break;
}
}
}
}
if (args.isCloseNexusStage() && !args.isDryRun()) {
StageClient client = new StageClient(new URL(getDescriptor().getNexusURL()), getDescriptor()
.getNexusUser(), getDescriptor().getNexusPassword());
try {
MavenModule rootModule = mmSet.getRootModule();
// TODO grab the version that we have just released...
Stage stage = client.getOpenStageID(rootModule.getModuleName().groupId,
rootModule.getModuleName().artifactId, args.getReleaseVersion());
if (stage != null) {
lstnr.getLogger().println("[M2Release] Closing repository " + stage);
client.closeStage(stage, args.getRepoDescription());
lstnr.getLogger().println("[M2Release] Closed staging repository.");
}
else {
retVal = false;
lstnr.fatalError("[M2Release] Could not find nexus stage repository for project.\n");
}
}
catch (StageException ex) {
lstnr.fatalError("[M2Release] Could not close repository , %s\n", ex.toString());
log.error("[M2Release] Could not close repository", ex);
retVal = false;
}
}
return retVal;
}
};
}
| public Environment setUp(@SuppressWarnings("rawtypes") AbstractBuild build, Launcher launcher, final BuildListener listener)
throws IOException,
InterruptedException {
if (!isReleaseBuild(build)) {
// we are not performing a release so don't need a custom tearDown.
return new Environment() {
/** intentionally blank */
@Override
public void buildEnvVars(Map<String, String> env) {
if (StringUtils.isNotBlank(releaseEnvVar)) {
// inform others that we are NOT doing a release build
env.put(releaseEnvVar, "false");
}
}
};
}
// we are a release build
M2ReleaseArgumentsAction args = build.getAction(M2ReleaseArgumentsAction.class);
StringBuilder buildGoals = new StringBuilder();
buildGoals.append("-DdevelopmentVersion=").append(args.getDevelopmentVersion()).append(' ');
buildGoals.append("-DreleaseVersion=").append(args.getReleaseVersion()).append(' ');
if (args.getScmUsername() != null) {
buildGoals.append("-Dusername=").append(args.getScmUsername()).append(' ');
}
if (args.getScmPassword() != null) {
buildGoals.append("-Dpassword=").append(args.getScmPassword()).append(' ');
}
if (args.getScmCommentPrefix() != null) {
buildGoals.append("\"-DscmCommentPrefix=");
buildGoals.append(args.getScmCommentPrefix());
if (args.isAppendHusonUserName()) {
buildGoals.append(String.format("(%s)", args.getHudsonUserName()));
}
buildGoals.append("\" ");
}
if (args.getScmTagName() != null) {
buildGoals.append("-Dtag=").append(args.getScmTagName()).append(' ');
}
if (args.isDryRun()) {
buildGoals.append(getDryRunGoals());
}
else {
buildGoals.append(getReleaseGoals());
}
build.addAction(new M2ReleaseArgumentInterceptorAction(buildGoals.toString()));
build.addAction(new M2ReleaseBadgeAction(args.getReleaseVersion(), args.isDryRun()));
return new Environment() {
@Override
public void buildEnvVars(Map<String, String> env) {
if (StringUtils.isNotBlank(releaseEnvVar)) {
// inform others that we are doing a release build
env.put(releaseEnvVar, "true");
}
}
@Override
public boolean tearDown(@SuppressWarnings("rawtypes") AbstractBuild bld, BuildListener lstnr)
throws IOException, InterruptedException {
boolean retVal = true;
final MavenModuleSet mmSet = getModuleSet(bld);
M2ReleaseArgumentsAction args = bld.getAction(M2ReleaseArgumentsAction.class);
if (args.isDryRun()) {
lstnr.getLogger().println("[M2Release] its only a dryRun, no need to mark it for keep");
}
if (bld.getResult() != null && bld.getResult().isBetterOrEqualTo(Result.SUCCESS) && !args.isDryRun()) {
// keep this build.
lstnr.getLogger().println("[M2Release] marking build to keep until the next release build");
bld.keepLog();
for (Run run : (RunList<? extends Run>) (bld.getProject().getBuilds())) {
M2ReleaseBadgeAction a = run.getAction(M2ReleaseBadgeAction.class);
if (a != null && run.getResult() == Result.SUCCESS && !a.isDryRun()) {
if (bld.getNumber() != run.getNumber()) {
lstnr.getLogger().println(
"[M2Release] removing keep build from build " + run.getNumber());
run.keepLog(false);
break;
}
}
}
}
if (args.isCloseNexusStage() && !args.isDryRun()) {
StageClient client = new StageClient(new URL(getDescriptor().getNexusURL()), getDescriptor()
.getNexusUser(), getDescriptor().getNexusPassword());
try {
MavenModule rootModule = mmSet.getRootModule();
// TODO grab the version that we have just released...
Stage stage = client.getOpenStageID(rootModule.getModuleName().groupId,
rootModule.getModuleName().artifactId, args.getReleaseVersion());
if (stage != null) {
if (bld.getResult() != null && bld.getResult().isBetterOrEqualTo(Result.SUCCESS)) {
lstnr.getLogger().println("[M2Release] Closing repository " + stage);
client.closeStage(stage, args.getRepoDescription());
lstnr.getLogger().println("[M2Release] Closed staging repository.");
}
else {
lstnr.getLogger().println("[M2Release] Dropping repository " + stage);
client.closeStage(stage, args.getRepoDescription());
lstnr.getLogger().println("[M2Release] Dropped staging repository.");
}
}
else {
retVal = false;
lstnr.fatalError("[M2Release] Could not find nexus stage repository for project.\n");
}
}
catch (StageException ex) {
lstnr.fatalError("[M2Release] Could not close repository , %s\n", ex.toString());
log.error("[M2Release] Could not close repository", ex);
retVal = false;
}
}
return retVal;
}
};
}
|
diff --git a/de.hcl.synchronize/src/de/hcl/synchronize/client/MainSynchClient.java b/de.hcl.synchronize/src/de/hcl/synchronize/client/MainSynchClient.java
index a6c7c3d..c4d03cf 100644
--- a/de.hcl.synchronize/src/de/hcl/synchronize/client/MainSynchClient.java
+++ b/de.hcl.synchronize/src/de/hcl/synchronize/client/MainSynchClient.java
@@ -1,143 +1,143 @@
package de.hcl.synchronize.client;
import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;
import de.hcl.synchronize.api.IHCLClient;
import de.hcl.synchronize.api.IHCLServer;
import de.hcl.synchronize.api.IHCLSession;
import de.hcl.synchronize.log.HCLLogger;
import de.hcl.synchronize.log.IHCLLogListener.HCLType;
import de.hcl.synchronize.util.IniFile;
import de.newsystem.rmi.api.Server;
import de.newsystem.rmi.protokol.RemoteException;
/**
* The main synchronization client reads the configuration file and creates the
* clients.
*
* @author sebastian
*/
public class MainSynchClient {
/**
* Property name for session id
*/
public static final String SESSION_ID = "session";
/**
* Property name for location
*/
public static final String LOCATION = "location";
/**
* Property name for read only flag
*/
public static final String READ_ONLY = "readonly";
/**
* Property name for register at file system flag
*/
public static final String REGISTER_LISTENER = "registerlistener";
/**
* Property name for client name
*/
public static final String CLIENT_NAME = "clientname";
/**
* Property name for refresh rate in seconds
*/
public static final String REFRESH_RATE = "prefreshrate";
public static void main(String registry, String config_file) {
try {
Server s = Server.getServer();
s.forceConnectToRegistry(registry);
s.startServer(IHCLClient.CLIENT_PORT + 1);
IHCLServer server = forceGetHCLServer(s);
IniFile iniFile = new IniFile(new File(config_file));
String location = null;
for (String clientID : iniFile.getSections()) {
String sessionID = iniFile.getPropertyString(clientID,
SESSION_ID, "null");
location = iniFile.getPropertyString(clientID, LOCATION,
"/dev/null");
IHCLSession session = server.getSession(sessionID);
boolean readOnly = iniFile.getPropertyBool(clientID, READ_ONLY,
true);
boolean listener = iniFile.getPropertyBool(clientID,
REGISTER_LISTENER, false);
String clientName = iniFile.getPropertyString(clientID,
CLIENT_NAME, "null");
int refreshRate = iniFile.getPropertyInt(clientID,
REFRESH_RATE, Subfolder.MINIMAL_REFRESH_TIME_DIRECTORY);
IHCLClient client = null;
try {
if (listener)
client = new FatClient(location, clientName, session,
readOnly, refreshRate);
else
client = new HCLClient(location, clientName, readOnly,
refreshRate);
HCLLogger.performLog("Add client synchronization: '"
+ clientName + "'", HCLType.INFORMATION, null);
session.addClient(client);
} catch (IOException e) {
HCLLogger.performLog(
"Error create client synchronization: '"
- + clientName + "'", HCLType.ERROR, null);
+ + clientName + "': " + e.getMessage(), HCLType.ERROR, null);
continue;
}
}
HCLLogger.addListener(new HCLNotificator("Home Cloud Client",
location + File.separator));
} catch (RemoteException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* force get hcl server from registry. while the registry does not contain
* the server, retry every second.
*
* @param registryIp
* @return IHCLServer
* @throws UnknownHostException
* @throws IOException
* @throws RemoteException
* @throws InterruptedException
*/
private static IHCLServer forceGetHCLServer(Server s)
throws UnknownHostException, IOException, RemoteException,
InterruptedException {
IHCLServer server = (IHCLServer) s.find(IHCLServer.SERVER_ID,
IHCLServer.class);
long waitTime = 1000;
long maxTime = 1000 * 60 * 10;
while (server == null) {
server = (IHCLServer) s
.find(IHCLServer.SERVER_ID, IHCLServer.class);
HCLLogger.performLog("No hcl server in registry", HCLType.WARNING,
null);
Thread.sleep(waitTime);
waitTime *= 2;
if (waitTime > maxTime)
waitTime = maxTime;
}
return server;
}
}
| true | true | public static void main(String registry, String config_file) {
try {
Server s = Server.getServer();
s.forceConnectToRegistry(registry);
s.startServer(IHCLClient.CLIENT_PORT + 1);
IHCLServer server = forceGetHCLServer(s);
IniFile iniFile = new IniFile(new File(config_file));
String location = null;
for (String clientID : iniFile.getSections()) {
String sessionID = iniFile.getPropertyString(clientID,
SESSION_ID, "null");
location = iniFile.getPropertyString(clientID, LOCATION,
"/dev/null");
IHCLSession session = server.getSession(sessionID);
boolean readOnly = iniFile.getPropertyBool(clientID, READ_ONLY,
true);
boolean listener = iniFile.getPropertyBool(clientID,
REGISTER_LISTENER, false);
String clientName = iniFile.getPropertyString(clientID,
CLIENT_NAME, "null");
int refreshRate = iniFile.getPropertyInt(clientID,
REFRESH_RATE, Subfolder.MINIMAL_REFRESH_TIME_DIRECTORY);
IHCLClient client = null;
try {
if (listener)
client = new FatClient(location, clientName, session,
readOnly, refreshRate);
else
client = new HCLClient(location, clientName, readOnly,
refreshRate);
HCLLogger.performLog("Add client synchronization: '"
+ clientName + "'", HCLType.INFORMATION, null);
session.addClient(client);
} catch (IOException e) {
HCLLogger.performLog(
"Error create client synchronization: '"
+ clientName + "'", HCLType.ERROR, null);
continue;
}
}
HCLLogger.addListener(new HCLNotificator("Home Cloud Client",
location + File.separator));
} catch (RemoteException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
| public static void main(String registry, String config_file) {
try {
Server s = Server.getServer();
s.forceConnectToRegistry(registry);
s.startServer(IHCLClient.CLIENT_PORT + 1);
IHCLServer server = forceGetHCLServer(s);
IniFile iniFile = new IniFile(new File(config_file));
String location = null;
for (String clientID : iniFile.getSections()) {
String sessionID = iniFile.getPropertyString(clientID,
SESSION_ID, "null");
location = iniFile.getPropertyString(clientID, LOCATION,
"/dev/null");
IHCLSession session = server.getSession(sessionID);
boolean readOnly = iniFile.getPropertyBool(clientID, READ_ONLY,
true);
boolean listener = iniFile.getPropertyBool(clientID,
REGISTER_LISTENER, false);
String clientName = iniFile.getPropertyString(clientID,
CLIENT_NAME, "null");
int refreshRate = iniFile.getPropertyInt(clientID,
REFRESH_RATE, Subfolder.MINIMAL_REFRESH_TIME_DIRECTORY);
IHCLClient client = null;
try {
if (listener)
client = new FatClient(location, clientName, session,
readOnly, refreshRate);
else
client = new HCLClient(location, clientName, readOnly,
refreshRate);
HCLLogger.performLog("Add client synchronization: '"
+ clientName + "'", HCLType.INFORMATION, null);
session.addClient(client);
} catch (IOException e) {
HCLLogger.performLog(
"Error create client synchronization: '"
+ clientName + "': " + e.getMessage(), HCLType.ERROR, null);
continue;
}
}
HCLLogger.addListener(new HCLNotificator("Home Cloud Client",
location + File.separator));
} catch (RemoteException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
|
diff --git a/2waySMS/app/common/CodeSandbox.java b/2waySMS/app/common/CodeSandbox.java
index 7a7780a..7706a3f 100644
--- a/2waySMS/app/common/CodeSandbox.java
+++ b/2waySMS/app/common/CodeSandbox.java
@@ -1,415 +1,415 @@
package common;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.CtNewMethod;
import javassist.NotFoundException;
import play.Logger;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
import com.google.i18n.phonenumbers.geocoding.PhoneNumberOfflineGeocoder;
import com.marketo.mktows.client.MktServiceException;
import com.marketo.mktows.client.MktowsClientException;
import com.marketo.mktows.client.MktowsUtil;
import com.marketo.mktows.wsdl.ArrayOfAttribute;
import com.marketo.mktows.wsdl.LeadRecord;
import com.marketo.mktows.wsdl.SyncStatus;
public class CodeSandbox {
private MktowsClient client;
private String munchkinAccountId;
private Long campaignId;
public CodeSandbox(String accessKey, String secretKey,
String munchkinAccountId, Long campaignId) {
this.munchkinAccountId = munchkinAccountId;
this.campaignId = campaignId;
String hostName = munchkinAccountId + ".mktoapi.com";
client = new MktowsClient(accessKey, secretKey, hostName);
}
public List<LeadRecord> mktoCapitalizeField(List<LeadRecord> inflightList,
String[] fieldNames, boolean syncImmediate) {
List<LeadRecord> retList = new ArrayList<LeadRecord>();
LeadRecord retLead = null;
for (LeadRecord lr : inflightList) {
retLead = null;
retLead = mktoCapitalizeLeadField(lr, fieldNames, syncImmediate);
if (retLead != null) {
retList.add(retLead);
}
}
return retList;
}
public LeadRecord mktoCapitalizeLeadField(LeadRecord leadRecord,
String[] fieldNames, boolean syncImmediate) {
if (leadRecord == null) {
return null;
}
HashMap<String, String> newAttrs = new HashMap<String, String>();
boolean valueChanged = false;
String fld;
for (int i = 0; i < fieldNames.length; i++) {
fld = fieldNames[i].trim();
String fv = extractAttributeValue(leadRecord, fld);
String nfv = "";
if (fv != null) {
Character fch = fv.charAt(0);
String remainder = fv.substring(1);
if (fch != null) {
fch = Character.toUpperCase(fch);
}
if (remainder != null) {
remainder = remainder.toLowerCase();
}
nfv = fch + remainder;
newAttrs.put(fld, nfv);
- Logger.debug("Capitalizing %s to : %s", fld, fv);
+ Logger.debug("Capitalizing %s to : %s", fld, nfv);
if (!fv.equals(nfv)) {
Logger.debug("Value changed for lead id :%d",
leadRecord.getId());
valueChanged = true;
}
}
}
if (valueChanged) {
LeadRecord newLeadRecord = MktowsUtil.newLeadRecord(
leadRecord.getId(), null, null, null, newAttrs);
try {
if (syncImmediate) {
client.syncLead(newLeadRecord, null, false);
}
} catch (MktowsClientException e) {
Logger.error("Unable to sync lead with capitalized name:%s",
e.getMessage());
} catch (MktServiceException e) {
Logger.error("Unable to sync lead with capitalized name:%s",
e.getMessage());
}
return newLeadRecord;
}
return null;
}
public List<LeadRecord> mktoAddScores(List<LeadRecord> inflightList,
String storeNewValue, String score1, String score2) {
List<LeadRecord> retList = new ArrayList<LeadRecord>();
LeadRecord retLead = null;
for (LeadRecord lr : inflightList) {
retLead = null;
retLead = mktoAddLeadScores(lr, false, storeNewValue, score1, score2);
if (retLead != null) {
retList.add(retLead);
}
}
return retList;
}
public LeadRecord mktoAddLeadScores(LeadRecord leadRecord,
boolean syncImmediate, String storeNewValue, String score1,
String score2) {
if (leadRecord == null) {
return null;
}
try {
Logger.debug("About to add scores %s and %s and store it in %s",
score1, score2, storeNewValue);
float sc1 = 0;
float sc2 = 0;
HashMap<String, String> newAttrs = new HashMap<String, String>();
String sc1Str = extractAttributeValue(leadRecord, score1);
String sc2Str = extractAttributeValue(leadRecord, score2);
String sc3Str = extractAttributeValue(leadRecord, storeNewValue);
if (sc1Str != null) {
Logger.debug("value of %s is %s", score1, sc1Str);
sc1 = Float.valueOf(sc1Str);
}
if (sc2Str != null) {
Logger.debug("value of %s is %s", score2, sc2Str);
sc2 = Float.valueOf(sc2Str);
}
float newScore = sc1 + sc2;
Logger.debug("New score is %f", newScore);
if (newScore != Float.valueOf(sc3Str)) {
newAttrs.put(storeNewValue, String.valueOf(newScore));
LeadRecord newLeadRecord = MktowsUtil.newLeadRecord(
leadRecord.getId(), null, null, null, newAttrs);
if (syncImmediate) {
client.syncLead(newLeadRecord, null, false);
}
return newLeadRecord;
}
} catch (MktowsClientException e) {
Logger.error("Marketo Server Exception : %s", e.getMessage());
} catch (MktServiceException e) {
Logger.error("Marketo Server Exception : %s", e.getMessage());
}
return null;
}
public List<LeadRecord> mktoGeocodePhone(List<LeadRecord> inflightList,
String phoneField, String regionField) {
List<LeadRecord> retList = new ArrayList<LeadRecord>();
LeadRecord retLead = null;
for (LeadRecord lr : inflightList) {
retLead = null;
retLead = mktoGeocodeLeadPhone(lr, false, phoneField, regionField);
if (retLead != null) {
retList.add(retLead);
}
}
return retList;
}
private LeadRecord mktoGeocodeLeadPhone(LeadRecord leadRecord,
boolean syncImmediate, String phoneField, String regionField) {
if (leadRecord == null) {
return null;
}
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
PhoneNumberOfflineGeocoder geocoder = PhoneNumberOfflineGeocoder
.getInstance();
try {
Logger.debug("About to geolocate number in field %s", phoneField);
HashMap<String, String> newAttrs = new HashMap<String, String>();
String region = null;
String oldRegion = extractAttributeValue(leadRecord, regionField);
String pn = extractAttributeValue(leadRecord, phoneField);
Logger.debug("Phone number is %s", pn);
PhoneNumber phoneObj = phoneUtil.parse(pn, "US");
region = geocoder.getDescriptionForNumber(phoneObj, Locale.ENGLISH);
Logger.debug("Region for phone %s is %s. old region is %s", pn,
region, oldRegion);
if (!region.equals("") && !region.equals(oldRegion)) {
newAttrs.put(regionField, region);
LeadRecord newLeadRecord = MktowsUtil.newLeadRecord(
leadRecord.getId(), null, null, null, newAttrs);
if (syncImmediate) {
client.syncLead(newLeadRecord, null, false);
}
return newLeadRecord;
}
} catch (MktowsClientException e) {
Logger.error("Marketo Server Exception : %s", e.getMessage());
} catch (MktServiceException e) {
Logger.error("Marketo Server Exception : %s", e.getMessage());
} catch (NumberParseException e) {
Logger.error("Phone number parse Exception : %s", e.getMessage());
}
return null;
}
public List<LeadRecord> mktoPhoneFormat(List<LeadRecord> inflightList,
String phoneField, String formatType) {
List<LeadRecord> retList = new ArrayList<LeadRecord>();
LeadRecord retLead = null;
for (LeadRecord lr : inflightList) {
retLead = null;
retLead = mktoLeadPhoneFormat(lr, false, phoneField, formatType);
if (retLead != null) {
retList.add(retLead);
}
}
return retList;
}
private LeadRecord mktoLeadPhoneFormat(LeadRecord leadRecord,
boolean syncImmediate, String phoneField, String formatType) {
if (leadRecord == null) {
return null;
}
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
PhoneNumberOfflineGeocoder geocoder = PhoneNumberOfflineGeocoder
.getInstance();
try {
Logger.debug("About to format number in field %s", phoneField);
HashMap<String, String> newAttrs = new HashMap<String, String>();
String region = null;
String opn = extractAttributeValue(leadRecord, phoneField);
Logger.debug("Phone number is %s", opn);
PhoneNumber phoneObj = phoneUtil.parse(opn, "US");
String npn = "";
if (formatType.equalsIgnoreCase(Constants.PHONE_FORMAT_E164)) {
npn = phoneUtil.format(phoneObj, PhoneNumberFormat.E164);
} else if (formatType
.equalsIgnoreCase(Constants.PHONE_FORMAT_INTERNATIONAL)) {
npn = phoneUtil.format(phoneObj,
PhoneNumberFormat.INTERNATIONAL);
} else if (formatType
.equalsIgnoreCase(Constants.PHONE_FORMAT_NATIONAL)) {
npn = phoneUtil.format(phoneObj, PhoneNumberFormat.NATIONAL);
}
Logger.debug("Format for phone %s is %s.", opn, npn);
if (!npn.equals("") && !npn.equals(opn)) {
newAttrs.put(phoneField, npn);
LeadRecord newLeadRecord = MktowsUtil.newLeadRecord(
leadRecord.getId(), null, null, null, newAttrs);
if (syncImmediate) {
client.syncLead(newLeadRecord, null, false);
}
return newLeadRecord;
}
} catch (MktowsClientException e) {
Logger.error("Marketo Server Exception : %s", e.getMessage());
} catch (MktServiceException e) {
Logger.error("Marketo Server Exception : %s", e.getMessage());
} catch (NumberParseException e) {
Logger.error("Phone number parse Exception : %s", e.getMessage());
}
return null;
}
private String extractAttributeValue(LeadRecord leadRecord, String fieldName) {
if (leadRecord == null) {
return null;
}
if (fieldName.equals(";")) {
Logger.debug("Dropping trailing ;");
}
Logger.debug("About to extract value of %s", fieldName);
Map<String, Object> attrMap = null;
ArrayOfAttribute aoAttribute = leadRecord.getLeadAttributeList();
if (aoAttribute != null) {
attrMap = MktowsUtil.getLeadAttributeMap(aoAttribute);
if (attrMap != null && !attrMap.isEmpty()) {
Set<String> keySet = attrMap.keySet();
if (keySet.contains(fieldName)) {
String fieldValue = attrMap.get(fieldName).toString();
Logger.debug("%s field is set to %s", fieldName, fieldValue);
return fieldValue;
}
}
}
return null;
}
public CtClass createClass(String className) {
ClassPool pool = ClassPool.getDefault();
CtClass mktoClass = null;
try {
pool.importPackage("com.marketo.mktows.wsdl");
pool.importPackage("com.marketo.mktows.client");
pool.importPackage("java.util");
mktoClass = pool.get(className);
} catch (NotFoundException e) {
Logger.debug("Did not find class :%s. Will create new one",
className);
mktoClass = pool.makeClass(className);
}
return mktoClass;
}
public boolean methodExists(CtClass mktoClass, String methodName) {
CtMethod[] methods = mktoClass.getMethods();
for (CtMethod method : methods) {
if (method.getName().equals(methodName)) {
Logger.debug("Found method %s in class", methodName);
return true;
}
}
return false;
}
public String addMethod(CtClass mktoClass, String methodDefinition) {
try {
// only call if method does NOT exist
String methodName = getMethodName();
String fullMethodDefn = "public LeadRecord " + methodName
+ "(LeadRecord leadRecord) {" + methodDefinition + "}";
Logger.debug("Adding new method to class:%s", fullMethodDefn);
mktoClass.addMethod(CtNewMethod.make(fullMethodDefn, mktoClass));
return methodName;
} catch (CannotCompileException e) {
Logger.error("Unable to compile : %s", e.getMessage());
return null;
}
}
public List<LeadRecord> executeMethod(Class clazz, String methodName,
List<LeadRecord> inflightList) {
List<LeadRecord> retList = new ArrayList<LeadRecord>();
LeadRecord retLead = null;
for (LeadRecord lr : inflightList) {
retLead = null;
retLead = executeMethod(clazz, methodName, lr);
if (retLead != null) {
retList.add(retLead);
}
}
return retList;
}
public LeadRecord executeMethod(Class clazz, String methodName,
LeadRecord leadRecord) {
try {
Object obj = clazz.newInstance();
Class[] formalParams = new Class[] { LeadRecord.class };
Method meth = clazz.getDeclaredMethod(methodName, formalParams);
Object[] actualParams = new Object[] { leadRecord };
LeadRecord result = ((LeadRecord) meth.invoke(obj, actualParams));
return result;
} catch (InstantiationException e) {
Logger.error("Unable to instantiate : %s", e.getMessage());
} catch (IllegalAccessException e) {
Logger.error("Illegal Access : %s", e.getMessage());
} catch (NoSuchMethodException e) {
Logger.error("No Such Method : %s", e.getMessage());
} catch (SecurityException e) {
Logger.error("Security Exception : %s", e.getMessage());
} catch (IllegalArgumentException e) {
Logger.error("Illegal Argument : %s", e.getMessage());
} catch (InvocationTargetException e) {
Logger.error("Invocation Target Exception : %s", e.getMessage());
}
return null;
}
public List<SyncStatus> syncMultipleLeads(
List<LeadRecord> processedLeadList, boolean dedupEnabled) {
try {
Logger.debug("About to sync %d leads", processedLeadList.size());
if (processedLeadList.size() == 0) {
return null;
}
List<SyncStatus> status = client.syncMultipleLeads(
processedLeadList, dedupEnabled);
Logger.debug("Finished sync-ing %d leads", processedLeadList.size());
return status;
} catch (MktowsClientException e) {
Logger.error("Marketo Client Exception : %s", e.getMessage());
} catch (MktServiceException e) {
Logger.error("Marketo Server Exception : %s", e.getMessage());
}
return null;
}
public String getMethodName() {
return ("eval" + this.munchkinAccountId + this.campaignId).replace("-",
"_");
}
}
| true | true | public LeadRecord mktoCapitalizeLeadField(LeadRecord leadRecord,
String[] fieldNames, boolean syncImmediate) {
if (leadRecord == null) {
return null;
}
HashMap<String, String> newAttrs = new HashMap<String, String>();
boolean valueChanged = false;
String fld;
for (int i = 0; i < fieldNames.length; i++) {
fld = fieldNames[i].trim();
String fv = extractAttributeValue(leadRecord, fld);
String nfv = "";
if (fv != null) {
Character fch = fv.charAt(0);
String remainder = fv.substring(1);
if (fch != null) {
fch = Character.toUpperCase(fch);
}
if (remainder != null) {
remainder = remainder.toLowerCase();
}
nfv = fch + remainder;
newAttrs.put(fld, nfv);
Logger.debug("Capitalizing %s to : %s", fld, fv);
if (!fv.equals(nfv)) {
Logger.debug("Value changed for lead id :%d",
leadRecord.getId());
valueChanged = true;
}
}
}
if (valueChanged) {
LeadRecord newLeadRecord = MktowsUtil.newLeadRecord(
leadRecord.getId(), null, null, null, newAttrs);
try {
if (syncImmediate) {
client.syncLead(newLeadRecord, null, false);
}
} catch (MktowsClientException e) {
Logger.error("Unable to sync lead with capitalized name:%s",
e.getMessage());
} catch (MktServiceException e) {
Logger.error("Unable to sync lead with capitalized name:%s",
e.getMessage());
}
return newLeadRecord;
}
return null;
}
| public LeadRecord mktoCapitalizeLeadField(LeadRecord leadRecord,
String[] fieldNames, boolean syncImmediate) {
if (leadRecord == null) {
return null;
}
HashMap<String, String> newAttrs = new HashMap<String, String>();
boolean valueChanged = false;
String fld;
for (int i = 0; i < fieldNames.length; i++) {
fld = fieldNames[i].trim();
String fv = extractAttributeValue(leadRecord, fld);
String nfv = "";
if (fv != null) {
Character fch = fv.charAt(0);
String remainder = fv.substring(1);
if (fch != null) {
fch = Character.toUpperCase(fch);
}
if (remainder != null) {
remainder = remainder.toLowerCase();
}
nfv = fch + remainder;
newAttrs.put(fld, nfv);
Logger.debug("Capitalizing %s to : %s", fld, nfv);
if (!fv.equals(nfv)) {
Logger.debug("Value changed for lead id :%d",
leadRecord.getId());
valueChanged = true;
}
}
}
if (valueChanged) {
LeadRecord newLeadRecord = MktowsUtil.newLeadRecord(
leadRecord.getId(), null, null, null, newAttrs);
try {
if (syncImmediate) {
client.syncLead(newLeadRecord, null, false);
}
} catch (MktowsClientException e) {
Logger.error("Unable to sync lead with capitalized name:%s",
e.getMessage());
} catch (MktServiceException e) {
Logger.error("Unable to sync lead with capitalized name:%s",
e.getMessage());
}
return newLeadRecord;
}
return null;
}
|
diff --git a/FlexAscParser/src_converter/Main2.java b/FlexAscParser/src_converter/Main2.java
index cf541b1..21a6071 100644
--- a/FlexAscParser/src_converter/Main2.java
+++ b/FlexAscParser/src_converter/Main2.java
@@ -1,2677 +1,2681 @@
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import macromedia.asc.parser.ApplyTypeExprNode;
import macromedia.asc.parser.ArgumentListNode;
import macromedia.asc.parser.BinaryExpressionNode;
import macromedia.asc.parser.BreakStatementNode;
import macromedia.asc.parser.CallExpressionNode;
import macromedia.asc.parser.CaseLabelNode;
import macromedia.asc.parser.ClassDefinitionNode;
import macromedia.asc.parser.CoerceNode;
import macromedia.asc.parser.ConditionalExpressionNode;
import macromedia.asc.parser.DeleteExpressionNode;
import macromedia.asc.parser.DoStatementNode;
import macromedia.asc.parser.ExpressionStatementNode;
import macromedia.asc.parser.ForStatementNode;
import macromedia.asc.parser.FunctionCommonNode;
import macromedia.asc.parser.FunctionDefinitionNode;
import macromedia.asc.parser.FunctionNameNode;
import macromedia.asc.parser.GetExpressionNode;
import macromedia.asc.parser.HasNextNode;
import macromedia.asc.parser.IdentifierNode;
import macromedia.asc.parser.IfStatementNode;
import macromedia.asc.parser.ImportDirectiveNode;
import macromedia.asc.parser.IncrementNode;
import macromedia.asc.parser.InterfaceDefinitionNode;
import macromedia.asc.parser.ListNode;
import macromedia.asc.parser.LiteralArrayNode;
import macromedia.asc.parser.LiteralBooleanNode;
import macromedia.asc.parser.LiteralNullNode;
import macromedia.asc.parser.LiteralNumberNode;
import macromedia.asc.parser.LiteralObjectNode;
import macromedia.asc.parser.LiteralRegExpNode;
import macromedia.asc.parser.LiteralStringNode;
import macromedia.asc.parser.MemberExpressionNode;
import macromedia.asc.parser.MetaDataNode;
import macromedia.asc.parser.Node;
import macromedia.asc.parser.PackageDefinitionNode;
import macromedia.asc.parser.ParameterListNode;
import macromedia.asc.parser.ParameterNode;
import macromedia.asc.parser.Parser;
import macromedia.asc.parser.ProgramNode;
import macromedia.asc.parser.QualifiedIdentifierNode;
import macromedia.asc.parser.ReturnStatementNode;
import macromedia.asc.parser.SelectorNode;
import macromedia.asc.parser.SetExpressionNode;
import macromedia.asc.parser.StatementListNode;
import macromedia.asc.parser.StoreRegisterNode;
import macromedia.asc.parser.SuperExpressionNode;
import macromedia.asc.parser.SuperStatementNode;
import macromedia.asc.parser.SwitchStatementNode;
import macromedia.asc.parser.ThisExpressionNode;
import macromedia.asc.parser.ThrowStatementNode;
import macromedia.asc.parser.Tokens;
import macromedia.asc.parser.TryStatementNode;
import macromedia.asc.parser.UnaryExpressionNode;
import macromedia.asc.parser.VariableBindingNode;
import macromedia.asc.parser.VariableDefinitionNode;
import macromedia.asc.parser.WhileStatementNode;
import macromedia.asc.util.Context;
import macromedia.asc.util.ContextStatics;
import macromedia.asc.util.ObjectList;
import bc.builtin.BuiltinClasses;
import bc.code.FileWriteDestination;
import bc.code.ListWriteDestination;
import bc.code.WriteDestination;
import bc.help.BcCodeCs;
import bc.help.BcNodeHelper;
import bc.lang.BcClassDefinitionNode;
import bc.lang.BcFuncParam;
import bc.lang.BcFunctionDeclaration;
import bc.lang.BcFunctionTypeNode;
import bc.lang.BcInterfaceDefinitionNode;
import bc.lang.BcTypeNode;
import bc.lang.BcVariableDeclaration;
import bc.lang.BcVectorTypeNode;
public class Main2
{
private static FileWriteDestination src;
private static ListWriteDestination impl;
private static WriteDestination dest;
private static Stack<WriteDestination> destStack;
private static String packageName;
private static BcClassDefinitionNode lastBcClass;
private static BcFunctionDeclaration lastBcFunction;
private static final String classObject = "Object";
private static final String classString = "String";
private static final String classVector = "Vector";
private static final String classArray = "Array";
private static final String classDictionary = "Dictionary";
private static final String classFunction = "Function";
private static final String classXML = "XML";
private static final String classXMLList = "XMLList";
private static final String classBoolean = "Boolean";
private static List<BcVariableDeclaration> declaredVars;
private static List<BcClassDefinitionNode> bcClasses;
private static List<BcClassDefinitionNode> bcApiClasses;
private static Map<String, BcFunctionDeclaration> bcBuitinFunctions; // top level functions
static
{
bcBuitinFunctions = new HashMap<String, BcFunctionDeclaration>();
try
{
List<BcClassDefinitionNode> classes = BuiltinClasses.load(new File("api/src"));
for (BcClassDefinitionNode bcClass : classes)
{
if (bcClass.getName().equals(BuiltinClasses.TOPLEVEL_DUMMY_CLASS_NAME))
{
List<BcFunctionDeclaration> bcTopLevelFunctions = bcClass.getFunctions();
for (BcFunctionDeclaration bcFunc : bcTopLevelFunctions)
{
bcBuitinFunctions.put(bcFunc.getName(), bcFunc);
}
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
BcFunctionDeclaration.thisCallMarker = BcCodeCs.thisCallMarker;
BcFunctionDeclaration.superCallMarker = BcCodeCs.superCallMarker;
File outputDir = new File(args[0]);
String[] filenames = new String[args.length - 1];
System.arraycopy(args, 1, filenames, 0, filenames.length);
try
{
bcClasses = new ArrayList<BcClassDefinitionNode>();
collect(new File("api/src")); // collect api classes
bcApiClasses = bcClasses;
bcClasses = new ArrayList<BcClassDefinitionNode>();
collect(filenames);
process();
write(outputDir, bcApiClasses);
write(outputDir, bcClasses);
}
catch (IOException e)
{
e.printStackTrace();
}
}
private static void collect(String... filenames) throws IOException
{
for (int i = 0; i < filenames.length; ++i)
{
collect(new File(filenames[i]));
}
}
private static void collect(File file) throws IOException
{
if (file.isDirectory())
{
File[] files = file.listFiles(new FileFilter()
{
@Override
public boolean accept(File pathname)
{
String filename = pathname.getName();
if (pathname.isDirectory())
return !filename.equals(".svn");
return filename.endsWith(".as");
}
});
for (File child : files)
{
collect(child);
}
}
else
{
collectSource(file);
}
}
private static void collectSource(File file) throws IOException
{
ContextStatics statics = new ContextStatics();
Context cx = new Context(statics);
FileInputStream in = new FileInputStream(file);
Parser parser = new Parser(cx, in, file.getPath());
ProgramNode programNode = parser.parseProgram();
in.close();
// NodePrinter printer = new NodePrinter();
// printer.evaluate(cx, programNode);
packageName = null;
for (Node node : programNode.statements.items)
{
dest = new ListWriteDestination();
destStack = new Stack<WriteDestination>();
if (node instanceof InterfaceDefinitionNode)
{
BcInterfaceDefinitionNode bcInterface = collect((InterfaceDefinitionNode) node);
bcClasses.add(bcInterface);
}
else if (node instanceof ClassDefinitionNode)
{
BcClassDefinitionNode bcClass = collect((ClassDefinitionNode) node);
bcClasses.add(bcClass);
}
else if (node instanceof PackageDefinitionNode)
{
if (packageName == null)
{
PackageDefinitionNode packageNode = (PackageDefinitionNode) node;
String packageNameString = packageNode.name.id.pkg_part;
if (packageNameString.length() > 0)
{
packageName = packageNameString;
}
}
}
else if (node instanceof MetaDataNode || node instanceof ImportDirectiveNode)
{
// nothing
}
}
}
private static BcInterfaceDefinitionNode collect(InterfaceDefinitionNode interfaceDefinitionNode)
{
String interfaceDeclaredName = BcCodeCs.identifier(interfaceDefinitionNode.name);
declaredVars = new ArrayList<BcVariableDeclaration>();
BcTypeNode interfaceType = BcTypeNode.create(interfaceDeclaredName);
BcInterfaceDefinitionNode bcInterface = new BcInterfaceDefinitionNode(interfaceType);
bcInterface.setPackageName(packageName);
bcInterface.setDeclaredVars(declaredVars);
lastBcClass = bcInterface;
ObjectList<Node> items = interfaceDefinitionNode.statements.items;
// collect the stuff
for (Node node : items)
{
if (node instanceof FunctionDefinitionNode)
{
bcInterface.add(collect((FunctionDefinitionNode) node));
}
else
{
assert false;
}
}
lastBcClass = null;
return bcInterface;
}
private static BcClassDefinitionNode collect(ClassDefinitionNode classDefinitionNode)
{
String classDeclaredName = BcCodeCs.identifier(classDefinitionNode.name);
declaredVars = new ArrayList<BcVariableDeclaration>();
BcTypeNode classType = BcTypeNode.create(classDeclaredName);
BcClassDefinitionNode bcClass = new BcClassDefinitionNode(classType);
bcClass.setPackageName(packageName);
bcClass.setDeclaredVars(declaredVars);
lastBcClass = bcClass;
// super type
Node baseclass = classDefinitionNode.baseclass;
if (baseclass == null)
{
BcTypeNode typeObject = BcTypeNode.create(classObject);
if (classType != typeObject)
{
bcClass.setExtendsType(typeObject);
}
}
else
{
BcTypeNode bcSuperType = extractBcType(baseclass);
bcClass.setExtendsType(bcSuperType);
}
// interfaces
if (classDefinitionNode.interfaces != null)
{
for (Node interfaceNode : classDefinitionNode.interfaces.items)
{
BcTypeNode interfaceType = extractBcType(interfaceNode);
bcClass.addInterface(interfaceType);
}
}
// collect members
ObjectList<Node> items = classDefinitionNode.statements.items;
for (Node node : items)
{
if (node instanceof FunctionDefinitionNode)
{
bcClass.add(collect((FunctionDefinitionNode) node));
}
else if (node instanceof VariableDefinitionNode)
{
bcClass.add(collect((VariableDefinitionNode)node));
}
else if (node instanceof MetaDataNode)
{
}
else if (node instanceof ExpressionStatementNode)
{
assert false : "Top level ExpressionStatementNode";
}
else
{
assert false : node.getClass();
}
}
lastBcClass = null;
declaredVars = null;
return bcClass;
}
private static BcVariableDeclaration collect(VariableDefinitionNode node)
{
assert node.list.items.size() == 1 : node.list.items.size();
VariableBindingNode varBindNode = (VariableBindingNode) node.list.items.get(0);
BcTypeNode bcType = extractBcType(varBindNode.variable.type);
String bcIdentifier = BcCodeCs.identifier(varBindNode.variable.identifier);
BcVariableDeclaration bcVar = new BcVariableDeclaration(bcType, bcIdentifier);
bcVar.setConst(node.kind == Tokens.CONST_TOKEN);
bcVar.setModifiers(BcNodeHelper.extractModifiers(varBindNode.attrs));
bcVar.setInitializerNode(varBindNode.initializer);
declaredVars.add(bcVar);
return bcVar;
}
private static BcFunctionDeclaration collect(FunctionDefinitionNode functionDefinitionNode)
{
FunctionNameNode functionNameNode = functionDefinitionNode.name;
String name = BcCodeCs.identifier(functionNameNode.identifier);
BcFunctionDeclaration bcFunc = new BcFunctionDeclaration(name);
if (functionNameNode.kind == Tokens.GET_TOKEN)
{
bcFunc.setGetter();
}
else if(functionNameNode.kind == Tokens.SET_TOKEN)
{
bcFunc.setSetter();
}
boolean isConstructor = lastBcClass != null && name.equals(lastBcClass.getName());
bcFunc.setConstructorFlag(isConstructor);
bcFunc.setModifiers(BcNodeHelper.extractModifiers(functionDefinitionNode.attrs));
ArrayList<BcVariableDeclaration> declaredVars = new ArrayList<BcVariableDeclaration>();
bcFunc.setDeclaredVars(declaredVars);
// get function params
ParameterListNode parameterNode = functionDefinitionNode.fexpr.signature.parameter;
if (parameterNode != null)
{
ObjectList<ParameterNode> params = parameterNode.items;
for (ParameterNode param : params)
{
BcFuncParam bcParam = new BcFuncParam(extractBcType(param.type), BcCodeCs.identifier(param.identifier));
if (param.init != null)
{
bcParam.setDefaultInitializer(param.init);
}
bcFunc.addParam(bcParam);
declaredVars.add(bcParam);
}
}
// get function return type
Node returnTypeNode = functionDefinitionNode.fexpr.signature.result;
if (returnTypeNode != null)
{
BcTypeNode bcReturnType = extractBcType(returnTypeNode);
bcFunc.setReturnType(bcReturnType);
}
bcFunc.setStatements(functionDefinitionNode.fexpr.body);
return bcFunc;
}
private static void process()
{
Collection<BcTypeNode> values = BcTypeNode.uniqueTypes.values();
for (BcTypeNode type : values)
{
process(type);
}
process(new ArrayList<BcClassDefinitionNode>(bcApiClasses));
process(bcClasses);
}
private static void process(List<BcClassDefinitionNode> classes)
{
for (BcClassDefinitionNode bcClass : classes)
{
bcMembersTypesStack = new Stack<BcTypeNode>();
if (bcClass.isInterface())
{
process((BcInterfaceDefinitionNode)bcClass);
}
else
{
process(bcClass);
}
}
}
private static void process(BcInterfaceDefinitionNode bcInterface)
{
declaredVars = bcInterface.getDeclaredVars();
}
private static void process(BcClassDefinitionNode bcClass)
{
System.out.println("Process: " + bcClass.getName());
declaredVars = bcClass.getDeclaredVars();
lastBcClass = bcClass;
List<BcVariableDeclaration> fields = bcClass.getFields();
for (BcVariableDeclaration bcField : fields)
{
process(bcField);
}
List<BcFunctionDeclaration> functions = bcClass.getFunctions();
for (BcFunctionDeclaration bcFunc : functions)
{
process(bcFunc);
}
lastBcClass = null;
declaredVars = null;
}
private static void process(BcVariableDeclaration bcVar)
{
BcTypeNode varType = bcVar.getType();
String varId = bcVar.getIdentifier();
dest.writef("%s %s", BcCodeCs.type(varType.getName()), BcCodeCs.identifier(varId));
Node initializer = bcVar.getInitializerNode();
if (initializer != null)
{
ListWriteDestination initializerDest = new ListWriteDestination();
pushDest(initializerDest);
process(initializer);
popDest();
bcVar.setInitializer(initializerDest);
bcVar.setIntegralInitializerFlag(BcNodeHelper.isIntegralLiteralNode(initializer));
dest.write(" = " + initializerDest);
}
dest.writeln(";");
}
private static void process(Node node)
{
assert node != null;
if (node instanceof MemberExpressionNode)
process((MemberExpressionNode)node);
else if (node instanceof SelectorNode)
process((SelectorNode)node);
else if (node instanceof IdentifierNode)
process((IdentifierNode)node);
else if (node instanceof ExpressionStatementNode)
process((ExpressionStatementNode)node);
else if (node instanceof VariableBindingNode)
process((VariableBindingNode)node);
else if (node instanceof VariableDefinitionNode)
process((VariableDefinitionNode)node);
else if (node instanceof LiteralNumberNode ||
node instanceof LiteralBooleanNode ||
node instanceof LiteralNullNode ||
node instanceof LiteralObjectNode ||
node instanceof LiteralStringNode ||
node instanceof LiteralRegExpNode ||
node instanceof LiteralArrayNode)
processLiteral(node);
else if (node instanceof BinaryExpressionNode)
process((BinaryExpressionNode)node);
else if (node instanceof UnaryExpressionNode)
process((UnaryExpressionNode)node);
else if (node instanceof IfStatementNode)
process((IfStatementNode)node);
else if (node instanceof ConditionalExpressionNode)
process((ConditionalExpressionNode)node);
else if (node instanceof WhileStatementNode)
process((WhileStatementNode)node);
else if (node instanceof ForStatementNode)
process((ForStatementNode)node);
else if (node instanceof DoStatementNode)
process((DoStatementNode)node);
else if (node instanceof SwitchStatementNode)
process((SwitchStatementNode)node);
else if (node instanceof TryStatementNode)
process((TryStatementNode)node);
else if (node instanceof ReturnStatementNode)
process((ReturnStatementNode)node);
else if (node instanceof BreakStatementNode)
process((BreakStatementNode)node);
else if (node instanceof ThisExpressionNode)
process((ThisExpressionNode)node);
else if (node instanceof SuperExpressionNode)
process((SuperExpressionNode)node);
else if (node instanceof ThrowStatementNode)
process((ThrowStatementNode)node);
else if (node instanceof SuperStatementNode)
process((SuperStatementNode)node);
else if (node instanceof ListNode)
process((ListNode)node);
else if (node instanceof StatementListNode)
process((StatementListNode)node);
else if (node instanceof ArgumentListNode)
process((ArgumentListNode)node);
else if (node instanceof FunctionCommonNode)
process((FunctionCommonNode)node);
else
assert false : node.getClass();
}
private static void process(StatementListNode statementsNode)
{
writeBlockOpen(dest);
ObjectList<Node> items = statementsNode.items;
for (Node node : items)
{
process(node);
}
writeBlockClose(dest);
}
private static void process(ArgumentListNode node)
{
int itemIndex = 0;
for (Node arg : node.items)
{
process(arg);
if (++itemIndex < node.items.size())
{
dest.write(", ");
}
}
}
private static void process(FunctionCommonNode node)
{
System.err.println("Fix me!!! FunctionCommonNode");
assert false;
}
private static BcVariableDeclaration process(VariableDefinitionNode node)
{
VariableBindingNode varBindNode = (VariableBindingNode) node.list.items.get(0);
BcTypeNode varType = extractBcType(varBindNode.variable.type);
String bcIdentifier = BcCodeCs.identifier(varBindNode.variable.identifier);
BcVariableDeclaration bcVar = new BcVariableDeclaration(varType, bcIdentifier);
bcVar.setConst(node.kind == Tokens.CONST_TOKEN);
bcVar.setModifiers(BcNodeHelper.extractModifiers(varBindNode.attrs));
dest.writef("%s %s", BcCodeCs.type(varType.getName()), BcCodeCs.identifier(bcIdentifier));
if (varBindNode.initializer != null)
{
ListWriteDestination initializer = new ListWriteDestination();
pushDest(initializer);
process(varBindNode.initializer);
popDest();
bcVar.setInitializer(initializer);
bcVar.setIntegralInitializerFlag(BcNodeHelper.isIntegralLiteralNode(varBindNode.initializer));
dest.write(" = " + initializer);
}
dest.writeln(";");
declaredVars.add(bcVar);
return bcVar;
}
// dirty hack: we need to check the recursion depth
private static BcTypeNode lastBcMemberType;
private static Stack<BcTypeNode> bcMembersTypesStack;
private static void process(MemberExpressionNode node)
{
bcMembersTypesStack.push(lastBcMemberType);
lastBcMemberType = null;
Node base = node.base;
SelectorNode selector = node.selector;
ListWriteDestination memberDest = new ListWriteDestination();
pushDest(memberDest);
if (base != null)
{
ListWriteDestination baseExpr = new ListWriteDestination();
pushDest(baseExpr);
process(base);
popDest();
lastBcMemberType = evaluateType(base);
assert lastBcMemberType != null;
boolean staticCall = false;
if (base instanceof MemberExpressionNode)
{
IdentifierNode identifierNode = BcNodeHelper.tryExtractIdentifier((MemberExpressionNode)base);
staticCall = identifierNode != null && canBeClass(identifierNode.name);
}
if (staticCall)
{
dest.write(BcCodeCs.type(baseExpr.toString()));
}
else
{
dest.write(baseExpr);
}
}
BcTypeNode baseType = lastBcMemberType;
ListWriteDestination selectorDest = new ListWriteDestination();
if (selector != null)
{
pushDest(selectorDest);
process(selector);
popDest();
}
boolean stringCall = false;
boolean needDot = true;
if (base != null && typeEquals(baseType, classString))
{
String selectorCode = selectorDest.toString();
stringCall = !selectorCode.equals("ToString()") && !selectorCode.equals("Length");
needDot = !stringCall;
}
if (base != null && needDot)
{
if (selector instanceof GetExpressionNode ||
selector instanceof CallExpressionNode ||
selector instanceof SetExpressionNode)
{
if (selector.getMode() != Tokens.LEFTBRACKET_TOKEN)
{
dest.write(".");
}
}
}
if (stringCall)
{
popDest(); // member dest
assert selector instanceof CallExpressionNode;
CallExpressionNode callExpr = (CallExpressionNode) selector;
ListWriteDestination argsDest = new ListWriteDestination();
if (callExpr.args != null)
{
pushDest(argsDest);
process(callExpr.args);
popDest();
}
IdentifierNode funcIndentifierNode = BcNodeHelper.tryExtractIdentifier(selector);
assert funcIndentifierNode != null;
String funcName = BcCodeCs.identifier(funcIndentifierNode);
// if (funcName.equals("charAt"))
// {
// dest.writef("%s[%s]", memberDest, argsDest);
// }
if (callExpr.args != null)
{
dest.writef("AsString.%s(%s, %s)", funcName, memberDest, argsDest);
}
else
{
dest.writef("AsString.%s(%s)", funcName, memberDest);
}
}
else
{
dest.write(selectorDest);
popDest(); // member dest
dest.write(memberDest);
}
lastBcMemberType = bcMembersTypesStack.pop();
}
private static void process(SelectorNode node)
{
if (node instanceof DeleteExpressionNode)
process((DeleteExpressionNode)node);
else if (node instanceof GetExpressionNode)
process((GetExpressionNode)node);
else if (node instanceof CallExpressionNode)
process((CallExpressionNode)node);
else if (node instanceof SetExpressionNode)
process((SetExpressionNode)node);
else if (node instanceof ApplyTypeExprNode)
process((ApplyTypeExprNode)node);
else if (node instanceof IncrementNode)
process((IncrementNode)node);
else
assert false : node.getClass();
}
private static void process(DeleteExpressionNode node)
{
ListWriteDestination expr = new ListWriteDestination();
pushDest(expr);
process(node.expr);
popDest();
assert node.getMode() == Tokens.LEFTBRACKET_TOKEN;
dest.writef(".remove(%s)", expr);
}
private static void process(GetExpressionNode node)
{
ListWriteDestination expr = new ListWriteDestination();
pushDest(expr);
process(node.expr);
popDest();
boolean accessingDynamicProperty = false;
String identifier = expr.toString();
boolean getterCalled = false;
if (node.expr instanceof IdentifierNode)
{
BcClassDefinitionNode bcClass;
if (lastBcMemberType != null)
{
bcClass = lastBcMemberType.getClassNode();
assert bcClass != null;
}
else
{
assert lastBcClass != null;
bcClass = lastBcClass;
}
BcClassDefinitionNode bcStaticClass = findClass(identifier);
if (bcStaticClass != null)
{
lastBcMemberType = bcStaticClass.getClassType();
assert lastBcMemberType != null;
addToImport(lastBcMemberType);
}
else
{
BcFunctionDeclaration bcFunc = bcClass.findGetterFunction(identifier);
if (bcFunc != null)
{
BcTypeNode funcType = bcFunc.getReturnType();
assert funcType != null : identifier;
lastBcMemberType = funcType;
if (classEquals(bcClass, classString) && identifier.equals("length"))
{
// keep String.length property as a "Lenght" property
identifier = Character.toUpperCase(identifier.charAt(0)) + identifier.substring(1);
}
else
{
identifier = BcCodeCs.getter(identifier);
getterCalled = true;
}
}
else
{
BcVariableDeclaration bcVar = findVariable(bcClass, identifier);
if (bcVar != null)
{
lastBcMemberType = bcVar.getType();
assert lastBcMemberType != null;
}
else
{
BcFunctionDeclaration bcFunction = bcClass.findFunction(identifier); // check if it's a function type
if (bcFunction != null)
{
System.err.println("Warning! Function type: " + identifier);
lastBcMemberType = BcTypeNode.create(classFunction);
}
else if (classEquals(bcClass, classXML))
{
IdentifierNode identifierNode = (IdentifierNode) node.expr;
if (identifierNode.isAttribute())
{
lastBcMemberType = BcTypeNode.create(classString);
}
else
{
assert false : identifierNode.name;
}
}
else
{
System.err.println("Warning! Dymaic property: " + identifier);
accessingDynamicProperty = true;
}
}
}
}
}
else if (node.expr instanceof ArgumentListNode)
{
assert lastBcMemberType != null;
if (lastBcMemberType instanceof BcVectorTypeNode)
{
BcVectorTypeNode vectorType = (BcVectorTypeNode) lastBcMemberType;
lastBcMemberType = vectorType.getGeneric();
assert lastBcMemberType != null;
}
else if (typeEquals(lastBcMemberType, classXMLList))
{
lastBcMemberType = BcTypeNode.create(classXML);
}
else
{
lastBcMemberType = BcTypeNode.create(classObject);
}
}
else
{
assert false;
}
if (node.getMode() == Tokens.LEFTBRACKET_TOKEN)
{
dest.writef("[%s]", identifier);
}
else if (accessingDynamicProperty)
{
dest.writef("getOwnProperty(\"%s\")", identifier);
}
else if (getterCalled)
{
dest.writef("%s()", identifier);
}
else
{
dest.write(identifier);
}
}
private static BcTypeNode findIdentifierType(String name)
{
BcClassDefinitionNode bcClass = findClass(name);
if (bcClass != null)
{
return bcClass.getClassType();
}
BcVariableDeclaration bcVar = findVariable(name);
if (bcVar != null)
{
return bcVar.getType();
}
BcFunctionDeclaration bcFunc = findFunction(name);
if (bcFunc != null)
{
return bcFunc.getReturnType();
}
return null;
}
private static BcVariableDeclaration findVariable(String name)
{
return findVariable(lastBcClass, name);
}
private static BcVariableDeclaration findVariable(BcClassDefinitionNode bcClass, String name)
{
BcVariableDeclaration bcVar = findLocalVar(name);
if (bcVar != null)
{
return bcVar;
}
return bcClass.findField(name);
}
private static BcVariableDeclaration findLocalVar(String name)
{
if (lastBcFunction == null)
{
return null;
}
return lastBcFunction.findVariable(name);
}
private static void process(CallExpressionNode node)
{
ListWriteDestination exprDest = new ListWriteDestination();
pushDest(exprDest);
process(node.expr);
popDest();
String identifier = exprDest.toString();
if (node.expr instanceof IdentifierNode)
{
if (lastBcMemberType == null)
{
lastBcMemberType = null;
if (!(identifier.equals(BcCodeCs.thisCallMarker) && identifier.equals(BcCodeCs.thisCallMarker)))
{
BcFunctionDeclaration bcFunc = findFunction(identifier);
if (bcFunc != null)
{
if (bcFunc.hasReturnType())
{
lastBcMemberType = bcFunc.getReturnType();
assert lastBcMemberType != null;
}
}
else if (node.is_new)
{
BcClassDefinitionNode bcNewClass = findClass(identifier);
assert bcNewClass != null : bcNewClass;
BcTypeNode bcClassType = bcNewClass.getClassType();
assert bcClassType != null : identifier;
lastBcMemberType = bcClassType;
}
}
}
else
{
BcClassDefinitionNode bcClass = lastBcMemberType.getClassNode();
assert bcClass != null;
BcFunctionDeclaration bcFunc = bcClass.findFunction(identifier);
if (bcFunc != null)
{
lastBcMemberType = bcFunc.getReturnType();
if (classEquals(bcClass, classString))
{
if (identifier.equals("toString"))
{
// turn toString() into ToString() for all strings
identifier = Character.toUpperCase(identifier.charAt(0)) + identifier.substring(1);
}
}
}
else
{
BcVariableDeclaration bcFuncVar = findVariable(bcClass, identifier);
if (bcFuncVar != null)
{
if (typeEquals(bcFuncVar.getType(), classFunction))
{
System.err.println("Warning! Function type: " + identifier);
lastBcMemberType = bcFuncVar.getType();
}
else
{
assert false : identifier;
}
}
else
{
assert false : identifier;
}
}
}
}
else if (node.expr instanceof MemberExpressionNode)
{
lastBcMemberType = evaluateMemberExpression((MemberExpressionNode) node.expr);
assert lastBcMemberType != null;
}
else
{
assert false : node;
}
ListWriteDestination argsDest = new ListWriteDestination();
if (node.args != null)
{
pushDest(argsDest);
process(node.args);
popDest();
}
BcTypeNode type = extractBcType(node.expr);
assert type != null : node.expr.getClass();
if (node.is_new)
{
if (type instanceof BcVectorTypeNode)
{
BcVectorTypeNode vectorType = (BcVectorTypeNode) type;
ObjectList<Node> args;
if (node.args != null && (args = node.args.items).size() == 1 && args.get(0) instanceof LiteralArrayNode)
{
LiteralArrayNode arrayNode = (LiteralArrayNode) args.get(0);
ArgumentListNode elementlist = arrayNode.elementlist;
WriteDestination initDest = new ListWriteDestination();
pushDest(initDest);
for (Node elementNode : elementlist.items)
{
initDest.write(".a(");
process(elementNode);
initDest.write(")");
}
popDest();
dest.write(BcCodeCs.construct(vectorType, elementlist.size()) + initDest);
}
else
{
dest.write(BcCodeCs.construct(vectorType, argsDest));
}
}
else
{
dest.write(BcCodeCs.construct(type, argsDest.toString()));
}
}
else if (node.expr instanceof MemberExpressionNode && ((MemberExpressionNode) node.expr).selector instanceof ApplyTypeExprNode)
{
assert type instanceof BcVectorTypeNode;
BcVectorTypeNode bcVector = (BcVectorTypeNode) type;
Node argNode = node.args.items.get(0);
if (argNode instanceof LiteralArrayNode)
{
LiteralArrayNode arrayNode = (LiteralArrayNode) argNode;
ArgumentListNode elementlist = arrayNode.elementlist;
WriteDestination initDest = new ListWriteDestination();
pushDest(initDest);
+ int elementIndex = 0;
for (Node elementNode : elementlist.items)
- {
- initDest.write(" << ");
+ {
process(elementNode);
+ if (++elementIndex < elementlist.size())
+ {
+ dest.write(", ");
+ }
}
popDest();
- dest.write(BcCodeCs.construct(bcVector, elementlist.size()) + initDest);
+ dest.write(BcCodeCs.construct(bcVector, initDest));
}
else
{
- dest.write(BcCodeCs.construct(type, 1) + " << " + argsDest);
+ dest.write(BcCodeCs.construct(type, argsDest));
}
}
else
{
if (node.getMode() == Tokens.EMPTY_TOKEN && node.args != null && node.args.items.size() == 1)
{
if (canBeClass(type) || BcCodeCs.isBasicType(type))
{
addToImport(type);
dest.writef("((%s)(%s))", BcCodeCs.type(identifier), argsDest);
}
else
{
dest.writef("%s(%s)", identifier, argsDest);
}
}
else
{
dest.writef("%s(%s)", identifier, argsDest);
}
}
}
private static void process(SetExpressionNode node)
{
ListWriteDestination exprDest = new ListWriteDestination();
pushDest(exprDest);
process(node.expr);
popDest();
String identifier = exprDest.toString();
boolean setterCalled = false;
if (node.expr instanceof IdentifierNode)
{
BcClassDefinitionNode bcClass;
if (lastBcMemberType != null)
{
bcClass = lastBcMemberType.getClassNode();
assert bcClass != null;
}
else
{
assert lastBcClass != null;
bcClass = lastBcClass;
}
BcFunctionDeclaration bcFunc = bcClass.findSetterFunction(identifier);
if (bcFunc != null)
{
List<BcFuncParam> funcParams = bcFunc.getParams();
BcTypeNode setterType = funcParams.get(0).getType();
setterCalled = true;
identifier = BcCodeCs.setter(identifier);
lastBcMemberType = setterType;
}
else
{
BcVariableDeclaration bcVar = findVariable(bcClass, identifier);
if (bcVar != null)
{
lastBcMemberType = bcVar.getType();
assert lastBcMemberType != null;
}
else
{
BcFunctionDeclaration bcFunction = bcClass.findFunction(identifier); // check if it's a function type
if (bcFunction != null)
{
System.err.println("Warning! Function type: " + identifier);
lastBcMemberType = BcTypeNode.create(classFunction);
}
else if (classEquals(bcClass, classXML))
{
IdentifierNode identifierNode = (IdentifierNode) node.expr;
if (identifierNode.isAttribute())
{
lastBcMemberType = BcTypeNode.create(classString);
}
else
{
assert false : identifierNode.name;
}
}
else
{
System.err.println("Warning! Dymaic set property: " + identifier);
}
}
}
}
else if (node.expr instanceof ArgumentListNode)
{
assert lastBcMemberType != null;
if (lastBcMemberType instanceof BcVectorTypeNode)
{
BcVectorTypeNode vectorType = (BcVectorTypeNode) lastBcMemberType;
lastBcMemberType = vectorType.getGeneric();
assert lastBcMemberType != null;
}
else
{
lastBcMemberType = BcTypeNode.create(classObject);
}
}
else
{
assert false;
}
ListWriteDestination argsDest = new ListWriteDestination();
pushDest(argsDest);
process(node.args);
popDest();
if (setterCalled)
{
if (node.getMode() == Tokens.LEFTBRACKET_TOKEN)
{
dest.writef("[%s](%s)", identifier, argsDest);
}
else
{
dest.writef("%s(%s)", identifier, argsDest);
}
}
else
{
if (node.getMode() == Tokens.LEFTBRACKET_TOKEN)
{
dest.writef("[%s] = %s", identifier, argsDest);
}
else
{
dest.writef("%s = %s", identifier, argsDest);
}
}
}
private static void process(ApplyTypeExprNode node)
{
ListWriteDestination expr = new ListWriteDestination();
pushDest(expr);
process(node.expr);
popDest();
String typeName = BcCodeCs.identifier((IdentifierNode)node.expr);
StringBuilder typeBuffer = new StringBuilder(typeName);
ListNode typeArgs = node.typeArgs;
int genericCount = typeArgs.items.size();
if (genericCount > 0)
{
typeBuffer.append("<");
int genericIndex = 0;
for (Node genericTypeNode : typeArgs.items)
{
BcTypeNode genericType = extractBcType(genericTypeNode);
typeBuffer.append(BcCodeCs.type(genericType));
if (++genericIndex < genericCount)
{
typeBuffer.append(",");
}
}
typeBuffer.append(">");
}
String type = typeBuffer.toString();
dest.write(type);
}
private static void process(IncrementNode node)
{
ListWriteDestination expr = new ListWriteDestination();
pushDest(expr);
process(node.expr);
popDest();
String op = Tokens.tokenToString[-node.op];
if (node.isPostfix)
{
dest.write(expr + op);
}
else
{
dest.write(op + expr);
}
}
private static void process(IdentifierNode node)
{
if (node.isAttr())
{
dest.write("attribute(\"");
dest.write(BcCodeCs.identifier(node));
dest.write("\")");
}
else
{
dest.write(BcCodeCs.identifier(node));
}
}
private static void process(VariableBindingNode node)
{
System.err.println("Fix me!!! VariableBindingNode");
}
private static void processLiteral(Node node)
{
if (node instanceof LiteralNumberNode)
{
LiteralNumberNode numberNode = (LiteralNumberNode) node;
dest.write(numberNode.value);
if (numberNode.value.indexOf('.') != -1)
{
dest.write("f");
}
}
else if (node instanceof LiteralNullNode)
{
dest.write(BcCodeCs.NULL);
}
else if (node instanceof LiteralBooleanNode)
{
LiteralBooleanNode booleanNode = (LiteralBooleanNode) node;
dest.write(booleanNode.value ? "true" : "false");
}
else if (node instanceof LiteralStringNode)
{
LiteralStringNode stringNode = (LiteralStringNode) node;
dest.writef("\"%s\"", replaceEscapes(stringNode.value));
}
else if (node instanceof LiteralRegExpNode)
{
assert false : "LiteralRegExpNode";
}
else if (node instanceof LiteralArrayNode)
{
LiteralArrayNode arrayNode = (LiteralArrayNode) node;
ArgumentListNode elementlist = arrayNode.elementlist;
WriteDestination elementDest = new ListWriteDestination();
pushDest(elementDest);
int elementIndex = 0;
for (Node elementNode : elementlist.items)
{
process(elementNode);
if (++elementIndex < elementlist.items.size())
{
elementDest.write(", ");
}
}
popDest();
dest.writef("new %s(%s)", BcCodeCs.type(classArray), elementDest);
}
else if (node instanceof LiteralObjectNode)
{
assert false : "LiteralObjectNode";
}
else
{
assert false : node.getClass();
}
}
private static String replaceEscapes(String str)
{
return str.replace("\"", "\\\"").replace("\b", "\\\b").replace("\f", "\\\f").replace("\n", "\\\n").replace("\r", "\\\r").replace("\t", "\\\t");
}
private static void process(IfStatementNode node)
{
ListWriteDestination condDest = new ListWriteDestination();
pushDest(condDest);
process(node.condition);
popDest();
String condString = condDest.toString();
assert node.condition instanceof ListNode : node.condition;
ListNode listNode = (ListNode) node.condition;
condString = createSafeConditionString(condString, listNode);
dest.writelnf("if(%s)", condString);
if (node.thenactions != null)
{
ListWriteDestination thenDest = new ListWriteDestination();
pushDest(thenDest);
process(node.thenactions);
popDest();
dest.writeln(thenDest);
}
else
{
writeEmptyBlock();
}
if (node.elseactions != null)
{
ListWriteDestination elseDest = new ListWriteDestination();
pushDest(elseDest);
process(node.elseactions);
popDest();
dest.writeln("else");
dest.writeln(elseDest);
}
}
private static String createSafeConditionString(String condString, ListNode listNode)
{
assert listNode.size() == 1 : listNode.size();
Node condition = listNode.items.get(0);
BcTypeNode conditionType = evaluateType(condition);
if (!typeEquals(conditionType, classBoolean))
{
if (typeEquals(conditionType, "int") || typeEquals(conditionType, "uint"))
{
return String.format("(%s) != 0", condString);
}
return String.format("(%s) != null", condString);
}
else
{
return String.format("%s", condString);
}
}
private static void process(ConditionalExpressionNode node)
{
ListWriteDestination condDest = new ListWriteDestination();
pushDest(condDest);
process(node.condition);
popDest();
ListWriteDestination thenDest = new ListWriteDestination();
pushDest(thenDest);
process(node.thenexpr);
popDest();
ListWriteDestination elseDest = new ListWriteDestination();
pushDest(elseDest);
process(node.elseexpr);
popDest();
dest.writef("((%s) ? (%s) : (%s))", condDest, thenDest, elseDest);
}
private static void process(WhileStatementNode node)
{
ListWriteDestination exprDest = new ListWriteDestination();
pushDest(exprDest);
process(node.expr);
popDest();
String condString = exprDest.toString();
assert node.expr instanceof ListNode : node.expr;
ListNode listNode = (ListNode) node.expr;
condString = createSafeConditionString(condString, listNode);
dest.writelnf("while(%s)", condString);
if (node.statement != null)
{
ListWriteDestination statementDest = new ListWriteDestination();
pushDest(statementDest);
process(node.statement);
popDest();
dest.writeln(statementDest);
}
else
{
writeEmptyBlock();
}
}
private static void process(ForStatementNode node)
{
boolean isForEach = node.test instanceof HasNextNode;
if (isForEach)
{
// get iterable collection expression
assert node.initialize != null;
assert node.initialize instanceof ListNode : node.initialize.getClass();
ListNode list = (ListNode) node.initialize;
assert list.items.size() == 2 : list.items.size();
StoreRegisterNode register = (StoreRegisterNode) list.items.get(1);
CoerceNode coerce = (CoerceNode) register.expr;
ListWriteDestination collection = new ListWriteDestination();
pushDest(collection);
process(coerce.expr);
popDest();
BcTypeNode collectionType = evaluateType(coerce.expr);
assert collectionType != null;
assert node.statement != null;
assert node.statement instanceof StatementListNode : node.statement.getClass();
StatementListNode statements = (StatementListNode) node.statement;
assert statements.items.size() == 2;
// get iteration
ExpressionStatementNode child1 = (ExpressionStatementNode) statements.items.get(0);
MemberExpressionNode child2 = (MemberExpressionNode) child1.expr;
SetExpressionNode child3 = (SetExpressionNode) child2.selector;
String loopVarName = null;
if (child3.expr instanceof QualifiedIdentifierNode)
{
QualifiedIdentifierNode identifier = (QualifiedIdentifierNode) child3.expr;
loopVarName = BcCodeCs.identifier(identifier);
}
else if (child3.expr instanceof IdentifierNode)
{
IdentifierNode identifier = (IdentifierNode) child3.expr;
loopVarName = BcCodeCs.identifier(identifier);
}
else
{
assert false : child3.expr.getClass();
}
BcVariableDeclaration loopVar = findDeclaredVar(loopVarName);
assert loopVar != null : loopVarName;
// get loop body
dest.writelnf("foreach (%s %s in %s)", BcCodeCs.type(loopVar.getType()), loopVarName, collection);
Node bodyNode = statements.items.get(1);
if (bodyNode != null)
{
assert bodyNode instanceof StatementListNode : bodyNode.getClass();
StatementListNode statementsNode = (StatementListNode) bodyNode;
writeBlockOpen(dest);
ObjectList<Node> items = statementsNode.items;
for (Node itemNode : items)
{
process(itemNode);
}
writeBlockClose(dest);
}
else
{
writeEmptyBlock();
}
}
else
{
ListWriteDestination initialize = new ListWriteDestination();
ListWriteDestination test = new ListWriteDestination();
ListWriteDestination increment = new ListWriteDestination();
if (node.initialize != null)
{
pushDest(initialize);
process(node.initialize);
popDest();
}
if (node.test != null)
{
pushDest(test);
process(node.test);
popDest();
}
if (node.increment != null)
{
increment = new ListWriteDestination();
pushDest(increment);
process(node.increment);
popDest();
}
dest.writelnf("for (%s; %s; %s)", initialize, test, increment);
process(node.statement);
}
}
private static void process(DoStatementNode node)
{
}
private static void process(SwitchStatementNode node)
{
ListWriteDestination expr = new ListWriteDestination();
pushDest(expr);
process(node.expr);
popDest();
dest.writelnf("switch(%s)", expr);
writeBlockOpen(dest);
if (node.statements != null)
{
ObjectList<Node> statements = node.statements.items;
for (Node statement : statements)
{
if (statement instanceof CaseLabelNode)
{
CaseLabelNode caseLabel = (CaseLabelNode)statement;
Node label = caseLabel.label;
if (label == null)
{
dest.writeln("default:");
}
else
{
ListWriteDestination caseDest = new ListWriteDestination();
pushDest(caseDest);
process(label);
popDest();
dest.writelnf("case %s:", caseDest);
}
writeBlockOpen(dest);
}
else if (statement instanceof BreakStatementNode)
{
process(statement);
writeBlockClose(dest);
}
else
{
process(statement);
}
}
}
writeBlockClose(dest);
}
private static void process(TryStatementNode node)
{
}
private static void process(ThrowStatementNode node)
{
}
private static void process(BinaryExpressionNode node)
{
ListWriteDestination ldest = new ListWriteDestination();
ListWriteDestination rdest = new ListWriteDestination();
pushDest(ldest);
process(node.lhs);
popDest();
pushDest(rdest);
process(node.rhs);
popDest();
if (node.op == Tokens.LOGICALAND_TOKEN || node.op == Tokens.LOGICALOR_TOKEN)
{
String lshString = ldest.toString();
String rshString = rdest.toString();
BcTypeNode lshType = evaluateType(node.lhs);
BcTypeNode rshType = evaluateType(node.rhs);
if (!typeEquals(lshType, classBoolean))
{
lshString = String.format("(%s != null)", lshString);
}
if (!typeEquals(rshType, classBoolean))
{
rshString = String.format("(%s != null)", rshString);
}
dest.writef("%s %s %s", lshString, Tokens.tokenToString[-node.op], rshString);
}
else if (node.op == Tokens.IS_TOKEN)
{
dest.write(BcCodeCs.operatorIs(ldest, rdest));
}
else if (node.op == Tokens.AS_TOKEN)
{
assert false;
}
else
{
dest.writef("%s %s %s", ldest, Tokens.tokenToString[-node.op], rdest);
}
}
private static void process(UnaryExpressionNode node)
{
ListWriteDestination expr = new ListWriteDestination();
pushDest(expr);
process(node.expr);
popDest();
switch (node.op)
{
case Tokens.NOT_TOKEN:
{
if (node.expr instanceof MemberExpressionNode)
{
MemberExpressionNode memberNode = (MemberExpressionNode) node.expr;
BcTypeNode memberType = evaluateMemberExpression(memberNode);
if (!typeEquals(memberType, classBoolean))
{
dest.writef("(%s == null)", expr);
}
else
{
dest.writef("!(%s)", expr);
}
}
else
{
assert false : node.expr;
}
break;
}
case Tokens.MINUS_TOKEN:
dest.writef("-%s", expr);
break;
default:
assert false : node.op;
}
}
private static void process(ReturnStatementNode node)
{
assert !node.finallyInserted;
dest.write("return");
if (node.expr != null)
{
dest.write(" ");
process(node.expr);
}
dest.writeln(";");
}
private static void process(BreakStatementNode node)
{
dest.write("break");
if (node.id != null)
{
String id = BcCodeCs.identifier(node.id);
dest.write(" " + id);
}
dest.writeln(";");
}
private static void process(ThisExpressionNode node)
{
dest.write("this");
}
private static void process(SuperExpressionNode node)
{
String extendsClass = BcCodeCs.type(lastBcClass.getExtendsType());
dest.write(extendsClass);
}
private static void process(SuperStatementNode node)
{
ArgumentListNode args = node.call.args;
ListWriteDestination argsDest = new ListWriteDestination();
if (args != null)
{
pushDest(argsDest);
int itemIndex = 0;
for (Node arg : args.items)
{
process(arg);
if (++itemIndex < args.items.size())
{
dest.write(", ");
}
}
popDest();
}
dest.writelnf("%s(%s);", BcCodeCs.superCallMarker, argsDest);
}
private static void process(BcFunctionDeclaration bcFunc)
{
List<BcVariableDeclaration> oldDeclaredVars = declaredVars;
lastBcFunction = bcFunc;
declaredVars = bcFunc.getDeclaredVars();
// get function statements
ListWriteDestination body = new ListWriteDestination();
pushDest(body);
process(bcFunc.getStatements());
popDest();
List<String> lines = body.getLines();
String lastLine = lines.get(lines.size() - 2);
if (lastLine.contains("return;"))
{
lines.remove(lines.size() - 2);
}
bcFunc.setBody(body);
declaredVars = oldDeclaredVars;
lastBcFunction = null;
}
private static void process(ExpressionStatementNode node)
{
process(node.expr);
dest.writeln(";");
}
private static void process(ListNode node)
{
ObjectList<Node> items = node.items;
for (Node item : items)
{
process(item);
}
}
private static void process(BcTypeNode typeNode)
{
if (!typeNode.isIntegral() && !typeNode.hasClassNode())
{
BcClassDefinitionNode classNode = findClass(typeNode.getNameEx());
assert classNode != null : typeNode.getNameEx();
typeNode.setClassNode(classNode);
}
}
private static BcClassDefinitionNode findClass(String name)
{
BcClassDefinitionNode bcClass = findClass(bcApiClasses, name);
if (bcClass != null)
{
return bcClass;
}
return findClass(bcClasses, name);
}
private static BcClassDefinitionNode findClass(List<BcClassDefinitionNode> classes, String name)
{
for (BcClassDefinitionNode bcClass : classes)
{
if (bcClass.getClassType().getName().equals(name))
{
return bcClass;
}
}
return null;
}
private static BcFunctionDeclaration findBuiltinFunc(String name)
{
return bcBuitinFunctions.get(name);
}
private static BcTypeNode findVariableType(String indentifier)
{
if (indentifier.equals("this"))
{
return BcTypeNode.create(lastBcClass.getName());
}
BcTypeNode foundType = null;
if (lastBcFunction != null)
{
foundType = findVariableType(lastBcFunction.getDeclaredVars(), indentifier);
if (foundType != null)
{
return foundType;
}
}
return findVariableType(lastBcClass.getDeclaredVars(), indentifier);
}
private static BcTypeNode findVariableType(List<BcVariableDeclaration> vars, String indentifier)
{
for (BcVariableDeclaration var : vars)
{
if (var.getIdentifier().equals(indentifier))
{
return var.getType();
}
}
return null;
}
private static void write(File outputDir, List<BcClassDefinitionNode> classes) throws IOException
{
for (BcClassDefinitionNode bcClass : classes)
{
writeClassDefinition(bcClass, outputDir);
}
}
private static void writeImports(WriteDestination dest, List<String> imports)
{
List<String> sortedImports = new ArrayList<String>(imports);
Collections.sort(sortedImports);
for (String importString : sortedImports)
{
dest.writelnf("using %s;", importString);
}
}
private static void writeInterfaceFunctions(BcClassDefinitionNode bcClass)
{
List<BcFunctionDeclaration> functions = bcClass.getFunctions();
for (BcFunctionDeclaration bcFunc : functions)
{
String type = bcFunc.hasReturnType() ? BcCodeCs.typeRef(bcFunc.getReturnType()) : "void";
String name = BcCodeCs.identifier(bcFunc.getName());
if (bcFunc.isConstructor())
{
continue;
}
src.writef("%s %s(", type, name);
StringBuilder paramsBuffer = new StringBuilder();
StringBuilder argsBuffer = new StringBuilder();
List<BcFuncParam> params = bcFunc.getParams();
int paramIndex = 0;
for (BcFuncParam bcParam : params)
{
String paramType = BcCodeCs.type(bcParam.getType());
String paramName = BcCodeCs.identifier(bcParam.getIdentifier());
paramsBuffer.append(String.format("%s %s", paramType, paramName));
argsBuffer.append(paramName);
if (++paramIndex < params.size())
{
paramsBuffer.append(", ");
argsBuffer.append(", ");
}
}
src.write(paramsBuffer);
src.writeln(");");
}
}
private static void writeClassDefinition(BcClassDefinitionNode bcClass, File outputDir) throws IOException
{
boolean isInterface = bcClass instanceof BcInterfaceDefinitionNode;
String className = getClassName(bcClass);
String packageName = bcClass.getPackageName();
String subPath = packageName.replace(".", "/");
File srcFileDir = new File(outputDir, subPath);
if (!srcFileDir.exists())
{
boolean successed = srcFileDir.mkdirs();
assert successed : srcFileDir.getAbsolutePath();
}
src = new FileWriteDestination(new File(srcFileDir, className + ".cs"));
impl = new ListWriteDestination();
src.writeln("using System;");
writeBlankLine(src);
writeImports(src, getImports(bcClass));
writeBlankLine(src);
src.writeln("namespace " + BcCodeCs.namespace(bcClass.getPackageName()));
writeBlockOpen(src);
if (isInterface)
{
src.writelnf("public interface %s", className);
writeBlockOpen(src);
writeInterfaceFunctions(bcClass);
writeBlockClose(src);
}
else
{
src.writef("public class %s", className);
boolean hasExtendsType = bcClass.hasExtendsType();
boolean hasInterfaces = bcClass.hasInterfaces();
if (hasExtendsType || hasInterfaces)
{
src.write(" : ");
}
if (hasExtendsType)
{
src.write(BcCodeCs.type(bcClass.getExtendsType()));
if (hasInterfaces)
{
src.write(", ");
}
}
if (hasInterfaces)
{
List<BcTypeNode> interfaces = bcClass.getInterfaces();
int interfaceIndex= 0;
for (BcTypeNode bcInterface : interfaces)
{
String interfaceType = BcCodeCs.type(bcInterface);
src.write(++interfaceIndex == interfaces.size() ? interfaceType : (interfaceType + ", "));
}
}
src.writeln();
writeBlockOpen(src);
writeFields(bcClass);
writeFunctions(bcClass);
writeBlockClose(src);
}
writeBlockClose(src);
src.close();
}
private static void writeFields(BcClassDefinitionNode bcClass)
{
List<BcVariableDeclaration> fields = bcClass.getFields();
impl.writeln();
for (BcVariableDeclaration bcField : fields)
{
String type = BcCodeCs.type(bcField.getType());
String name = BcCodeCs.identifier(bcField.getIdentifier());
src.write(bcField.getVisiblity() + " ");
if (bcField.isConst())
{
if (canBeClass(bcField.getType()))
{
src.write("static ");
}
else
{
src.write("const ");
}
}
else if (bcField.isStatic())
{
src.write("static ");
}
src.writef("%s %s", type, name);
if (bcField.hasInitializer())
{
src.writef(" = %s", bcField.getInitializer());
}
src.writeln(";");
}
}
private static void writeFunctions(BcClassDefinitionNode bcClass)
{
List<BcFunctionDeclaration> functions = bcClass.getFunctions();
for (BcFunctionDeclaration bcFunc : functions)
{
src.write(bcFunc.getVisiblity() + " ");
if (bcFunc.isConstructor())
{
src.write(getClassName(bcClass));
}
else
{
if (bcFunc.isStatic())
{
src.write("static ");
}
else if (!bcFunc.isPrivate())
{
src.write("virtual ");
}
String type = bcFunc.hasReturnType() ? BcCodeCs.type(bcFunc.getReturnType()) : "void";
String name = BcCodeCs.identifier(bcFunc.getName());
if (bcFunc.isGetter())
{
name = BcCodeCs.getter(name);
}
else if (bcFunc.isSetter())
{
name = BcCodeCs.setter(name);
}
src.writef("%s %s", type, name);
}
StringBuilder paramsBuffer = new StringBuilder();
List<BcFuncParam> params = bcFunc.getParams();
int paramIndex = 0;
for (BcFuncParam bcParam : params)
{
String paramType = BcCodeCs.type(bcParam.getType());
String paramName = BcCodeCs.identifier(bcParam.getIdentifier());
paramsBuffer.append(String.format("%s %s", paramType, paramName));
if (++paramIndex < params.size())
{
paramsBuffer.append(", ");
}
}
src.writelnf("(%s)", paramsBuffer);
ListWriteDestination body = bcFunc.getBody();
if (bcFunc.isConstructor())
{
writeConstructorBody(body);
}
else
{
src.writeln(body);
}
}
}
private static void writeConstructorBody(ListWriteDestination body)
{
List<String> lines = body.getLines();
String firstLine = lines.get(1).trim();
if (firstLine.startsWith(BcCodeCs.thisCallMarker))
{
firstLine = firstLine.replace(BcCodeCs.thisCallMarker, "this");
if (firstLine.endsWith(";"))
{
firstLine = firstLine.substring(0, firstLine.length() - 1);
}
src.writeln(" : " + firstLine);
lines.remove(1);
src.writeln(new ListWriteDestination(lines));
}
else if (firstLine.startsWith(BcCodeCs.superCallMarker))
{
firstLine = firstLine.replace(BcCodeCs.superCallMarker, "base");
if (firstLine.endsWith(";"))
{
firstLine = firstLine.substring(0, firstLine.length() - 1);
}
src.writeln(" : " + firstLine);
lines.remove(1);
src.writeln(new ListWriteDestination(lines));
}
else
{
src.writeln(body);
}
}
private static void writeBlockOpen(WriteDestination dest)
{
dest.writeln("{");
dest.incTab();
}
private static void writeBlockClose(WriteDestination dest)
{
dest.decTab();
dest.writeln("}");
}
private static void writeEmptyBlock()
{
writeEmptyBlock(dest);
}
private static void writeBlankLine(WriteDestination dest)
{
dest.writeln();
}
private static void writeBlankLine()
{
src.writeln();
impl.writeln();
}
private static void writeEmptyBlock(WriteDestination dest)
{
writeBlockOpen(dest);
writeBlockClose(dest);
}
private static void pushDest(WriteDestination newDest)
{
destStack.push(dest);
dest = newDest;
}
private static void popDest()
{
dest = destStack.pop();
}
///////////////////////////////////////////////////////////////
// Helpers
private static BcFunctionDeclaration findFunction(String name)
{
return lastBcClass.findFunction(name);
}
private static BcVariableDeclaration findDeclaredVar(String name)
{
assert declaredVars != null;
for (BcVariableDeclaration var : declaredVars)
{
if (var.getIdentifier().equals(name))
return var;
}
return null;
}
private static List<String> getImports(BcClassDefinitionNode bcClass)
{
List<String> imports = new ArrayList<String>();
if (bcClass.hasExtendsType())
{
tryAddUniqueNamespace(imports, bcClass.getExtendsType());
}
if (bcClass.hasInterfaces())
{
List<BcTypeNode> interfaces = bcClass.getInterfaces();
for (BcTypeNode bcInterface : interfaces)
{
tryAddUniqueNamespace(imports, bcInterface);
}
}
List<BcVariableDeclaration> classVars = bcClass.getDeclaredVars();
for (BcVariableDeclaration bcVar : classVars)
{
BcTypeNode type = bcVar.getType();
tryAddUniqueNamespace(imports, type);
}
List<BcFunctionDeclaration> functions = bcClass.getFunctions();
for (BcFunctionDeclaration bcFunc : functions)
{
if (bcFunc.hasReturnType())
{
BcTypeNode returnType = bcFunc.getReturnType();
tryAddUniqueNamespace(imports, returnType);
}
List<BcFuncParam> params = bcFunc.getParams();
for (BcFuncParam param : params)
{
BcTypeNode type = param.getType();
tryAddUniqueNamespace(imports, type);
}
}
List<BcTypeNode> additionalImports = bcClass.getAdditionalImports();
for (BcTypeNode bcType : additionalImports)
{
tryAddUniqueNamespace(imports, bcType);
}
return imports;
}
private static void tryAddUniqueNamespace(List<String> imports, BcTypeNode type)
{
if (canBeClass(type))
{
BcClassDefinitionNode classNode = type.getClassNode();
assert classNode != null : type.getName();
String packageName = classNode.getPackageName();
assert packageName != null : classNode.getName();
if (!imports.contains(packageName))
{
imports.add(packageName);
}
if (type instanceof BcVectorTypeNode)
{
BcVectorTypeNode vectorType = (BcVectorTypeNode) type;
BcTypeNode generic = vectorType.getGeneric();
if (generic != null)
{
tryAddUniqueNamespace(imports, generic);
}
}
}
}
private static void addToImport(BcTypeNode bcType)
{
if (canBeClass(bcType))
{
assert lastBcClass != null;
lastBcClass.addToImport(bcType);
}
}
private static String getClassName(BcClassDefinitionNode bcClass)
{
return BcCodeCs.type(bcClass.getName());
}
public static BcTypeNode evaluateType(Node node)
{
if (node instanceof MemberExpressionNode)
{
return evaluateMemberExpression((MemberExpressionNode) node);
}
if (node instanceof IdentifierNode)
{
IdentifierNode identifier = (IdentifierNode) node;
return findIdentifierType(BcCodeCs.identifier(identifier));
}
if (node instanceof LiteralNumberNode)
{
LiteralNumberNode numberNode = (LiteralNumberNode) node;
return numberNode.value.indexOf('.') != -1 ? BcTypeNode.create("float") : BcTypeNode.create("int");
}
if (node instanceof LiteralStringNode)
{
return BcTypeNode.create(classString);
}
if (node instanceof LiteralBooleanNode)
{
return BcTypeNode.create("BOOL");
}
if (node instanceof LiteralNullNode)
{
return BcTypeNode.create("null");
}
if (node instanceof ListNode)
{
ListNode listNode = (ListNode) node;
assert listNode.items.size() == 1;
return evaluateType(listNode.items.get(0));
}
if (node instanceof ThisExpressionNode)
{
assert lastBcClass != null;
return lastBcClass.getClassType();
}
if (node instanceof SuperExpressionNode)
{
assert lastBcClass != null;
assert lastBcClass.hasExtendsType();
return lastBcClass.getExtendsType();
}
if (node instanceof GetExpressionNode)
{
GetExpressionNode get = (GetExpressionNode) node;
return evaluateType(get.expr);
}
if (node instanceof ArgumentListNode)
{
ArgumentListNode args = (ArgumentListNode) node;
assert args.size() == 1;
return evaluateType(args.items.get(0));
}
if (node instanceof BinaryExpressionNode)
{
BinaryExpressionNode binaryNode = (BinaryExpressionNode) node;
BcTypeNode lhsType = evaluateType(binaryNode.lhs);
BcTypeNode rhsType = evaluateType(binaryNode.rhs);
if (binaryNode.op == Tokens.LOGICALAND_TOKEN ||
binaryNode.op == Tokens.LOGICALOR_TOKEN ||
binaryNode.op == Tokens.EQUALS_TOKEN ||
binaryNode.op == Tokens.NOTEQUALS_TOKEN ||
binaryNode.op == Tokens.GREATERTHAN_TOKEN ||
binaryNode.op == Tokens.GREATERTHANOREQUALS_TOKEN ||
binaryNode.op == Tokens.LESSTHAN_TOKEN ||
binaryNode.op == Tokens.LESSTHANOREQUALS_TOKEN ||
binaryNode.op == Tokens.IS_TOKEN)
{
return BcTypeNode.create(classBoolean);
}
if (typeEquals(lhsType, classString) || typeEquals(rhsType, classString))
{
return BcTypeNode.create(classString);
}
if (typeEquals(lhsType, "Number") || typeEquals(rhsType, "Number"))
{
return BcTypeNode.create("Number");
}
if (typeEquals(lhsType, "uint") || typeEquals(rhsType, "uint"))
{
return BcTypeNode.create("int");
}
if (typeEquals(lhsType, "int") || typeEquals(rhsType, "int"))
{
return BcTypeNode.create("int");
}
assert false;
}
if (node instanceof UnaryExpressionNode)
{
UnaryExpressionNode unary = (UnaryExpressionNode) node;
if (unary.expr instanceof MemberExpressionNode)
{
if (unary.op == Tokens.NOT_TOKEN)
{
return BcTypeNode.create(classBoolean);
}
return evaluateMemberExpression((MemberExpressionNode) unary.expr);
}
else
{
assert false;
}
}
assert false : node;
return null;
}
private static BcTypeNode evaluateMemberExpression(MemberExpressionNode node)
{
BcClassDefinitionNode baseClass = lastBcClass;
boolean hasCallTarget = node.base != null;
if (hasCallTarget)
{
if (node.base instanceof MemberExpressionNode)
{
assert node.base instanceof MemberExpressionNode;
BcTypeNode baseType = evaluateMemberExpression((MemberExpressionNode) node.base);
assert baseType != null;
baseClass = baseType.getClassNode();
assert baseClass != null;
}
else if (node.base instanceof ThisExpressionNode)
{
// we're good
}
else if (node.base instanceof SuperExpressionNode)
{
baseClass = baseClass.getExtendsType().getClassNode(); // get supertype
}
else if (node.base instanceof ListNode)
{
ListNode list = (ListNode) node.base;
assert list.size() == 1 : list.size();
assert list.items.get(0) instanceof MemberExpressionNode;
BcTypeNode baseType = evaluateMemberExpression((MemberExpressionNode) list.items.get(0));
assert baseType != null;
baseClass = baseType.getClassNode();
assert baseClass != null;
}
else
{
assert false;
}
}
if (node.selector instanceof SelectorNode)
{
SelectorNode selector = (SelectorNode) node.selector;
if (selector.expr instanceof IdentifierNode)
{
IdentifierNode identifier = (IdentifierNode) selector.expr;
BcTypeNode identifierType = findIdentifierType(baseClass, identifier, hasCallTarget);
if (identifierType != null)
{
return identifierType;
}
else
{
if (classEquals(baseClass, classXML))
{
return BcTypeNode.create(classXMLList); // dirty hack
}
else if (BcCodeCs.identifier(identifier).equals(BcCodeCs.thisCallMarker))
{
return lastBcClass.getClassType(); // this referes to the current class
}
else if (classEquals(baseClass, classObject))
{
return BcTypeNode.create(classObject);
}
}
}
else if (selector.expr instanceof ArgumentListNode)
{
BcTypeNode baseClassType = baseClass.getClassType();
if (baseClassType instanceof BcVectorTypeNode)
{
BcVectorTypeNode bcVector = (BcVectorTypeNode) baseClassType;
return bcVector.getGeneric();
}
else
{
return BcTypeNode.create(classObject); // no generics
}
}
else
{
assert false;
}
}
else
{
assert false;
}
return null;
}
private static BcTypeNode findIdentifierType(BcClassDefinitionNode baseClass, IdentifierNode identifier, boolean hasCallTarget)
{
if (identifier.isAttr())
{
return BcTypeNode.create(classString); // hack
}
String name = BcCodeCs.identifier(identifier);
// check if it's class
BcClassDefinitionNode bcClass = findClass(name);
if (bcClass != null)
{
return bcClass.getClassType();
}
if (BcCodeCs.isBasicType(name))
{
return BcTypeNode.create(name);
}
// search for local variable
if (!hasCallTarget && lastBcFunction != null)
{
BcVariableDeclaration bcVar = lastBcFunction.findVariable(name);
if (bcVar != null) return bcVar.getType();
}
// search for function
BcFunctionDeclaration bcFunc = baseClass.findFunction(name);
if (bcFunc != null || (bcFunc = findBuiltinFunc(name)) != null)
{
if (bcFunc.hasReturnType())
{
return bcFunc.getReturnType();
}
return BcTypeNode.create("void");
}
// search for field
BcVariableDeclaration bcField = baseClass.findField(name);
if (bcField != null)
{
return bcField.getType();
}
return null;
}
private static BcTypeNode extractBcType(Node node)
{
BcTypeNode bcType = BcNodeHelper.extractBcType(node);
if (bcType instanceof BcVectorTypeNode)
{
BcClassDefinitionNode vectorGenericClass = findClass(classVector).clone();
vectorGenericClass.setClassType(bcType);
bcApiClasses.add(vectorGenericClass);
bcType.setClassNode(vectorGenericClass);
}
BcTypeNode.add(bcType.getNameEx(), bcType);
return bcType;
}
private static boolean classEquals(BcClassDefinitionNode classNode, String name)
{
return typeEquals(classNode.getClassType(), name);
}
private static boolean typeEquals(BcTypeNode type, String name)
{
return type == BcTypeNode.create(name);
}
private static boolean canBeClass(String name)
{
return findClass(name) != null;
}
private static boolean canBeClass(BcTypeNode type)
{
return canBeClass(type.getName());
}
}
| false | true | private static void process(CallExpressionNode node)
{
ListWriteDestination exprDest = new ListWriteDestination();
pushDest(exprDest);
process(node.expr);
popDest();
String identifier = exprDest.toString();
if (node.expr instanceof IdentifierNode)
{
if (lastBcMemberType == null)
{
lastBcMemberType = null;
if (!(identifier.equals(BcCodeCs.thisCallMarker) && identifier.equals(BcCodeCs.thisCallMarker)))
{
BcFunctionDeclaration bcFunc = findFunction(identifier);
if (bcFunc != null)
{
if (bcFunc.hasReturnType())
{
lastBcMemberType = bcFunc.getReturnType();
assert lastBcMemberType != null;
}
}
else if (node.is_new)
{
BcClassDefinitionNode bcNewClass = findClass(identifier);
assert bcNewClass != null : bcNewClass;
BcTypeNode bcClassType = bcNewClass.getClassType();
assert bcClassType != null : identifier;
lastBcMemberType = bcClassType;
}
}
}
else
{
BcClassDefinitionNode bcClass = lastBcMemberType.getClassNode();
assert bcClass != null;
BcFunctionDeclaration bcFunc = bcClass.findFunction(identifier);
if (bcFunc != null)
{
lastBcMemberType = bcFunc.getReturnType();
if (classEquals(bcClass, classString))
{
if (identifier.equals("toString"))
{
// turn toString() into ToString() for all strings
identifier = Character.toUpperCase(identifier.charAt(0)) + identifier.substring(1);
}
}
}
else
{
BcVariableDeclaration bcFuncVar = findVariable(bcClass, identifier);
if (bcFuncVar != null)
{
if (typeEquals(bcFuncVar.getType(), classFunction))
{
System.err.println("Warning! Function type: " + identifier);
lastBcMemberType = bcFuncVar.getType();
}
else
{
assert false : identifier;
}
}
else
{
assert false : identifier;
}
}
}
}
else if (node.expr instanceof MemberExpressionNode)
{
lastBcMemberType = evaluateMemberExpression((MemberExpressionNode) node.expr);
assert lastBcMemberType != null;
}
else
{
assert false : node;
}
ListWriteDestination argsDest = new ListWriteDestination();
if (node.args != null)
{
pushDest(argsDest);
process(node.args);
popDest();
}
BcTypeNode type = extractBcType(node.expr);
assert type != null : node.expr.getClass();
if (node.is_new)
{
if (type instanceof BcVectorTypeNode)
{
BcVectorTypeNode vectorType = (BcVectorTypeNode) type;
ObjectList<Node> args;
if (node.args != null && (args = node.args.items).size() == 1 && args.get(0) instanceof LiteralArrayNode)
{
LiteralArrayNode arrayNode = (LiteralArrayNode) args.get(0);
ArgumentListNode elementlist = arrayNode.elementlist;
WriteDestination initDest = new ListWriteDestination();
pushDest(initDest);
for (Node elementNode : elementlist.items)
{
initDest.write(".a(");
process(elementNode);
initDest.write(")");
}
popDest();
dest.write(BcCodeCs.construct(vectorType, elementlist.size()) + initDest);
}
else
{
dest.write(BcCodeCs.construct(vectorType, argsDest));
}
}
else
{
dest.write(BcCodeCs.construct(type, argsDest.toString()));
}
}
else if (node.expr instanceof MemberExpressionNode && ((MemberExpressionNode) node.expr).selector instanceof ApplyTypeExprNode)
{
assert type instanceof BcVectorTypeNode;
BcVectorTypeNode bcVector = (BcVectorTypeNode) type;
Node argNode = node.args.items.get(0);
if (argNode instanceof LiteralArrayNode)
{
LiteralArrayNode arrayNode = (LiteralArrayNode) argNode;
ArgumentListNode elementlist = arrayNode.elementlist;
WriteDestination initDest = new ListWriteDestination();
pushDest(initDest);
for (Node elementNode : elementlist.items)
{
initDest.write(" << ");
process(elementNode);
}
popDest();
dest.write(BcCodeCs.construct(bcVector, elementlist.size()) + initDest);
}
else
{
dest.write(BcCodeCs.construct(type, 1) + " << " + argsDest);
}
}
else
{
if (node.getMode() == Tokens.EMPTY_TOKEN && node.args != null && node.args.items.size() == 1)
{
if (canBeClass(type) || BcCodeCs.isBasicType(type))
{
addToImport(type);
dest.writef("((%s)(%s))", BcCodeCs.type(identifier), argsDest);
}
else
{
dest.writef("%s(%s)", identifier, argsDest);
}
}
else
{
dest.writef("%s(%s)", identifier, argsDest);
}
}
}
| private static void process(CallExpressionNode node)
{
ListWriteDestination exprDest = new ListWriteDestination();
pushDest(exprDest);
process(node.expr);
popDest();
String identifier = exprDest.toString();
if (node.expr instanceof IdentifierNode)
{
if (lastBcMemberType == null)
{
lastBcMemberType = null;
if (!(identifier.equals(BcCodeCs.thisCallMarker) && identifier.equals(BcCodeCs.thisCallMarker)))
{
BcFunctionDeclaration bcFunc = findFunction(identifier);
if (bcFunc != null)
{
if (bcFunc.hasReturnType())
{
lastBcMemberType = bcFunc.getReturnType();
assert lastBcMemberType != null;
}
}
else if (node.is_new)
{
BcClassDefinitionNode bcNewClass = findClass(identifier);
assert bcNewClass != null : bcNewClass;
BcTypeNode bcClassType = bcNewClass.getClassType();
assert bcClassType != null : identifier;
lastBcMemberType = bcClassType;
}
}
}
else
{
BcClassDefinitionNode bcClass = lastBcMemberType.getClassNode();
assert bcClass != null;
BcFunctionDeclaration bcFunc = bcClass.findFunction(identifier);
if (bcFunc != null)
{
lastBcMemberType = bcFunc.getReturnType();
if (classEquals(bcClass, classString))
{
if (identifier.equals("toString"))
{
// turn toString() into ToString() for all strings
identifier = Character.toUpperCase(identifier.charAt(0)) + identifier.substring(1);
}
}
}
else
{
BcVariableDeclaration bcFuncVar = findVariable(bcClass, identifier);
if (bcFuncVar != null)
{
if (typeEquals(bcFuncVar.getType(), classFunction))
{
System.err.println("Warning! Function type: " + identifier);
lastBcMemberType = bcFuncVar.getType();
}
else
{
assert false : identifier;
}
}
else
{
assert false : identifier;
}
}
}
}
else if (node.expr instanceof MemberExpressionNode)
{
lastBcMemberType = evaluateMemberExpression((MemberExpressionNode) node.expr);
assert lastBcMemberType != null;
}
else
{
assert false : node;
}
ListWriteDestination argsDest = new ListWriteDestination();
if (node.args != null)
{
pushDest(argsDest);
process(node.args);
popDest();
}
BcTypeNode type = extractBcType(node.expr);
assert type != null : node.expr.getClass();
if (node.is_new)
{
if (type instanceof BcVectorTypeNode)
{
BcVectorTypeNode vectorType = (BcVectorTypeNode) type;
ObjectList<Node> args;
if (node.args != null && (args = node.args.items).size() == 1 && args.get(0) instanceof LiteralArrayNode)
{
LiteralArrayNode arrayNode = (LiteralArrayNode) args.get(0);
ArgumentListNode elementlist = arrayNode.elementlist;
WriteDestination initDest = new ListWriteDestination();
pushDest(initDest);
for (Node elementNode : elementlist.items)
{
initDest.write(".a(");
process(elementNode);
initDest.write(")");
}
popDest();
dest.write(BcCodeCs.construct(vectorType, elementlist.size()) + initDest);
}
else
{
dest.write(BcCodeCs.construct(vectorType, argsDest));
}
}
else
{
dest.write(BcCodeCs.construct(type, argsDest.toString()));
}
}
else if (node.expr instanceof MemberExpressionNode && ((MemberExpressionNode) node.expr).selector instanceof ApplyTypeExprNode)
{
assert type instanceof BcVectorTypeNode;
BcVectorTypeNode bcVector = (BcVectorTypeNode) type;
Node argNode = node.args.items.get(0);
if (argNode instanceof LiteralArrayNode)
{
LiteralArrayNode arrayNode = (LiteralArrayNode) argNode;
ArgumentListNode elementlist = arrayNode.elementlist;
WriteDestination initDest = new ListWriteDestination();
pushDest(initDest);
int elementIndex = 0;
for (Node elementNode : elementlist.items)
{
process(elementNode);
if (++elementIndex < elementlist.size())
{
dest.write(", ");
}
}
popDest();
dest.write(BcCodeCs.construct(bcVector, initDest));
}
else
{
dest.write(BcCodeCs.construct(type, argsDest));
}
}
else
{
if (node.getMode() == Tokens.EMPTY_TOKEN && node.args != null && node.args.items.size() == 1)
{
if (canBeClass(type) || BcCodeCs.isBasicType(type))
{
addToImport(type);
dest.writef("((%s)(%s))", BcCodeCs.type(identifier), argsDest);
}
else
{
dest.writef("%s(%s)", identifier, argsDest);
}
}
else
{
dest.writef("%s(%s)", identifier, argsDest);
}
}
}
|
diff --git a/plugins/org.jboss.tools.forge.ui.ext/src/org/jboss/tools/forge/ui/ext/wizards/ForgeWizard.java b/plugins/org.jboss.tools.forge.ui.ext/src/org/jboss/tools/forge/ui/ext/wizards/ForgeWizard.java
index 1b110a6f..dc438ef8 100644
--- a/plugins/org.jboss.tools.forge.ui.ext/src/org/jboss/tools/forge/ui/ext/wizards/ForgeWizard.java
+++ b/plugins/org.jboss.tools.forge.ui.ext/src/org/jboss/tools/forge/ui/ext/wizards/ForgeWizard.java
@@ -1,179 +1,181 @@
/**
* Copyright 2013 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.jboss.tools.forge.ui.ext.wizards;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.wizard.IWizardContainer;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.swt.widgets.Shell;
import org.jboss.forge.addon.ui.controller.CommandController;
import org.jboss.forge.addon.ui.controller.WizardCommandController;
import org.jboss.forge.addon.ui.result.CompositeResult;
import org.jboss.forge.addon.ui.result.Failed;
import org.jboss.forge.addon.ui.result.Result;
import org.jboss.tools.forge.ui.ext.ForgeUIPlugin;
import org.jboss.tools.forge.ui.ext.context.UIContextImpl;
import org.jboss.tools.forge.ui.ext.listeners.EventBus;
import org.jboss.tools.forge.ui.notifications.NotificationType;
/**
*
* @author <a href="[email protected]">George Gastaldi</a>
*/
public class ForgeWizard extends MutableWizard {
private final CommandController controller;
private final UIContextImpl uiContext;
public ForgeWizard(String windowTitle, CommandController controller,
UIContextImpl contextImpl) {
this.controller = controller;
this.uiContext = contextImpl;
setWindowTitle(windowTitle);
setNeedsProgressMonitor(true);
setForcePreviousAndNextButtons(isWizard());
}
public UIContextImpl getUIContext() {
return uiContext;
}
@Override
public void addPages() {
addPage(createPage());
}
@Override
public boolean canFinish() {
return controller.canExecute();
}
@Override
public boolean performFinish() {
try {
IWizardContainer container = getContainer();
performFinish(container, container.getShell());
} catch (Exception e) {
ForgeUIPlugin.log(e);
}
return true;
}
public void performFinish(final IRunnableContext container,
final Shell shell) throws InvocationTargetException,
InterruptedException {
container.run(true, true, new IRunnableWithProgress() {
@Override
public void run(IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException {
try {
Map<Object, Object> attributeMap = uiContext
.getAttributeMap();
attributeMap.put(IProgressMonitor.class, monitor);
attributeMap.put(Shell.class, shell);
Result commandResult = controller.execute();
List<Result> results;
if (commandResult instanceof CompositeResult) {
results = ((CompositeResult) commandResult)
.getResults();
} else {
results = Arrays.asList(commandResult);
}
for (Result result : results) {
if (result != null) {
String message = result.getMessage();
if (message != null) {
+ NotificationType notificationType = result instanceof Failed ? NotificationType.ERROR
+ : NotificationType.INFO;
ForgeUIPlugin.displayMessage(getWindowTitle(),
- message, NotificationType.INFO);
+ message, notificationType);
}
if (result instanceof Failed) {
Throwable exception = ((Failed) result)
.getException();
if (exception != null) {
ForgeUIPlugin.log(exception);
ForgeUIPlugin.displayMessage(
getWindowTitle(), String
.valueOf(exception
.getMessage()),
NotificationType.ERROR);
}
}
}
EventBus.INSTANCE.fireWizardFinished(uiContext);
}
} catch (Exception e) {
ForgeUIPlugin.displayMessage(getWindowTitle(),
"Error while executing task, check Error log view",
NotificationType.ERROR);
ForgeUIPlugin.log(e);
} finally {
try {
controller.close();
} catch (Exception e) {
ForgeUIPlugin.log(e);
}
}
}
});
}
@Override
public boolean performCancel() {
EventBus.INSTANCE.fireWizardClosed(uiContext);
return true;
}
protected ForgeWizardPage createPage() {
return new ForgeWizardPage(this, controller);
}
private boolean isWizard() {
return controller instanceof WizardCommandController;
}
@Override
public IWizardPage getNextPage(IWizardPage page) {
IWizardPage nextPage = super.getNextPage(page);
if (nextPage != null) {
// Subsequent pages are stale. Remove all subsequent pages
removeSubsequentPages(nextPage);
nextPage = null;
}
if (nextPage == null) {
try {
addPage(createPage());
nextPage = super.getNextPage(page);
} catch (Exception e) {
ForgeUIPlugin.log(e);
}
}
return nextPage;
}
/**
* @param page
*/
private void removeSubsequentPages(IWizardPage page) {
List<ForgeWizardPage> pageList = getPageList();
int idx = pageList.indexOf(page);
List<ForgeWizardPage> subList = pageList.subList(idx, pageList.size());
for (ForgeWizardPage forgeWizardPage : subList) {
forgeWizardPage.dispose();
}
subList.clear();
}
}
| false | true | public void performFinish(final IRunnableContext container,
final Shell shell) throws InvocationTargetException,
InterruptedException {
container.run(true, true, new IRunnableWithProgress() {
@Override
public void run(IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException {
try {
Map<Object, Object> attributeMap = uiContext
.getAttributeMap();
attributeMap.put(IProgressMonitor.class, monitor);
attributeMap.put(Shell.class, shell);
Result commandResult = controller.execute();
List<Result> results;
if (commandResult instanceof CompositeResult) {
results = ((CompositeResult) commandResult)
.getResults();
} else {
results = Arrays.asList(commandResult);
}
for (Result result : results) {
if (result != null) {
String message = result.getMessage();
if (message != null) {
ForgeUIPlugin.displayMessage(getWindowTitle(),
message, NotificationType.INFO);
}
if (result instanceof Failed) {
Throwable exception = ((Failed) result)
.getException();
if (exception != null) {
ForgeUIPlugin.log(exception);
ForgeUIPlugin.displayMessage(
getWindowTitle(), String
.valueOf(exception
.getMessage()),
NotificationType.ERROR);
}
}
}
EventBus.INSTANCE.fireWizardFinished(uiContext);
}
} catch (Exception e) {
ForgeUIPlugin.displayMessage(getWindowTitle(),
"Error while executing task, check Error log view",
NotificationType.ERROR);
ForgeUIPlugin.log(e);
} finally {
try {
controller.close();
} catch (Exception e) {
ForgeUIPlugin.log(e);
}
}
}
});
}
| public void performFinish(final IRunnableContext container,
final Shell shell) throws InvocationTargetException,
InterruptedException {
container.run(true, true, new IRunnableWithProgress() {
@Override
public void run(IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException {
try {
Map<Object, Object> attributeMap = uiContext
.getAttributeMap();
attributeMap.put(IProgressMonitor.class, monitor);
attributeMap.put(Shell.class, shell);
Result commandResult = controller.execute();
List<Result> results;
if (commandResult instanceof CompositeResult) {
results = ((CompositeResult) commandResult)
.getResults();
} else {
results = Arrays.asList(commandResult);
}
for (Result result : results) {
if (result != null) {
String message = result.getMessage();
if (message != null) {
NotificationType notificationType = result instanceof Failed ? NotificationType.ERROR
: NotificationType.INFO;
ForgeUIPlugin.displayMessage(getWindowTitle(),
message, notificationType);
}
if (result instanceof Failed) {
Throwable exception = ((Failed) result)
.getException();
if (exception != null) {
ForgeUIPlugin.log(exception);
ForgeUIPlugin.displayMessage(
getWindowTitle(), String
.valueOf(exception
.getMessage()),
NotificationType.ERROR);
}
}
}
EventBus.INSTANCE.fireWizardFinished(uiContext);
}
} catch (Exception e) {
ForgeUIPlugin.displayMessage(getWindowTitle(),
"Error while executing task, check Error log view",
NotificationType.ERROR);
ForgeUIPlugin.log(e);
} finally {
try {
controller.close();
} catch (Exception e) {
ForgeUIPlugin.log(e);
}
}
}
});
}
|
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/JavaDebugHover.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/JavaDebugHover.java
index e4f4cf565..85ed56644 100644
--- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/JavaDebugHover.java
+++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/JavaDebugHover.java
@@ -1,220 +1,235 @@
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.debug.ui;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.core.model.IVariable;
import org.eclipse.debug.ui.DebugUITools;
import org.eclipse.debug.ui.IDebugUIConstants;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICodeAssist;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.ILocalVariable;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.debug.core.IJavaFieldVariable;
import org.eclipse.jdt.debug.core.IJavaStackFrame;
import org.eclipse.jdt.debug.core.IJavaThread;
import org.eclipse.jdt.debug.core.IJavaVariable;
import org.eclipse.jdt.internal.debug.core.JDIDebugPlugin;
import org.eclipse.jdt.internal.debug.ui.actions.AbstractDisplayOptionsAction;
import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.text.java.hover.IJavaEditorTextHover;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultInformationControl;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextHoverExtension;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
public class JavaDebugHover implements IJavaEditorTextHover, ITextHoverExtension {
private IEditorPart fEditor;
/* (non-Javadoc)
* @see org.eclipse.jdt.ui.text.java.hover.IJavaEditorTextHover#setEditor(org.eclipse.ui.IEditorPart)
*/
public void setEditor(IEditorPart editor) {
fEditor = editor;
}
/* (non-Javadoc)
* @see org.eclipse.jface.text.ITextHover#getHoverRegion(org.eclipse.jface.text.ITextViewer, int)
*/
public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
return JavaWordFinder.findWord(textViewer.getDocument(), offset);
}
/**
* Returns the stack frame in which to search for variables, or <code>null</code>
* if none.
*
* @return the stack frame in which to search for variables, or <code>null</code>
* if none
*/
protected IJavaStackFrame getFrame() {
IAdaptable adaptable = DebugUITools.getDebugContext();
if (adaptable != null) {
return (IJavaStackFrame)adaptable.getAdapter(IJavaStackFrame.class);
}
return null;
}
/* (non-Javadoc)
* @see org.eclipse.jface.text.ITextHover#getHoverInfo(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion)
*/
public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
IJavaStackFrame frame = getFrame();
if (frame != null) {
ICodeAssist codeAssist = null;
if (fEditor != null) {
IEditorInput input = fEditor.getEditorInput();
Object element = JavaUI.getWorkingCopyManager().getWorkingCopy(input);
if (element == null) {
element = input.getAdapter(IClassFile.class);
}
if (element instanceof ICodeAssist) {
codeAssist = ((ICodeAssist)element);
}
}
if (codeAssist == null) {
return getRemoteHoverInfo(frame, textViewer, hoverRegion);
} else {
try {
IJavaElement[] resolve = codeAssist.codeSelect(hoverRegion.getOffset(), 0);
for (int i = 0; i < resolve.length; i++) {
IJavaElement javaElement = resolve[i];
if (javaElement instanceof IField) {
IField field = (IField)javaElement;
- IJavaFieldVariable fieldVariable = frame.getThis().getField(field.getElementName(), Signature.createTypeSignature(field.getDeclaringType().getFullyQualifiedName(), true));
+ String typeSignature = Signature.createTypeSignature(field.getDeclaringType().getFullyQualifiedName(), true);
+ typeSignature = typeSignature.replace('.', '/');
+ IJavaFieldVariable fieldVariable = frame.getThis().getField(field.getElementName(), typeSignature);
if (fieldVariable != null) {
StringBuffer buf = new StringBuffer();
appendVariable(buf, fieldVariable);
return buf.toString();
}
break;
}
if (javaElement instanceof ILocalVariable) {
ILocalVariable var = (ILocalVariable)javaElement;
IJavaElement parent = var.getParent();
while (!(parent instanceof IMethod) && parent != null) {
parent = parent.getParent();
}
if (parent instanceof IMethod) {
IMethod method = (IMethod) parent;
- if (method.getSignature().equals(frame.getSignature())) {
+ boolean equal = false;
+ if (method.isBinary()) {
+ // compare resolved signatures
+ if (method.getSignature().equals(frame.getSignature())) {
+ equal = true;
+ }
+ } else {
+ // compare unresolved signatures
+ if (frame.getMethodName().equals(method.getElementName())
+ && frame.getDeclaringTypeName().endsWith(method.getDeclaringType().getElementName())) {
+ equal = true;
+ }
+ }
+ if (equal) {
return generateHoverForLocal(frame, var.getElementName());
}
}
break;
}
}
} catch (CoreException e) {
JDIDebugPlugin.log(e);
}
}
}
return null;
}
/**
* Generate hover info via a variable search, if the java element is not avilable.
*/
private String getRemoteHoverInfo(IJavaStackFrame frame, ITextViewer textViewer, IRegion hoverRegion) {
if (frame != null) {
try {
IDocument document= textViewer.getDocument();
if (document != null) {
String variableName= document.get(hoverRegion.getOffset(), hoverRegion.getLength());
return generateHoverForLocal(frame, variableName);
}
} catch (BadLocationException x) {
}
}
return null;
}
private String generateHoverForLocal(IJavaStackFrame frame, String varName) {
StringBuffer buffer= new StringBuffer();
try {
IVariable variable= frame.findVariable(varName);
if (variable != null) {
appendVariable(buffer, variable);
}
} catch (DebugException x) {
if (x.getStatus().getCode() != IJavaThread.ERR_THREAD_NOT_SUSPENDED) {
JDIDebugUIPlugin.log(x);
}
}
if (buffer.length() > 0) {
return buffer.toString();
}
return null;
}
/**
* Append HTML for the given variable to the given buffer
*/
private static void appendVariable(StringBuffer buffer, IVariable variable) throws DebugException {
JDIModelPresentation modelPresentation = getModelPresentation();
buffer.append("<p><pre>"); //$NON-NLS-1$
buffer.append(modelPresentation.getVariableText((IJavaVariable) variable));
buffer.append("</pre></p>"); //$NON-NLS-1$
}
/**
* Returns a configured model presentation for use displaying variables.
*/
private static JDIModelPresentation getModelPresentation() {
JDIModelPresentation presentation = new JDIModelPresentation();
String viewId= IDebugUIConstants.ID_VARIABLE_VIEW;
String showDetails = AbstractDisplayOptionsAction.getStringPreferenceValue(viewId, IJDIPreferencesConstants.PREF_SHOW_DETAILS);
presentation.setAttribute(JDIModelPresentation.SHOW_DETAILS, showDetails);
String[][] booleanPrefs= {{IJDIPreferencesConstants.PREF_SHOW_HEX, JDIModelPresentation.SHOW_HEX_VALUES},
{IJDIPreferencesConstants.PREF_SHOW_CHAR, JDIModelPresentation.SHOW_CHAR_VALUES},
{IJDIPreferencesConstants.PREF_SHOW_UNSIGNED, JDIModelPresentation.SHOW_UNSIGNED_VALUES}};
for (int i = 0; i < booleanPrefs.length; i++) {
boolean preferenceValue = AbstractDisplayOptionsAction.getBooleanPreferenceValue(viewId, booleanPrefs[i][0]);
presentation.setAttribute(booleanPrefs[i][1], (preferenceValue ? Boolean.TRUE : Boolean.FALSE));
}
return presentation;
}
/* (non-Javadoc)
* @see org.eclipse.jface.text.ITextHoverExtension#getHoverControlCreator()
*/
public IInformationControlCreator getHoverControlCreator() {
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE)) { //$NON-NLS-1$
return new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
return new DefaultInformationControl(parent, SWT.NONE,
new HTMLTextPresenter(true),
DebugUIMessages.getString("JavaDebugHover.16")); //$NON-NLS-1$
}
};
}
return null;
}
}
| false | true | public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
IJavaStackFrame frame = getFrame();
if (frame != null) {
ICodeAssist codeAssist = null;
if (fEditor != null) {
IEditorInput input = fEditor.getEditorInput();
Object element = JavaUI.getWorkingCopyManager().getWorkingCopy(input);
if (element == null) {
element = input.getAdapter(IClassFile.class);
}
if (element instanceof ICodeAssist) {
codeAssist = ((ICodeAssist)element);
}
}
if (codeAssist == null) {
return getRemoteHoverInfo(frame, textViewer, hoverRegion);
} else {
try {
IJavaElement[] resolve = codeAssist.codeSelect(hoverRegion.getOffset(), 0);
for (int i = 0; i < resolve.length; i++) {
IJavaElement javaElement = resolve[i];
if (javaElement instanceof IField) {
IField field = (IField)javaElement;
IJavaFieldVariable fieldVariable = frame.getThis().getField(field.getElementName(), Signature.createTypeSignature(field.getDeclaringType().getFullyQualifiedName(), true));
if (fieldVariable != null) {
StringBuffer buf = new StringBuffer();
appendVariable(buf, fieldVariable);
return buf.toString();
}
break;
}
if (javaElement instanceof ILocalVariable) {
ILocalVariable var = (ILocalVariable)javaElement;
IJavaElement parent = var.getParent();
while (!(parent instanceof IMethod) && parent != null) {
parent = parent.getParent();
}
if (parent instanceof IMethod) {
IMethod method = (IMethod) parent;
if (method.getSignature().equals(frame.getSignature())) {
return generateHoverForLocal(frame, var.getElementName());
}
}
break;
}
}
} catch (CoreException e) {
JDIDebugPlugin.log(e);
}
}
}
return null;
}
| public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
IJavaStackFrame frame = getFrame();
if (frame != null) {
ICodeAssist codeAssist = null;
if (fEditor != null) {
IEditorInput input = fEditor.getEditorInput();
Object element = JavaUI.getWorkingCopyManager().getWorkingCopy(input);
if (element == null) {
element = input.getAdapter(IClassFile.class);
}
if (element instanceof ICodeAssist) {
codeAssist = ((ICodeAssist)element);
}
}
if (codeAssist == null) {
return getRemoteHoverInfo(frame, textViewer, hoverRegion);
} else {
try {
IJavaElement[] resolve = codeAssist.codeSelect(hoverRegion.getOffset(), 0);
for (int i = 0; i < resolve.length; i++) {
IJavaElement javaElement = resolve[i];
if (javaElement instanceof IField) {
IField field = (IField)javaElement;
String typeSignature = Signature.createTypeSignature(field.getDeclaringType().getFullyQualifiedName(), true);
typeSignature = typeSignature.replace('.', '/');
IJavaFieldVariable fieldVariable = frame.getThis().getField(field.getElementName(), typeSignature);
if (fieldVariable != null) {
StringBuffer buf = new StringBuffer();
appendVariable(buf, fieldVariable);
return buf.toString();
}
break;
}
if (javaElement instanceof ILocalVariable) {
ILocalVariable var = (ILocalVariable)javaElement;
IJavaElement parent = var.getParent();
while (!(parent instanceof IMethod) && parent != null) {
parent = parent.getParent();
}
if (parent instanceof IMethod) {
IMethod method = (IMethod) parent;
boolean equal = false;
if (method.isBinary()) {
// compare resolved signatures
if (method.getSignature().equals(frame.getSignature())) {
equal = true;
}
} else {
// compare unresolved signatures
if (frame.getMethodName().equals(method.getElementName())
&& frame.getDeclaringTypeName().endsWith(method.getDeclaringType().getElementName())) {
equal = true;
}
}
if (equal) {
return generateHoverForLocal(frame, var.getElementName());
}
}
break;
}
}
} catch (CoreException e) {
JDIDebugPlugin.log(e);
}
}
}
return null;
}
|
diff --git a/core/src/processing/core/PApplet.java b/core/src/processing/core/PApplet.java
index 16c0bbc29..c38ac90e0 100644
--- a/core/src/processing/core/PApplet.java
+++ b/core/src/processing/core/PApplet.java
@@ -1,15237 +1,15253 @@
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2004-12 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
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, version 2.1.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
package processing.core;
import processing.data.*;
import processing.event.*;
import processing.event.Event;
import processing.opengl.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.*;
import java.io.*;
import java.lang.reflect.*;
import java.net.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
import java.util.zip.*;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
/**
* Base class for all sketches that use processing.core.
* <p/>
* Note that you should not use AWT or Swing components inside a Processing
* applet. The surface is made to automatically update itself, and will cause
* problems with redraw of components drawn above it. If you'd like to
* integrate other Java components, see below.
* <p/>
* The <A HREF="http://wiki.processing.org/w/Window_Size_and_Full_Screen">
* Window Size and Full Screen</A> page on the Wiki has useful information
* about sizing, multiple displays, full screen, etc.
* <p/>
* As of release 0145, Processing uses active mode rendering in all cases.
* All animation tasks happen on the "Processing Animation Thread". The
* setup() and draw() methods are handled by that thread, and events (like
* mouse movement and key presses, which are fired by the event dispatch
* thread or EDT) are queued to be (safely) handled at the end of draw().
* For code that needs to run on the EDT, use SwingUtilities.invokeLater().
* When doing so, be careful to synchronize between that code (since
* invokeLater() will make your code run from the EDT) and the Processing
* animation thread. Use of a callback function or the registerXxx() methods
* in PApplet can help ensure that your code doesn't do something naughty.
* <p/>
* As of Processing 2.0, we have discontinued support for versions of Java
* prior to 1.6. We don't have enough people to support it, and for a
* project of our (tiny) size, we should be focusing on the future, rather
* than working around legacy Java code.
* <p/>
* This class extends Applet instead of JApplet because 1) historically,
* we supported Java 1.1, which does not include Swing (without an
* additional, sizable, download), and 2) Swing is a bloated piece of crap.
* A Processing applet is a heavyweight AWT component, and can be used the
* same as any other AWT component, with or without Swing.
* <p/>
* Similarly, Processing runs in a Frame and not a JFrame. However, there's
* nothing to prevent you from embedding a PApplet into a JFrame, it's just
* that the base version uses a regular AWT frame because there's simply
* no need for Swing in that context. If people want to use Swing, they can
* embed themselves as they wish.
* <p/>
* It is possible to use PApplet, along with core.jar in other projects.
* This also allows you to embed a Processing drawing area into another Java
* application. This means you can use standard GUI controls with a Processing
* sketch. Because AWT and Swing GUI components cannot be used on top of a
* PApplet, you can instead embed the PApplet inside another GUI the way you
* would any other Component.
* <p/>
* Because the default animation thread will run at 60 frames per second,
* an embedded PApplet can make the parent application sluggish. You can use
* frameRate() to make it update less often, or you can use noLoop() and loop()
* to disable and then re-enable looping. If you want to only update the sketch
* intermittently, use noLoop() inside setup(), and redraw() whenever the
* screen needs to be updated once (or loop() to re-enable the animation
* thread). The following example embeds a sketch and also uses the noLoop()
* and redraw() methods. You need not use noLoop() and redraw() when embedding
* if you want your application to animate continuously.
* <PRE>
* public class ExampleFrame extends Frame {
*
* public ExampleFrame() {
* super("Embedded PApplet");
*
* setLayout(new BorderLayout());
* PApplet embed = new Embedded();
* add(embed, BorderLayout.CENTER);
*
* // important to call this whenever embedding a PApplet.
* // It ensures that the animation thread is started and
* // that other internal variables are properly set.
* embed.init();
* }
* }
*
* public class Embedded extends PApplet {
*
* public void setup() {
* // original setup code here ...
* size(400, 400);
*
* // prevent thread from starving everything else
* noLoop();
* }
*
* public void draw() {
* // drawing code goes here
* }
*
* public void mousePressed() {
* // do something based on mouse movement
*
* // update the screen (run draw once)
* redraw();
* }
* }
* </PRE>
* @usage Web & Application
*/
public class PApplet extends Applet
implements PConstants, Runnable,
MouseListener, MouseMotionListener, KeyListener, FocusListener
{
/**
* Full name of the Java version (i.e. 1.5.0_11).
* Prior to 0125, this was only the first three digits.
*/
public static final String javaVersionName =
System.getProperty("java.version");
/**
* Version of Java that's in use, whether 1.1 or 1.3 or whatever,
* stored as a float.
* <p>
* Note that because this is stored as a float, the values may
* not be <EM>exactly</EM> 1.3 or 1.4. Instead, make sure you're
* comparing against 1.3f or 1.4f, which will have the same amount
* of error (i.e. 1.40000001). This could just be a double, but
* since Processing only uses floats, it's safer for this to be a float
* because there's no good way to specify a double with the preproc.
*/
public static final float javaVersion =
new Float(javaVersionName.substring(0, 3)).floatValue();
/**
* Current platform in use.
* <p>
* Equivalent to System.getProperty("os.name"), just used internally.
*/
/**
* Current platform in use, one of the
* PConstants WINDOWS, MACOSX, MACOS9, LINUX or OTHER.
*/
static public int platform;
/**
* Name associated with the current 'platform' (see PConstants.platformNames)
*/
//static public String platformName;
static {
String osname = System.getProperty("os.name");
if (osname.indexOf("Mac") != -1) {
platform = MACOSX;
} else if (osname.indexOf("Windows") != -1) {
platform = WINDOWS;
} else if (osname.equals("Linux")) { // true for the ibm vm
platform = LINUX;
} else {
platform = OTHER;
}
}
/**
* Setting for whether to use the Quartz renderer on OS X. The Quartz
* renderer is on its way out for OS X, but Processing uses it by default
* because it's much faster than the Sun renderer. In some cases, however,
* the Quartz renderer is preferred. For instance, fonts are less thick
* when using the Sun renderer, so to improve how fonts look,
* change this setting before you call PApplet.main().
* <pre>
* static public void main(String[] args) {
* PApplet.useQuartz = false;
* PApplet.main(new String[] { "YourSketch" });
* }
* </pre>
* This setting must be called before any AWT work happens, so that's why
* it's such a terrible hack in how it's employed here. Calling setProperty()
* inside setup() is a joke, since it's long since the AWT has been invoked.
*/
// static public boolean useQuartz = true;
static public boolean useQuartz = false;
/**
* Whether to use native (AWT) dialogs for selectInput and selectOutput.
* The native dialogs on Linux tend to be pretty awful. With selectFolder()
* this is ignored, because there is no native folder selector, except on
* Mac OS X. On OS X, the native folder selector will be used unless
* useNativeSelect is set to false.
*/
static public boolean useNativeSelect = (platform != LINUX);
// /**
// * Modifier flags for the shortcut key used to trigger menus.
// * (Cmd on Mac OS X, Ctrl on Linux and Windows)
// */
// static public final int MENU_SHORTCUT =
// Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
/** The PGraphics renderer associated with this PApplet */
public PGraphics g;
/** The frame containing this applet (if any) */
public Frame frame;
// /**
// * Usually just 0, but with multiple displays, the X and Y coordinates of
// * the screen will depend on the current screen's position relative to
// * the other displays.
// */
// public int displayX;
// public int displayY;
/**
* ( begin auto-generated from screenWidth.xml )
*
* System variable which stores the width of the computer screen. For
* example, if the current screen resolution is 1024x768,
* <b>displayWidth</b> is 1024 and <b>displayHeight</b> is 768. These
* dimensions are useful when exporting full-screen applications.
* <br /><br />
* To ensure that the sketch takes over the entire screen, use "Present"
* instead of "Run". Otherwise the window will still have a frame border
* around it and not be placed in the upper corner of the screen. On Mac OS
* X, the menu bar will remain present unless "Present" mode is used.
*
* ( end auto-generated )
* @webref environment
*/
public int displayWidth;
/**
* ( begin auto-generated from screenHeight.xml )
*
* System variable that stores the height of the computer screen. For
* example, if the current screen resolution is 1024x768,
* <b>screenWidth</b> is 1024 and <b>screenHeight</b> is 768. These
* dimensions are useful when exporting full-screen applications.
* <br /><br />
* To ensure that the sketch takes over the entire screen, use "Present"
* instead of "Run". Otherwise the window will still have a frame border
* around it and not be placed in the upper corner of the screen. On Mac OS
* X, the menu bar will remain present unless "Present" mode is used.
*
* ( end auto-generated )
* @webref environment
*/
public int displayHeight;
/**
* A leech graphics object that is echoing all events.
*/
public PGraphics recorder;
/**
* Command line options passed in from main().
* <p>
* This does not include the arguments passed in to PApplet itself.
*/
public String[] args;
/** Path to sketch folder */
public String sketchPath; //folder;
static final boolean DEBUG = false;
// static final boolean DEBUG = true;
/** Default width and height for applet when not specified */
static public final int DEFAULT_WIDTH = 100;
static public final int DEFAULT_HEIGHT = 100;
/**
* Minimum dimensions for the window holding an applet. This varies between
* platforms, Mac OS X 10.3 (confirmed with 10.7 and Java 6) can do any
* height but requires at least 128 pixels width. Windows XP has another
* set of limitations. And for all I know, Linux probably lets you make
* windows with negative sizes.
*/
static public final int MIN_WINDOW_WIDTH = 128;
static public final int MIN_WINDOW_HEIGHT = 128;
/**
* Gets set by main() if --present (old) or --full-screen (newer) are used,
* and is returned by sketchFullscreen() when initializing in main().
*/
// protected boolean fullScreen = false;
/**
* Exception thrown when size() is called the first time.
* <p>
* This is used internally so that setup() is forced to run twice
* when the renderer is changed. This is the only way for us to handle
* invoking the new renderer while also in the midst of rendering.
*/
static public class RendererChangeException extends RuntimeException { }
/**
* true if no size() command has been executed. This is used to wait until
* a size has been set before placing in the window and showing it.
*/
public boolean defaultSize;
/** Storage for the current renderer size to avoid re-allocation. */
Dimension currentSize = new Dimension();
// volatile boolean resizeRequest;
// volatile int resizeWidth;
// volatile int resizeHeight;
/**
* ( begin auto-generated from pixels.xml )
*
* Array containing the values for all the pixels in the display window.
* These values are of the color datatype. This array is the size of the
* display window. For example, if the image is 100x100 pixels, there will
* be 10000 values and if the window is 200x300 pixels, there will be 60000
* values. The <b>index</b> value defines the position of a value within
* the array. For example, the statement <b>color b = pixels[230]</b> will
* set the variable <b>b</b> to be equal to the value at that location in
* the array.<br />
* <br />
* Before accessing this array, the data must loaded with the
* <b>loadPixels()</b> function. After the array data has been modified,
* the <b>updatePixels()</b> function must be run to update the changes.
* Without <b>loadPixels()</b>, running the code may (or will in future
* releases) result in a NullPointerException.
*
* ( end auto-generated )
*
* @webref image:pixels
* @see PApplet#loadPixels()
* @see PApplet#updatePixels()
* @see PApplet#get(int, int, int, int)
* @see PApplet#set(int, int, int)
* @see PImage
*/
public int pixels[];
/**
* ( begin auto-generated from width.xml )
*
* System variable which stores the width of the display window. This value
* is set by the first parameter of the <b>size()</b> function. For
* example, the function call <b>size(320, 240)</b> sets the <b>width</b>
* variable to the value 320. The value of <b>width</b> is zero until
* <b>size()</b> is called.
*
* ( end auto-generated )
* @webref environment
*/
public int width;
/**
* ( begin auto-generated from height.xml )
*
* System variable which stores the height of the display window. This
* value is set by the second parameter of the <b>size()</b> function. For
* example, the function call <b>size(320, 240)</b> sets the <b>height</b>
* variable to the value 240. The value of <b>height</b> is zero until
* <b>size()</b> is called.
*
* ( end auto-generated )
* @webref environment
*
*/
public int height;
/**
* ( begin auto-generated from mouseX.xml )
*
* The system variable <b>mouseX</b> always contains the current horizontal
* coordinate of the mouse.
*
* ( end auto-generated )
* @webref input:mouse
* @see PApplet#mouseY
* @see PApplet#mousePressed
* @see PApplet#mousePressed()
* @see PApplet#mouseReleased()
* @see PApplet#mouseMoved()
* @see PApplet#mouseDragged()
*
*
*/
public int mouseX;
/**
* ( begin auto-generated from mouseY.xml )
*
* The system variable <b>mouseY</b> always contains the current vertical
* coordinate of the mouse.
*
* ( end auto-generated )
* @webref input:mouse
* @see PApplet#mouseX
* @see PApplet#mousePressed
* @see PApplet#mousePressed()
* @see PApplet#mouseReleased()
* @see PApplet#mouseMoved()
* @see PApplet#mouseDragged()
*
*/
public int mouseY;
/**
* ( begin auto-generated from pmouseX.xml )
*
* The system variable <b>pmouseX</b> always contains the horizontal
* position of the mouse in the frame previous to the current frame.<br />
* <br />
* You may find that <b>pmouseX</b> and <b>pmouseY</b> have different
* values inside <b>draw()</b> and inside events like <b>mousePressed()</b>
* and <b>mouseMoved()</b>. This is because they're used for different
* roles, so don't mix them. Inside <b>draw()</b>, <b>pmouseX</b> and
* <b>pmouseY</b> update only once per frame (once per trip through your
* <b>draw()</b>). But, inside mouse events, they update each time the
* event is called. If they weren't separated, then the mouse would be read
* only once per frame, making response choppy. If the mouse variables were
* always updated multiple times per frame, using <NOBR><b>line(pmouseX,
* pmouseY, mouseX, mouseY)</b></NOBR> inside <b>draw()</b> would have lots
* of gaps, because <b>pmouseX</b> may have changed several times in
* between the calls to <b>line()</b>. Use <b>pmouseX</b> and
* <b>pmouseY</b> inside <b>draw()</b> if you want values relative to the
* previous frame. Use <b>pmouseX</b> and <b>pmouseY</b> inside the mouse
* functions if you want continuous response.
*
* ( end auto-generated )
* @webref input:mouse
* @see PApplet#pmouseY
* @see PApplet#mouseX
* @see PApplet#mouseY
*/
public int pmouseX;
/**
* ( begin auto-generated from pmouseY.xml )
*
* The system variable <b>pmouseY</b> always contains the vertical position
* of the mouse in the frame previous to the current frame. More detailed
* information about how <b>pmouseY</b> is updated inside of <b>draw()</b>
* and mouse events is explained in the reference for <b>pmouseX</b>.
*
* ( end auto-generated )
* @webref input:mouse
* @see PApplet#pmouseX
* @see PApplet#mouseX
* @see PApplet#mouseY
*/
public int pmouseY;
/**
* previous mouseX/Y for the draw loop, separated out because this is
* separate from the pmouseX/Y when inside the mouse event handlers.
*/
protected int dmouseX, dmouseY;
/**
* pmouseX/Y for the event handlers (mousePressed(), mouseDragged() etc)
* these are different because mouse events are queued to the end of
* draw, so the previous position has to be updated on each event,
* as opposed to the pmouseX/Y that's used inside draw, which is expected
* to be updated once per trip through draw().
*/
protected int emouseX, emouseY;
/**
* Used to set pmouseX/Y to mouseX/Y the first time mouseX/Y are used,
* otherwise pmouseX/Y are always zero, causing a nasty jump.
* <p>
* Just using (frameCount == 0) won't work since mouseXxxxx()
* may not be called until a couple frames into things.
* <p>
* @deprecated Please refrain from using this variable, it will be removed
* from future releases of Processing because it cannot be used consistently
* across platforms and input methods.
*/
@Deprecated
public boolean firstMouse;
/**
* ( begin auto-generated from mouseButton.xml )
*
* Processing automatically tracks if the mouse button is pressed and which
* button is pressed. The value of the system variable <b>mouseButton</b>
* is either <b>LEFT</b>, <b>RIGHT</b>, or <b>CENTER</b> depending on which
* button is pressed.
*
* ( end auto-generated )
*
* <h3>Advanced:</h3>
*
* If running on Mac OS, a ctrl-click will be interpreted as the right-hand
* mouse button (unlike Java, which reports it as the left mouse).
* @webref input:mouse
* @see PApplet#mouseX
* @see PApplet#mouseY
* @see PApplet#mousePressed()
* @see PApplet#mouseReleased()
* @see PApplet#mouseMoved()
* @see PApplet#mouseDragged()
*/
public int mouseButton;
/**
* ( begin auto-generated from mousePressed_var.xml )
*
* Variable storing if a mouse button is pressed. The value of the system
* variable <b>mousePressed</b> is true if a mouse button is pressed and
* false if a button is not pressed.
*
* ( end auto-generated )
* @webref input:mouse
* @see PApplet#mouseX
* @see PApplet#mouseY
* @see PApplet#mouseReleased()
* @see PApplet#mouseMoved()
* @see PApplet#mouseDragged()
*/
public boolean mousePressed;
/**
* @deprecated Use a mouse event handler that passes an event instead.
*/
@Deprecated
public MouseEvent mouseEvent;
/**
* ( begin auto-generated from key.xml )
*
* The system variable <b>key</b> always contains the value of the most
* recent key on the keyboard that was used (either pressed or released).
* <br/> <br/>
* For non-ASCII keys, use the <b>keyCode</b> variable. The keys included
* in the ASCII specification (BACKSPACE, TAB, ENTER, RETURN, ESC, and
* DELETE) do not require checking to see if they key is coded, and you
* should simply use the <b>key</b> variable instead of <b>keyCode</b> If
* you're making cross-platform projects, note that the ENTER key is
* commonly used on PCs and Unix and the RETURN key is used instead on
* Macintosh. Check for both ENTER and RETURN to make sure your program
* will work for all platforms.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
*
* Last key pressed.
* <p>
* If it's a coded key, i.e. UP/DOWN/CTRL/SHIFT/ALT,
* this will be set to CODED (0xffff or 65535).
*
* @webref input:keyboard
* @see PApplet#keyCode
* @see PApplet#keyPressed
* @see PApplet#keyPressed()
* @see PApplet#keyReleased()
*/
public char key;
/**
* ( begin auto-generated from keyCode.xml )
*
* The variable <b>keyCode</b> is used to detect special keys such as the
* UP, DOWN, LEFT, RIGHT arrow keys and ALT, CONTROL, SHIFT. When checking
* for these keys, it's first necessary to check and see if the key is
* coded. This is done with the conditional "if (key == CODED)" as shown in
* the example.
* <br/> <br/>
* The keys included in the ASCII specification (BACKSPACE, TAB, ENTER,
* RETURN, ESC, and DELETE) do not require checking to see if they key is
* coded, and you should simply use the <b>key</b> variable instead of
* <b>keyCode</b> If you're making cross-platform projects, note that the
* ENTER key is commonly used on PCs and Unix and the RETURN key is used
* instead on Macintosh. Check for both ENTER and RETURN to make sure your
* program will work for all platforms.
* <br/> <br/>
* For users familiar with Java, the values for UP and DOWN are simply
* shorter versions of Java's KeyEvent.VK_UP and KeyEvent.VK_DOWN. Other
* keyCode values can be found in the Java <a
* href="http://download.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html">KeyEvent</a> reference.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* When "key" is set to CODED, this will contain a Java key code.
* <p>
* For the arrow keys, keyCode will be one of UP, DOWN, LEFT and RIGHT.
* Also available are ALT, CONTROL and SHIFT. A full set of constants
* can be obtained from java.awt.event.KeyEvent, from the VK_XXXX variables.
*
* @webref input:keyboard
* @see PApplet#key
* @see PApplet#keyPressed
* @see PApplet#keyPressed()
* @see PApplet#keyReleased()
*/
public int keyCode;
/**
* ( begin auto-generated from keyPressed_var.xml )
*
* The boolean system variable <b>keyPressed</b> is <b>true</b> if any key
* is pressed and <b>false</b> if no keys are pressed.
*
* ( end auto-generated )
* @webref input:keyboard
* @see PApplet#key
* @see PApplet#keyCode
* @see PApplet#keyPressed()
* @see PApplet#keyReleased()
*/
public boolean keyPressed;
/**
* The last KeyEvent object passed into a mouse function.
* @deprecated Use a key event handler that passes an event instead.
*/
@Deprecated
public KeyEvent keyEvent;
/**
* ( begin auto-generated from focused.xml )
*
* Confirms if a Processing program is "focused", meaning that it is active
* and will accept input from mouse or keyboard. This variable is "true" if
* it is focused and "false" if not. This variable is often used when you
* want to warn people they need to click on or roll over an applet before
* it will work.
*
* ( end auto-generated )
* @webref environment
*/
public boolean focused = false;
/**
* Confirms if a Processing program is running inside a web browser. This
* variable is "true" if the program is online and "false" if not.
*/
@Deprecated
public boolean online = false;
// This is deprecated because it's poorly named (and even more poorly
// understood). Further, we'll probably be removing applets soon, in which
// case this won't work at all. If you want this feature, you can check
// whether getAppletContext() returns null.
/**
* Time in milliseconds when the applet was started.
* <p>
* Used by the millis() function.
*/
long millisOffset = System.currentTimeMillis();
/**
* ( begin auto-generated from frameRate_var.xml )
*
* The system variable <b>frameRate</b> contains the approximate frame rate
* of the software as it executes. The initial value is 10 fps and is
* updated with each frame. The value is averaged (integrated) over several
* frames. As such, this value won't be valid until after 5-10 frames.
*
* ( end auto-generated )
* @webref environment
* @see PApplet#frameRate(float)
*/
public float frameRate = 10;
/** Last time in nanoseconds that frameRate was checked */
protected long frameRateLastNanos = 0;
/** As of release 0116, frameRate(60) is called as a default */
protected float frameRateTarget = 60;
protected long frameRatePeriod = 1000000000L / 60L;
protected boolean looping;
/** flag set to true when a redraw is asked for by the user */
protected boolean redraw;
/**
* ( begin auto-generated from frameCount.xml )
*
* The system variable <b>frameCount</b> contains the number of frames
* displayed since the program started. Inside <b>setup()</b> the value is
* 0 and and after the first iteration of draw it is 1, etc.
*
* ( end auto-generated )
* @webref environment
* @see PApplet#frameRate(float)
*/
public int frameCount;
/** true if the sketch has stopped permanently. */
public volatile boolean finished;
/**
* true if the animation thread is paused.
*/
public volatile boolean paused;
/**
* true if exit() has been called so that things shut down
* once the main thread kicks off.
*/
protected boolean exitCalled;
Object pauseObject = new Object();
Thread thread;
// messages to send if attached as an external vm
/**
* Position of the upper-lefthand corner of the editor window
* that launched this applet.
*/
static public final String ARGS_EDITOR_LOCATION = "--editor-location";
/**
* Location for where to position the applet window on screen.
* <p>
* This is used by the editor to when saving the previous applet
* location, or could be used by other classes to launch at a
* specific position on-screen.
*/
static public final String ARGS_EXTERNAL = "--external";
static public final String ARGS_LOCATION = "--location";
static public final String ARGS_DISPLAY = "--display";
static public final String ARGS_BGCOLOR = "--bgcolor";
/** @deprecated use --full-screen instead. */
static public final String ARGS_PRESENT = "--present";
static public final String ARGS_FULL_SCREEN = "--full-screen";
// static public final String ARGS_EXCLUSIVE = "--exclusive";
static public final String ARGS_STOP_COLOR = "--stop-color";
static public final String ARGS_HIDE_STOP = "--hide-stop";
/**
* Allows the user or PdeEditor to set a specific sketch folder path.
* <p>
* Used by PdeEditor to pass in the location where saveFrame()
* and all that stuff should write things.
*/
static public final String ARGS_SKETCH_FOLDER = "--sketch-path";
/**
* When run externally to a PdeEditor,
* this is sent by the applet when it quits.
*/
//static public final String EXTERNAL_QUIT = "__QUIT__";
static public final String EXTERNAL_STOP = "__STOP__";
/**
* When run externally to a PDE Editor, this is sent by the applet
* whenever the window is moved.
* <p>
* This is used so that the editor can re-open the sketch window
* in the same position as the user last left it.
*/
static public final String EXTERNAL_MOVE = "__MOVE__";
/** true if this sketch is being run by the PDE */
boolean external = false;
static final String ERROR_MIN_MAX =
"Cannot use min() or max() on an empty array.";
// during rev 0100 dev cycle, working on new threading model,
// but need to disable and go conservative with changes in order
// to get pdf and audio working properly first.
// for 0116, the CRUSTY_THREADS are being disabled to fix lots of bugs.
//static final boolean CRUSTY_THREADS = false; //true;
/**
* Applet initialization. This can do GUI work because the components have
* not been 'realized' yet: things aren't visible, displayed, etc.
*/
@Override
public void init() {
// println("init() called " + Integer.toHexString(hashCode()));
// using a local version here since the class variable is deprecated
// Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
// screenWidth = screen.width;
// screenHeight = screen.height;
// send tab keys through to the PApplet
setFocusTraversalKeysEnabled(false);
//millisOffset = System.currentTimeMillis(); // moved to the variable declaration
finished = false; // just for clarity
// this will be cleared by draw() if it is not overridden
looping = true;
redraw = true; // draw this guy once
firstMouse = true;
// these need to be inited before setup
// sizeMethods = new RegisteredMethods();
// pauseMethods = new RegisteredMethods();
// resumeMethods = new RegisteredMethods();
// preMethods = new RegisteredMethods();
// drawMethods = new RegisteredMethods();
// postMethods = new RegisteredMethods();
// mouseEventMethods = new RegisteredMethods();
// keyEventMethods = new RegisteredMethods();
// disposeMethods = new RegisteredMethods();
try {
getAppletContext();
online = true;
} catch (NullPointerException e) {
online = false;
}
try {
if (sketchPath == null) {
sketchPath = System.getProperty("user.dir");
}
} catch (Exception e) { } // may be a security problem
Dimension size = getSize();
if ((size.width != 0) && (size.height != 0)) {
// When this PApplet is embedded inside a Java application with other
// Component objects, its size() may already be set externally (perhaps
// by a LayoutManager). In this case, honor that size as the default.
// Size of the component is set, just create a renderer.
g = makeGraphics(size.width, size.height, sketchRenderer(), null, true);
// This doesn't call setSize() or setPreferredSize() because the fact
// that a size was already set means that someone is already doing it.
} else {
// Set the default size, until the user specifies otherwise
this.defaultSize = true;
int w = sketchWidth();
int h = sketchHeight();
g = makeGraphics(w, h, sketchRenderer(), null, true);
// Fire component resize event
setSize(w, h);
setPreferredSize(new Dimension(w, h));
}
width = g.width;
height = g.height;
// addListeners(); // 2.0a6
// moved out of addListeners() in 2.0a6
addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
// Component c = e.getComponent();
// //System.out.println("componentResized() " + c);
// Rectangle bounds = c.getBounds();
// resizeRequest = true;
// resizeWidth = bounds.width;
// resizeHeight = bounds.height;
if (!looping) {
redraw();
}
}
});
// if (thread == null) {
// paused = true;
thread = new Thread(this, "Animation Thread");
thread.start();
// }
// this is automatically called in applets
// though it's here for applications anyway
// start();
}
public int sketchQuality() {
return 2;
}
public int sketchWidth() {
return DEFAULT_WIDTH;
}
public int sketchHeight() {
return DEFAULT_HEIGHT;
}
public String sketchRenderer() {
return JAVA2D;
}
public boolean sketchFullScreen() {
// return fullScreen;
return false;
}
public void orientation(int which) {
// ignore calls to the orientation command
}
/**
* Called by the browser or applet viewer to inform this applet that it
* should start its execution. It is called after the init method and
* each time the applet is revisited in a Web page.
* <p/>
* Called explicitly via the first call to PApplet.paint(), because
* PAppletGL needs to have a usable screen before getting things rolling.
*/
@Override
public void start() {
debug("start() called");
// new Exception().printStackTrace(System.out);
paused = false; // unpause the thread
resume();
// resumeMethods.handle();
handleMethods("resume");
debug("un-pausing thread");
synchronized (pauseObject) {
debug("start() calling pauseObject.notifyAll()");
// try {
pauseObject.notifyAll(); // wake up the animation thread
debug("un-pausing thread 3");
// } catch (InterruptedException e) { }
}
}
/**
* Called by the browser or applet viewer to inform
* this applet that it should stop its execution.
* <p/>
* Unfortunately, there are no guarantees from the Java spec
* when or if stop() will be called (i.e. on browser quit,
* or when moving between web pages), and it's not always called.
*/
@Override
public void stop() {
// this used to shut down the sketch, but that code has
// been moved to destroy/dispose()
// if (paused) {
// synchronized (pauseObject) {
// try {
// pauseObject.wait();
// } catch (InterruptedException e) {
// // waiting for this interrupt on a start() (resume) call
// }
// }
// }
// on the next trip through the animation thread, things will go sleepy-by
paused = true; // causes animation thread to sleep
pause();
handleMethods("pause");
// actual pause will happen in the run() method
// synchronized (pauseObject) {
// debug("stop() calling pauseObject.wait()");
// try {
// pauseObject.wait();
// } catch (InterruptedException e) {
// // waiting for this interrupt on a start() (resume) call
// }
// }
}
/**
* Sketch has been paused. Called when switching tabs in a browser or
* swapping to a different application on Android. Also called just before
* quitting. Use to safely disable things like serial, sound, or sensors.
*/
public void pause() { }
/**
* Sketch has resumed. Called when switching tabs in a browser or
* swapping to this application on Android. Also called on startup.
* Use this to safely disable things like serial, sound, or sensors.
*/
public void resume() { }
/**
* Called by the browser or applet viewer to inform this applet
* that it is being reclaimed and that it should destroy
* any resources that it has allocated.
* <p/>
* destroy() supposedly gets called as the applet viewer
* is shutting down the applet. stop() is called
* first, and then destroy() to really get rid of things.
* no guarantees on when they're run (on browser quit, or
* when moving between pages), though.
*/
@Override
public void destroy() {
this.dispose();
}
//////////////////////////////////////////////////////////////
/** Map of registered methods, stored by name. */
HashMap<String, RegisteredMethods> registerMap =
new HashMap<String, PApplet.RegisteredMethods>();
class RegisteredMethods {
int count;
Object[] objects;
// Because the Method comes from the class being called,
// it will be unique for most, if not all, objects.
Method[] methods;
Object[] emptyArgs = new Object[] { };
void handle() {
handle(emptyArgs);
}
void handle(Object[] args) {
for (int i = 0; i < count; i++) {
try {
methods[i].invoke(objects[i], args);
} catch (Exception e) {
// check for wrapped exception, get root exception
Throwable t;
if (e instanceof InvocationTargetException) {
InvocationTargetException ite = (InvocationTargetException) e;
t = ite.getCause();
} else {
t = e;
}
// check for RuntimeException, and allow to bubble up
if (t instanceof RuntimeException) {
// re-throw exception
throw (RuntimeException) t;
} else {
// trap and print as usual
t.printStackTrace();
}
}
}
}
void add(Object object, Method method) {
if (findIndex(object) == -1) {
if (objects == null) {
objects = new Object[5];
methods = new Method[5];
} else if (count == objects.length) {
objects = (Object[]) PApplet.expand(objects);
methods = (Method[]) PApplet.expand(methods);
}
objects[count] = object;
methods[count] = method;
count++;
} else {
die(method.getName() + "() already added for this instance of " +
object.getClass().getName());
}
}
/**
* Removes first object/method pair matched (and only the first,
* must be called multiple times if object is registered multiple times).
* Does not shrink array afterwards, silently returns if method not found.
*/
// public void remove(Object object, Method method) {
// int index = findIndex(object, method);
public void remove(Object object) {
int index = findIndex(object);
if (index != -1) {
// shift remaining methods by one to preserve ordering
count--;
for (int i = index; i < count; i++) {
objects[i] = objects[i+1];
methods[i] = methods[i+1];
}
// clean things out for the gc's sake
objects[count] = null;
methods[count] = null;
}
}
// protected int findIndex(Object object, Method method) {
protected int findIndex(Object object) {
for (int i = 0; i < count; i++) {
if (objects[i] == object) {
// if (objects[i] == object && methods[i].equals(method)) {
//objects[i].equals() might be overridden, so use == for safety
// since here we do care about actual object identity
//methods[i]==method is never true even for same method, so must use
// equals(), this should be safe because of object identity
return i;
}
}
return -1;
}
}
/**
* Register a built-in event so that it can be fired for libraries, etc.
* Supported events include:
* <ul>
* <li>pre – at the very top of the draw() method (safe to draw)
* <li>draw – at the end of the draw() method (safe to draw)
* <li>post – after draw() has exited (not safe to draw)
* <li>pause – called when the sketch is paused
* <li>resume – called when the sketch is resumed
* <li>dispose – when the sketch is shutting down (definitely not safe to draw)
* <ul>
* In addition, the new (for 2.0) processing.event classes are passed to
* the following event types:
* <ul>
* <li>mouseEvent
* <li>keyEvent
* <li>touchEvent
* </ul>
* The older java.awt events are no longer supported.
* See the Library Wiki page for more details.
* @param methodName name of the method to be called
* @param target the target object that should receive the event
*/
public void registerMethod(String methodName, Object target) {
if (methodName.equals("mouseEvent")) {
registerWithArgs("mouseEvent", target, new Class[] { processing.event.MouseEvent.class });
} else if (methodName.equals("keyEvent")) {
registerWithArgs("keyEvent", target, new Class[] { processing.event.KeyEvent.class });
} else if (methodName.equals("touchEvent")) {
registerWithArgs("touchEvent", target, new Class[] { processing.event.TouchEvent.class });
} else {
registerNoArgs(methodName, target);
}
}
private void registerNoArgs(String name, Object o) {
RegisteredMethods meth = registerMap.get(name);
if (meth == null) {
meth = new RegisteredMethods();
registerMap.put(name, meth);
}
Class<?> c = o.getClass();
try {
Method method = c.getMethod(name, new Class[] {});
meth.add(o, method);
} catch (NoSuchMethodException nsme) {
die("There is no public " + name + "() method in the class " +
o.getClass().getName());
} catch (Exception e) {
die("Could not register " + name + " + () for " + o, e);
}
}
private void registerWithArgs(String name, Object o, Class<?> cargs[]) {
RegisteredMethods meth = registerMap.get(name);
if (meth == null) {
meth = new RegisteredMethods();
registerMap.put(name, meth);
}
Class<?> c = o.getClass();
try {
Method method = c.getMethod(name, cargs);
meth.add(o, method);
} catch (NoSuchMethodException nsme) {
die("There is no public " + name + "() method in the class " +
o.getClass().getName());
} catch (Exception e) {
die("Could not register " + name + " + () for " + o, e);
}
}
// public void registerMethod(String methodName, Object target, Object... args) {
// registerWithArgs(methodName, target, args);
// }
public void unregisterMethod(String name, Object target) {
RegisteredMethods meth = registerMap.get(name);
if (meth == null) {
die("No registered methods with the name " + name + "() were found.");
}
try {
// Method method = o.getClass().getMethod(name, new Class[] {});
// meth.remove(o, method);
meth.remove(target);
} catch (Exception e) {
die("Could not unregister " + name + "() for " + target, e);
}
}
protected void handleMethods(String methodName) {
RegisteredMethods meth = registerMap.get(methodName);
if (meth != null) {
meth.handle();
}
}
protected void handleMethods(String methodName, Object[] args) {
RegisteredMethods meth = registerMap.get(methodName);
if (meth != null) {
meth.handle(args);
}
}
@Deprecated
public void registerSize(Object o) {
System.err.println("The registerSize() command is no longer supported.");
// Class<?> methodArgs[] = new Class[] { Integer.TYPE, Integer.TYPE };
// registerWithArgs(sizeMethods, "size", o, methodArgs);
}
@Deprecated
public void registerPre(Object o) {
registerNoArgs("pre", o);
}
@Deprecated
public void registerDraw(Object o) {
registerNoArgs("draw", o);
}
@Deprecated
public void registerPost(Object o) {
registerNoArgs("post", o);
}
@Deprecated
public void registerDispose(Object o) {
registerNoArgs("dispose", o);
}
@Deprecated
public void unregisterSize(Object o) {
System.err.println("The unregisterSize() command is no longer supported.");
// Class<?> methodArgs[] = new Class[] { Integer.TYPE, Integer.TYPE };
// unregisterWithArgs(sizeMethods, "size", o, methodArgs);
}
@Deprecated
public void unregisterPre(Object o) {
unregisterMethod("pre", o);
}
@Deprecated
public void unregisterDraw(Object o) {
unregisterMethod("draw", o);
}
@Deprecated
public void unregisterPost(Object o) {
unregisterMethod("post", o);
}
@Deprecated
public void unregisterDispose(Object o) {
unregisterMethod("dispose", o);
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
// Old methods with AWT API that should not be used.
// These were never implemented on Android so they're stored separately.
RegisteredMethods mouseEventMethods, keyEventMethods;
protected void reportDeprecation(Class<?> c, boolean mouse) {
if (g != null) {
PGraphics.showWarning("The class " + c.getName() +
" is incompatible with Processing 2.0.");
PGraphics.showWarning("A library (or other code) is using register" +
(mouse ? "Mouse" : "Key") + "Event() " +
"which is no longer available.");
// This will crash with OpenGL, so quit anyway
if (g instanceof PGraphicsOpenGL) {
PGraphics.showWarning("Stopping the sketch because this code will " +
"not work correctly with OpenGL.");
throw new RuntimeException("This sketch uses a library that " +
"needs to be updated for Processing 2.0.");
}
}
}
@Deprecated
public void registerMouseEvent(Object o) {
Class<?> c = o.getClass();
reportDeprecation(c, true);
try {
Method method = c.getMethod("mouseEvent", new Class[] { java.awt.event.MouseEvent.class });
if (mouseEventMethods == null) {
mouseEventMethods = new RegisteredMethods();
}
mouseEventMethods.add(o, method);
} catch (Exception e) {
die("Could not register mouseEvent() for " + o, e);
}
}
@Deprecated
public void unregisterMouseEvent(Object o) {
try {
// Method method = o.getClass().getMethod("mouseEvent", new Class[] { MouseEvent.class });
// mouseEventMethods.remove(o, method);
mouseEventMethods.remove(o);
} catch (Exception e) {
die("Could not unregister mouseEvent() for " + o, e);
}
}
@Deprecated
public void registerKeyEvent(Object o) {
Class<?> c = o.getClass();
reportDeprecation(c, false);
try {
Method method = c.getMethod("keyEvent", new Class[] { java.awt.event.KeyEvent.class });
if (keyEventMethods == null) {
keyEventMethods = new RegisteredMethods();
}
keyEventMethods.add(o, method);
} catch (Exception e) {
die("Could not register keyEvent() for " + o, e);
}
}
@Deprecated
public void unregisterKeyEvent(Object o) {
try {
// Method method = o.getClass().getMethod("keyEvent", new Class[] { KeyEvent.class });
// keyEventMethods.remove(o, method);
keyEventMethods.remove(o);
} catch (Exception e) {
die("Could not unregister keyEvent() for " + o, e);
}
}
//////////////////////////////////////////////////////////////
/**
* ( begin auto-generated from setup.xml )
*
* The <b>setup()</b> function is called once when the program starts. It's
* used to define initial
* enviroment properties such as screen size and background color and to
* load media such as images
* and fonts as the program starts. There can only be one <b>setup()</b>
* function for each program and
* it shouldn't be called again after its initial execution. Note:
* Variables declared within
* <b>setup()</b> are not accessible within other functions, including
* <b>draw()</b>.
*
* ( end auto-generated )
* @webref structure
* @usage web_application
* @see PApplet#size(int, int)
* @see PApplet#loop()
* @see PApplet#noLoop()
* @see PApplet#draw()
*/
public void setup() {
}
/**
* ( begin auto-generated from draw.xml )
*
* Called directly after <b>setup()</b> and continuously executes the lines
* of code contained inside its block until the program is stopped or
* <b>noLoop()</b> is called. The <b>draw()</b> function is called
* automatically and should never be called explicitly. It should always be
* controlled with <b>noLoop()</b>, <b>redraw()</b> and <b>loop()</b>.
* After <b>noLoop()</b> stops the code in <b>draw()</b> from executing,
* <b>redraw()</b> causes the code inside <b>draw()</b> to execute once and
* <b>loop()</b> will causes the code inside <b>draw()</b> to execute
* continuously again. The number of times <b>draw()</b> executes in each
* second may be controlled with <b>frameRate()</b> function.
* There can only be one <b>draw()</b> function for each sketch
* and <b>draw()</b> must exist if you want the code to run continuously or
* to process events such as <b>mousePressed()</b>. Sometimes, you might
* have an empty call to <b>draw()</b> in your program as shown in the
* above example.
*
* ( end auto-generated )
* @webref structure
* @usage web_application
* @see PApplet#setup()
* @see PApplet#loop()
* @see PApplet#noLoop()
* @see PApplet#redraw()
* @see PApplet#frameRate(float)
*/
public void draw() {
// if no draw method, then shut things down
//System.out.println("no draw method, goodbye");
finished = true;
}
//////////////////////////////////////////////////////////////
protected void resizeRenderer(int newWidth, int newHeight) {
debug("resizeRenderer request for " + newWidth + " " + newHeight);
if (width != newWidth || height != newHeight) {
debug(" former size was " + width + " " + height);
g.setSize(newWidth, newHeight);
width = newWidth;
height = newHeight;
}
}
/**
* ( begin auto-generated from size.xml )
*
* Defines the dimension of the display window in units of pixels. The
* <b>size()</b> function must be the first line in <b>setup()</b>. If
* <b>size()</b> is not used, the default size of the window is 100x100
* pixels. The system variables <b>width</b> and <b>height</b> are set by
* the parameters passed to this function.<br />
* <br />
* Do not use variables as the parameters to <b>size()</b> function,
* because it will cause problems when exporting your sketch. When
* variables are used, the dimensions of your sketch cannot be determined
* during export. Instead, employ numeric values in the <b>size()</b>
* statement, and then use the built-in <b>width</b> and <b>height</b>
* variables inside your program when the dimensions of the display window
* are needed.<br />
* <br />
* The <b>size()</b> function can only be used once inside a sketch, and
* cannot be used for resizing.<br/>
* <br/> <b>renderer</b> parameter selects which rendering engine to use.
* For example, if you will be drawing 3D shapes, use <b>P3D</b>, if you
* want to export images from a program as a PDF file use <b>PDF</b>. A
* brief description of the three primary renderers follows:<br />
* <br />
* <b>P2D</b> (Processing 2D) - The default renderer that supports two
* dimensional drawing.<br />
* <br />
* <b>P3D</b> (Processing 3D) - 3D graphics renderer that makes use of
* OpenGL-compatible graphics hardware.<br />
* <br />
* <b>PDF</b> - The PDF renderer draws 2D graphics directly to an Acrobat
* PDF file. This produces excellent results when you need vector shapes
* for high resolution output or printing. You must first use Import
* Library → PDF to make use of the library. More information can be
* found in the PDF library reference.<br />
* <br />
* The P3D renderer doesn't support <b>strokeCap()</b> or
* <b>strokeJoin()</b>, which can lead to ugly results when using
* <b>strokeWeight()</b>. (<a
* href="http://code.google.com/p/processing/issues/detail?id=123">Issue
* 123</a>) <br />
* <br />
* The maximum width and height is limited by your operating system, and is
* usually the width and height of your actual screen. On some machines it
* may simply be the number of pixels on your current screen, meaning that
* a screen of 800x600 could support <b>size(1600, 300)</b>, since it's the
* same number of pixels. This varies widely so you'll have to try
* different rendering modes and sizes until you get what you're looking
* for. If you need something larger, use <b>createGraphics</b> to create a
* non-visible drawing surface.<br />
* <br />
* Again, the <b>size()</b> function must be the first line of the code (or
* first item inside setup). Any code that appears before the <b>size()</b>
* command may run more than once, which can lead to confusing results.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* If using Java 1.3 or later, this will default to using
* PGraphics2, the Java2D-based renderer. If using Java 1.1,
* or if PGraphics2 is not available, then PGraphics will be used.
* To set your own renderer, use the other version of the size()
* method that takes a renderer as its last parameter.
* <p>
* If called once a renderer has already been set, this will
* use the previous renderer and simply resize it.
*
* @webref environment
* @param w width of the display window in units of pixels
* @param h height of the display window in units of pixels
*/
public void size(int w, int h) {
size(w, h, JAVA2D, null);
}
/**
* @param renderer Either P2D, P3D, or PDF
*/
public void size(int w, int h, String renderer) {
size(w, h, renderer, null);
}
/**
* @nowebref
*/
public void size(final int w, final int h,
String renderer, String path) {
// Run this from the EDT, just cuz it's AWT stuff (or maybe later Swing)
EventQueue.invokeLater(new Runnable() {
public void run() {
// Set the preferred size so that the layout managers can handle it
setPreferredSize(new Dimension(w, h));
setSize(w, h);
}
});
// ensure that this is an absolute path
if (path != null) path = savePath(path);
String currentRenderer = g.getClass().getName();
if (currentRenderer.equals(renderer)) {
// Avoid infinite loop of throwing exception to reset renderer
resizeRenderer(w, h);
//redraw(); // will only be called insize draw()
} else { // renderer is being changed
// otherwise ok to fall through and create renderer below
// the renderer is changing, so need to create a new object
g = makeGraphics(w, h, renderer, path, true);
this.width = w;
this.height = h;
// fire resize event to make sure the applet is the proper size
// setSize(iwidth, iheight);
// this is the function that will run if the user does their own
// size() command inside setup, so set defaultSize to false.
defaultSize = false;
// throw an exception so that setup() is called again
// but with a properly sized render
// this is for opengl, which needs a valid, properly sized
// display before calling anything inside setup().
throw new RendererChangeException();
}
}
public PGraphics createGraphics(int w, int h) {
return createGraphics(w, h, JAVA2D);
}
/**
* ( begin auto-generated from createGraphics.xml )
*
* Creates and returns a new <b>PGraphics</b> object of the types P2D or
* P3D. Use this class if you need to draw into an off-screen graphics
* buffer. The PDF renderer requires the filename parameter. The DXF
* renderer should not be used with <b>createGraphics()</b>, it's only
* built for use with <b>beginRaw()</b> and <b>endRaw()</b>.<br />
* <br />
* It's important to call any drawing functions between <b>beginDraw()</b>
* and <b>endDraw()</b> statements. This is also true for any functions
* that affect drawing, such as <b>smooth()</b> or <b>colorMode()</b>.<br/>
* <br/> the main drawing surface which is completely opaque, surfaces
* created with <b>createGraphics()</b> can have transparency. This makes
* it possible to draw into a graphics and maintain the alpha channel. By
* using <b>save()</b> to write a PNG or TGA file, the transparency of the
* graphics object will be honored. Note that transparency levels are
* binary: pixels are either complete opaque or transparent. For the time
* being, this means that text characters will be opaque blocks. This will
* be fixed in a future release (<a
* href="http://code.google.com/p/processing/issues/detail?id=80">Issue 80</a>).
*
* ( end auto-generated )
* <h3>Advanced</h3>
* Create an offscreen PGraphics object for drawing. This can be used
* for bitmap or vector images drawing or rendering.
* <UL>
* <LI>Do not use "new PGraphicsXxxx()", use this method. This method
* ensures that internal variables are set up properly that tie the
* new graphics context back to its parent PApplet.
* <LI>The basic way to create bitmap images is to use the <A
* HREF="http://processing.org/reference/saveFrame_.html">saveFrame()</A>
* function.
* <LI>If you want to create a really large scene and write that,
* first make sure that you've allocated a lot of memory in the Preferences.
* <LI>If you want to create images that are larger than the screen,
* you should create your own PGraphics object, draw to that, and use
* <A HREF="http://processing.org/reference/save_.html">save()</A>.
* <PRE>
*
* PGraphics big;
*
* void setup() {
* big = createGraphics(3000, 3000);
*
* big.beginDraw();
* big.background(128);
* big.line(20, 1800, 1800, 900);
* // etc..
* big.endDraw();
*
* // make sure the file is written to the sketch folder
* big.save("big.tif");
* }
*
* </PRE>
* <LI>It's important to always wrap drawing to createGraphics() with
* beginDraw() and endDraw() (beginFrame() and endFrame() prior to
* revision 0115). The reason is that the renderer needs to know when
* drawing has stopped, so that it can update itself internally.
* This also handles calling the defaults() method, for people familiar
* with that.
* <LI>With Processing 0115 and later, it's possible to write images in
* formats other than the default .tga and .tiff. The exact formats and
* background information can be found in the developer's reference for
* <A HREF="http://dev.processing.org/reference/core/javadoc/processing/core/PImage.html#save(java.lang.String)">PImage.save()</A>.
* </UL>
*
* @webref rendering
* @param w width in pixels
* @param h height in pixels
* @param renderer Either P2D, P3D, or PDF
*
* @see PGraphics#PGraphics
*
*/
public PGraphics createGraphics(int w, int h, String renderer) {
PGraphics pg = makeGraphics(w, h, renderer, null, false);
//pg.parent = this; // make save() work
return pg;
}
/**
* Create an offscreen graphics surface for drawing, in this case
* for a renderer that writes to a file (such as PDF or DXF).
* @param path the name of the file (can be an absolute or relative path)
*/
public PGraphics createGraphics(int w, int h,
String renderer, String path) {
if (path != null) {
path = savePath(path);
}
PGraphics pg = makeGraphics(w, h, renderer, path, false);
pg.parent = this; // make save() work
return pg;
}
/**
* Version of createGraphics() used internally.
*/
protected PGraphics makeGraphics(int w, int h,
String renderer, String path,
boolean primary) {
String openglError = external ?
"Before using OpenGL, first select " +
"Import Library > OpenGL from the Sketch menu." :
"The Java classpath and native library path is not " + // welcome to Java programming!
"properly set for using the OpenGL library.";
if (!primary && !g.isGL()) {
if (renderer.equals(P2D)) {
throw new RuntimeException("createGraphics() with P2D requires size() to use P2D or P3D");
} else if (renderer.equals(P3D)) {
throw new RuntimeException("createGraphics() with P3D or OPENGL requires size() to use P2D or P3D");
}
}
try {
Class<?> rendererClass =
Thread.currentThread().getContextClassLoader().loadClass(renderer);
Constructor<?> constructor = rendererClass.getConstructor(new Class[] { });
PGraphics pg = (PGraphics) constructor.newInstance();
pg.setParent(this);
pg.setPrimary(primary);
if (path != null) pg.setPath(path);
// pg.setQuality(sketchQuality());
pg.setSize(w, h);
// everything worked, return it
return pg;
} catch (InvocationTargetException ite) {
String msg = ite.getTargetException().getMessage();
if ((msg != null) &&
(msg.indexOf("no jogl in java.library.path") != -1)) {
throw new RuntimeException(openglError +
" (The native library is missing.)");
} else {
ite.getTargetException().printStackTrace();
Throwable target = ite.getTargetException();
if (platform == MACOSX) target.printStackTrace(System.out); // bug
// neither of these help, or work
//target.printStackTrace(System.err);
//System.err.flush();
//System.out.println(System.err); // and the object isn't null
throw new RuntimeException(target.getMessage());
}
} catch (ClassNotFoundException cnfe) {
if (cnfe.getMessage().indexOf("processing.opengl.PGraphicsOpenGL") != -1) {
throw new RuntimeException(openglError +
" (The library .jar file is missing.)");
} else {
throw new RuntimeException("You need to use \"Import Library\" " +
"to add " + renderer + " to your sketch.");
}
} catch (Exception e) {
if ((e instanceof IllegalArgumentException) ||
(e instanceof NoSuchMethodException) ||
(e instanceof IllegalAccessException)) {
if (e.getMessage().contains("cannot be <= 0")) {
// IllegalArgumentException will be thrown if w/h is <= 0
// http://code.google.com/p/processing/issues/detail?id=983
throw new RuntimeException(e);
} else {
e.printStackTrace();
String msg = renderer + " needs to be updated " +
"for the current release of Processing.";
throw new RuntimeException(msg);
}
} else {
if (platform == MACOSX) e.printStackTrace(System.out);
throw new RuntimeException(e.getMessage());
}
}
}
/**
* ( begin auto-generated from createImage.xml )
*
* Creates a new PImage (the datatype for storing images). This provides a
* fresh buffer of pixels to play with. Set the size of the buffer with the
* <b>width</b> and <b>height</b> parameters. The <b>format</b> parameter
* defines how the pixels are stored. See the PImage reference for more information.
* <br/> <br/>
* Be sure to include all three parameters, specifying only the width and
* height (but no format) will produce a strange error.
* <br/> <br/>
* Advanced users please note that createImage() should be used instead of
* the syntax <tt>new PImage()</tt>.
*
* ( end auto-generated )
* <h3>Advanced</h3>
* Preferred method of creating new PImage objects, ensures that a
* reference to the parent PApplet is included, which makes save() work
* without needing an absolute path.
*
* @webref image
* @param w width in pixels
* @param h height in pixels
* @param format Either RGB, ARGB, ALPHA (grayscale alpha channel)
* @see PImage#PImage
* @see PGraphics#PGraphics
*/
public PImage createImage(int w, int h, int format) {
PImage image = new PImage(w, h, format);
image.parent = this; // make save() work
return image;
}
/*
public PImage createImage(int w, int h, int format) {
return createImage(w, h, format, null);
}
// unapproved
public PImage createImage(int w, int h, int format, Object params) {
PImage image = new PImage(w, h, format);
if (params != null) {
image.setParams(g, params);
}
image.parent = this; // make save() work
return image;
}
*/
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
@Override
public void update(Graphics screen) {
paint(screen);
}
@Override
public void paint(Graphics screen) {
// int r = (int) random(10000);
// System.out.println("into paint " + r);
//super.paint(screen);
// ignore the very first call to paint, since it's coming
// from the o.s., and the applet will soon update itself anyway.
if (frameCount == 0) {
// println("Skipping frame");
// paint() may be called more than once before things
// are finally painted to the screen and the thread gets going
return;
}
// without ignoring the first call, the first several frames
// are confused because paint() gets called in the midst of
// the initial nextFrame() call, so there are multiple
// updates fighting with one another.
// make sure the screen is visible and usable
// (also prevents over-drawing when using PGraphicsOpenGL)
/* the 1.5.x version
if (g != null) {
// added synchronization for 0194 because of flicker issues with JAVA2D
// http://code.google.com/p/processing/issues/detail?id=558
// g.image is synchronized so that draw/loop and paint don't
// try to fight over it. this was causing a randomized slowdown
// that would cut the frameRate into a third on macosx,
// and is probably related to the windows sluggishness bug too
if (g.image != null) {
System.out.println("ui paint");
synchronized (g.image) {
screen.drawImage(g.image, 0, 0, null);
}
}
}
*/
// if (insideDraw) {
// new Exception().printStackTrace(System.out);
// }
if (!insideDraw && (g != null) && (g.image != null)) {
if (useStrategy) {
render();
} else {
// System.out.println("drawing to screen");
//screen.drawImage(g.image, 0, 0, null); // not retina friendly
screen.drawImage(g.image, 0, 0, width, height, null);
}
//} else {
// System.out.println(insideDraw + " " + g + " " + ((g != null) ? g.image : "-"));
}
}
boolean useActive = true;
// boolean useStrategy = true;
boolean useStrategy = false;
Canvas canvas;
protected synchronized void render() {
if (canvas == null) {
removeListeners(this);
canvas = new Canvas();
add(canvas);
setIgnoreRepaint(true);
canvas.setIgnoreRepaint(true);
addListeners(canvas);
// add(canvas, BorderLayout.CENTER);
// doLayout();
}
canvas.setBounds(0, 0, width, height);
// System.out.println("render(), canvas bounds are " + canvas.getBounds());
if (canvas.getBufferStrategy() == null) { // whole block [121222]
// System.out.println("creating a strategy");
canvas.createBufferStrategy(2);
}
BufferStrategy strategy = canvas.getBufferStrategy();
if (strategy == null) {
return;
}
// Render single frame
do {
// The following loop ensures that the contents of the drawing buffer
// are consistent in case the underlying surface was recreated
do {
Graphics draw = strategy.getDrawGraphics();
draw.drawImage(g.image, 0, 0, width, height, null);
draw.dispose();
// Repeat the rendering if the drawing buffer contents
// were restored
// System.out.println("restored " + strategy.contentsRestored());
} while (strategy.contentsRestored());
// Display the buffer
// System.out.println("showing");
strategy.show();
// Repeat the rendering if the drawing buffer was lost
// System.out.println("lost " + strategy.contentsLost());
// System.out.println();
} while (strategy.contentsLost());
}
/*
// active paint method (also the 1.2.1 version)
protected void paint() {
try {
Graphics screen = this.getGraphics();
if (screen != null) {
if ((g != null) && (g.image != null)) {
screen.drawImage(g.image, 0, 0, null);
}
Toolkit.getDefaultToolkit().sync();
}
} catch (Exception e) {
// Seen on applet destroy, maybe can ignore?
e.printStackTrace();
// } finally {
// if (g != null) {
// g.dispose();
// }
}
}
protected void paint_1_5_1() {
try {
Graphics screen = getGraphics();
if (screen != null) {
if (g != null) {
// added synchronization for 0194 because of flicker issues with JAVA2D
// http://code.google.com/p/processing/issues/detail?id=558
if (g.image != null) {
System.out.println("active paint");
synchronized (g.image) {
screen.drawImage(g.image, 0, 0, null);
}
Toolkit.getDefaultToolkit().sync();
}
}
}
} catch (Exception e) {
// Seen on applet destroy, maybe can ignore?
e.printStackTrace();
}
}
*/
//////////////////////////////////////////////////////////////
/**
* Main method for the primary animation thread.
*
* <A HREF="http://java.sun.com/products/jfc/tsc/articles/painting/">Painting in AWT and Swing</A>
*/
public void run() { // not good to make this synchronized, locks things up
long beforeTime = System.nanoTime();
long overSleepTime = 0L;
int noDelays = 0;
// Number of frames with a delay of 0 ms before the
// animation thread yields to other running threads.
final int NO_DELAYS_PER_YIELD = 15;
/*
// this has to be called after the exception is thrown,
// otherwise the supporting libs won't have a valid context to draw to
Object methodArgs[] =
new Object[] { new Integer(width), new Integer(height) };
sizeMethods.handle(methodArgs);
*/
if (!online) {
start();
}
while ((Thread.currentThread() == thread) && !finished) {
if (paused) {
debug("PApplet.run() paused, calling object wait...");
synchronized (pauseObject) {
try {
pauseObject.wait();
debug("out of wait");
} catch (InterruptedException e) {
// waiting for this interrupt on a start() (resume) call
}
}
}
debug("done with pause");
// while (paused) {
// debug("paused...");
// try {
// Thread.sleep(100L);
// } catch (InterruptedException e) { } // ignored
// }
// Don't resize the renderer from the EDT (i.e. from a ComponentEvent),
// otherwise it may attempt a resize mid-render.
// if (resizeRequest) {
// resizeRenderer(resizeWidth, resizeHeight);
// resizeRequest = false;
// }
if (g != null) {
getSize(currentSize);
if (currentSize.width != g.width || currentSize.height != g.height) {
resizeRenderer(currentSize.width, currentSize.height);
}
}
// render a single frame
//handleDraw();
if (g != null) g.requestDraw();
if (frameCount == 1) {
// for 2.0a6, moving this request to the EDT
EventQueue.invokeLater(new Runnable() {
public void run() {
// Call the request focus event once the image is sure to be on
// screen and the component is valid. The OpenGL renderer will
// request focus for its canvas inside beginDraw().
// http://java.sun.com/j2se/1.4.2/docs/api/java/awt/doc-files/FocusSpec.html
// Disabling for 0185, because it causes an assertion failure on OS X
// http://code.google.com/p/processing/issues/detail?id=258
// requestFocus();
// Changing to this version for 0187
// http://code.google.com/p/processing/issues/detail?id=279
requestFocusInWindow();
}
});
}
// wait for update & paint to happen before drawing next frame
// this is necessary since the drawing is sometimes in a
// separate thread, meaning that the next frame will start
// before the update/paint is completed
long afterTime = System.nanoTime();
long timeDiff = afterTime - beforeTime;
//System.out.println("time diff is " + timeDiff);
long sleepTime = (frameRatePeriod - timeDiff) - overSleepTime;
if (sleepTime > 0) { // some time left in this cycle
try {
// Thread.sleep(sleepTime / 1000000L); // nanoseconds -> milliseconds
Thread.sleep(sleepTime / 1000000L, (int) (sleepTime % 1000000L));
noDelays = 0; // Got some sleep, not delaying anymore
} catch (InterruptedException ex) { }
overSleepTime = (System.nanoTime() - afterTime) - sleepTime;
//System.out.println(" oversleep is " + overSleepTime);
} else { // sleepTime <= 0; the frame took longer than the period
// excess -= sleepTime; // store excess time value
overSleepTime = 0L;
if (noDelays > NO_DELAYS_PER_YIELD) {
Thread.yield(); // give another thread a chance to run
noDelays = 0;
}
}
beforeTime = System.nanoTime();
}
dispose(); // call to shutdown libs?
// If the user called the exit() function, the window should close,
// rather than the sketch just halting.
if (exitCalled) {
exitActual();
}
}
protected boolean insideDraw;
//synchronized public void handleDisplay() {
public void handleDraw() {
debug("handleDraw() " + g + " " + looping + " " + redraw + " valid:" + this.isValid() + " visible:" + this.isVisible());
if (g != null && (looping || redraw)) {
if (!g.canDraw()) {
debug("g.canDraw() is false");
// Don't draw if the renderer is not yet ready.
// (e.g. OpenGL has to wait for a peer to be on screen)
return;
}
insideDraw = true;
g.beginDraw();
if (recorder != null) {
recorder.beginDraw();
}
long now = System.nanoTime();
if (frameCount == 0) {
GraphicsConfiguration gc = getGraphicsConfiguration();
if (gc == null) return;
GraphicsDevice displayDevice =
getGraphicsConfiguration().getDevice();
if (displayDevice == null) return;
Rectangle screenRect =
displayDevice.getDefaultConfiguration().getBounds();
// screenX = screenRect.x;
// screenY = screenRect.y;
displayWidth = screenRect.width;
displayHeight = screenRect.height;
try {
//println("Calling setup()");
setup();
//println("Done with setup()");
} catch (RendererChangeException e) {
// Give up, instead set the new renderer and re-attempt setup()
return;
}
this.defaultSize = false;
} else { // frameCount > 0, meaning an actual draw()
// update the current frameRate
double rate = 1000000.0 / ((now - frameRateLastNanos) / 1000000.0);
float instantaneousRate = (float) rate / 1000.0f;
frameRate = (frameRate * 0.9f) + (instantaneousRate * 0.1f);
if (frameCount != 0) {
handleMethods("pre");
}
// use dmouseX/Y as previous mouse pos, since this is the
// last position the mouse was in during the previous draw.
pmouseX = dmouseX;
pmouseY = dmouseY;
//println("Calling draw()");
draw();
//println("Done calling draw()");
// dmouseX/Y is updated only once per frame (unlike emouseX/Y)
dmouseX = mouseX;
dmouseY = mouseY;
// these are called *after* loop so that valid
// drawing commands can be run inside them. it can't
// be before, since a call to background() would wipe
// out anything that had been drawn so far.
dequeueEvents();
// dequeueMouseEvents();
// dequeueKeyEvents();
handleMethods("draw");
redraw = false; // unset 'redraw' flag in case it was set
// (only do this once draw() has run, not just setup())
}
g.endDraw();
if (recorder != null) {
recorder.endDraw();
}
insideDraw = false;
// 1.5.1 version
if (useActive) {
if (useStrategy) {
render();
} else {
Graphics screen = getGraphics();
screen.drawImage(g.image, 0, 0, width, height, null);
}
} else {
repaint();
}
// getToolkit().sync(); // force repaint now (proper method)
if (frameCount != 0) {
handleMethods("post");
}
frameRateLastNanos = now;
frameCount++;
}
}
//////////////////////////////////////////////////////////////
/**
* ( begin auto-generated from redraw.xml )
*
* Executes the code within <b>draw()</b> one time. This functions allows
* the program to update the display window only when necessary, for
* example when an event registered by <b>mousePressed()</b> or
* <b>keyPressed()</b> occurs.
* <br/><br/> structuring a program, it only makes sense to call redraw()
* within events such as <b>mousePressed()</b>. This is because
* <b>redraw()</b> does not run <b>draw()</b> immediately (it only sets a
* flag that indicates an update is needed).
* <br/><br/> <b>redraw()</b> within <b>draw()</b> has no effect because
* <b>draw()</b> is continuously called anyway.
*
* ( end auto-generated )
* @webref structure
* @usage web_application
* @see PApplet#draw()
* @see PApplet#loop()
* @see PApplet#noLoop()
* @see PApplet#frameRate(float)
*/
synchronized public void redraw() {
if (!looping) {
redraw = true;
// if (thread != null) {
// // wake from sleep (necessary otherwise it'll be
// // up to 10 seconds before update)
// if (CRUSTY_THREADS) {
// thread.interrupt();
// } else {
// synchronized (blocker) {
// blocker.notifyAll();
// }
// }
// }
}
}
/**
* ( begin auto-generated from loop.xml )
*
* Causes Processing to continuously execute the code within <b>draw()</b>.
* If <b>noLoop()</b> is called, the code in <b>draw()</b> stops executing.
*
* ( end auto-generated )
* @webref structure
* @usage web_application
* @see PApplet#noLoop()
* @see PApplet#redraw()
* @see PApplet#draw()
*/
synchronized public void loop() {
if (!looping) {
looping = true;
}
}
/**
* ( begin auto-generated from noLoop.xml )
*
* Stops Processing from continuously executing the code within
* <b>draw()</b>. If <b>loop()</b> is called, the code in <b>draw()</b>
* begin to run continuously again. If using <b>noLoop()</b> in
* <b>setup()</b>, it should be the last line inside the block.
* <br/> <br/>
* When <b>noLoop()</b> is used, it's not possible to manipulate or access
* the screen inside event handling functions such as <b>mousePressed()</b>
* or <b>keyPressed()</b>. Instead, use those functions to call
* <b>redraw()</b> or <b>loop()</b>, which will run <b>draw()</b>, which
* can update the screen properly. This means that when noLoop() has been
* called, no drawing can happen, and functions like saveFrame() or
* loadPixels() may not be used.
* <br/> <br/>
* Note that if the sketch is resized, <b>redraw()</b> will be called to
* update the sketch, even after <b>noLoop()</b> has been specified.
* Otherwise, the sketch would enter an odd state until <b>loop()</b> was called.
*
* ( end auto-generated )
* @webref structure
* @usage web_application
* @see PApplet#loop()
* @see PApplet#redraw()
* @see PApplet#draw()
*/
synchronized public void noLoop() {
if (looping) {
looping = false;
}
}
//////////////////////////////////////////////////////////////
// public void addListeners() {
// addMouseListener(this);
// addMouseMotionListener(this);
// addKeyListener(this);
// addFocusListener(this);
//
// addComponentListener(new ComponentAdapter() {
// public void componentResized(ComponentEvent e) {
// Component c = e.getComponent();
// //System.out.println("componentResized() " + c);
// Rectangle bounds = c.getBounds();
// resizeRequest = true;
// resizeWidth = bounds.width;
// resizeHeight = bounds.height;
//
// if (!looping) {
// redraw();
// }
// }
// });
// }
//
//
// public void removeListeners() {
// removeMouseListener(this);
// removeMouseMotionListener(this);
// removeKeyListener(this);
// removeFocusListener(this);
//
//// removeComponentListener(??);
//// addComponentListener(new ComponentAdapter() {
//// public void componentResized(ComponentEvent e) {
//// Component c = e.getComponent();
//// //System.out.println("componentResized() " + c);
//// Rectangle bounds = c.getBounds();
//// resizeRequest = true;
//// resizeWidth = bounds.width;
//// resizeHeight = bounds.height;
////
//// if (!looping) {
//// redraw();
//// }
//// }
//// });
// }
public void addListeners(Component comp) {
comp.addMouseListener(this);
comp.addMouseMotionListener(this);
comp.addKeyListener(this);
comp.addFocusListener(this);
// canvas.addComponentListener(new ComponentAdapter() {
// public void componentResized(ComponentEvent e) {
// Component c = e.getComponent();
// //System.out.println("componentResized() " + c);
// Rectangle bounds = c.getBounds();
// resizeRequest = true;
// resizeWidth = bounds.width;
// resizeHeight = bounds.height;
//
// if (!looping) {
// redraw();
// }
// }
// });
}
public void removeListeners(Component comp) {
comp.removeMouseListener(this);
comp.removeMouseMotionListener(this);
comp.removeKeyListener(this);
comp.removeFocusListener(this);
}
/**
* Call to remove, then add, listeners to a component.
* Avoids issues with double-adding.
*/
public void updateListeners(Component comp) {
removeListeners(comp);
addListeners(comp);
}
//////////////////////////////////////////////////////////////
// protected Event eventQueue[] = new Event[10];
// protected int eventCount;
class InternalEventQueue {
protected Event queue[] = new Event[10];
protected int offset;
protected int count;
synchronized void add(Event e) {
if (count == queue.length) {
queue = (Event[]) expand(queue);
}
queue[count++] = e;
}
synchronized Event remove() {
if (offset == count) {
throw new RuntimeException("Nothing left on the event queue.");
}
Event outgoing = queue[offset++];
if (offset == count) {
// All done, time to reset
offset = 0;
count = 0;
}
return outgoing;
}
synchronized boolean available() {
return count != 0;
}
}
InternalEventQueue eventQueue = new InternalEventQueue();
/**
* Add an event to the internal event queue, or process it immediately if
* the sketch is not currently looping.
*/
public void postEvent(processing.event.Event pe) {
// if (pe instanceof MouseEvent) {
//// switch (pe.getFlavor()) {
//// case Event.MOUSE:
// if (looping) {
// enqueueMouseEvent((MouseEvent) pe);
// } else {
// handleMouseEvent((MouseEvent) pe);
// enqueueEvent(pe);
// }
// } else if (pe instanceof KeyEvent) {
// if (looping) {
// enqueueKeyEvent((KeyEvent) pe);
// } else {
// handleKeyEvent((KeyEvent) pe);
// }
// }
// synchronized (eventQueue) {
// if (eventCount == eventQueue.length) {
// eventQueue = (Event[]) expand(eventQueue);
// }
// eventQueue[eventCount++] = pe;
// }
eventQueue.add(pe);
if (!looping) {
dequeueEvents();
}
}
// protected void enqueueEvent(Event e) {
// synchronized (eventQueue) {
// if (eventCount == eventQueue.length) {
// eventQueue = (Event[]) expand(eventQueue);
// }
// eventQueue[eventCount++] = e;
// }
// }
protected void dequeueEvents() {
// can't do this.. thread lock
// synchronized (eventQueue) {
// for (int i = 0; i < eventCount; i++) {
// Event e = eventQueue[i];
while (eventQueue.available()) {
Event e = eventQueue.remove();
switch (e.getFlavor()) {
case Event.MOUSE:
handleMouseEvent((MouseEvent) e);
break;
case Event.KEY:
handleKeyEvent((KeyEvent) e);
break;
}
// }
// eventCount = 0;
}
}
//////////////////////////////////////////////////////////////
// MouseEvent mouseEventQueue[] = new MouseEvent[10];
// int mouseEventCount;
//
// protected void enqueueMouseEvent(MouseEvent e) {
// synchronized (mouseEventQueue) {
// if (mouseEventCount == mouseEventQueue.length) {
// MouseEvent temp[] = new MouseEvent[mouseEventCount << 1];
// System.arraycopy(mouseEventQueue, 0, temp, 0, mouseEventCount);
// mouseEventQueue = temp;
// }
// mouseEventQueue[mouseEventCount++] = e;
// }
// }
//
// protected void dequeueMouseEvents() {
// synchronized (mouseEventQueue) {
// for (int i = 0; i < mouseEventCount; i++) {
// handleMouseEvent(mouseEventQueue[i]);
// }
// mouseEventCount = 0;
// }
// }
/**
* Actually take action based on a mouse event.
* Internally updates mouseX, mouseY, mousePressed, and mouseEvent.
* Then it calls the event type with no params,
* i.e. mousePressed() or mouseReleased() that the user may have
* overloaded to do something more useful.
*/
protected void handleMouseEvent(MouseEvent event) {
// http://dev.processing.org/bugs/show_bug.cgi?id=170
// also prevents mouseExited() on the mac from hosing the mouse
// position, because x/y are bizarre values on the exit event.
// see also the id check below.. both of these go together.
// Not necessary to set mouseX/Y on PRESS or RELEASE events because the
// actual position will have been set by a MOVE or DRAG event.
if (event.getAction() == MouseEvent.DRAG ||
event.getAction() == MouseEvent.MOVE) {
pmouseX = emouseX;
pmouseY = emouseY;
mouseX = event.getX();
mouseY = event.getY();
}
// Get the (already processed) button code
mouseButton = event.getButton();
// Compatibility for older code (these have AWT object params, not P5)
if (mouseEventMethods != null) {
// Probably also good to check this, in case anyone tries to call
// postEvent() with an artificial event they've created.
if (event.getNative() != null) {
mouseEventMethods.handle(new Object[] { event.getNative() });
}
}
// this used to only be called on mouseMoved and mouseDragged
// change it back if people run into trouble
if (firstMouse) {
pmouseX = mouseX;
pmouseY = mouseY;
dmouseX = mouseX;
dmouseY = mouseY;
firstMouse = false;
}
mouseEvent = event;
// Do this up here in case a registered method relies on the
// boolean for mousePressed.
switch (event.getAction()) {
case MouseEvent.PRESS:
mousePressed = true;
break;
case MouseEvent.RELEASE:
mousePressed = false;
break;
}
handleMethods("mouseEvent", new Object[] { event });
switch (event.getAction()) {
case MouseEvent.PRESS:
// mousePressed = true;
mousePressed(event);
break;
case MouseEvent.RELEASE:
// mousePressed = false;
mouseReleased(event);
break;
case MouseEvent.CLICK:
mouseClicked(event);
break;
case MouseEvent.DRAG:
mouseDragged(event);
break;
case MouseEvent.MOVE:
mouseMoved(event);
break;
case MouseEvent.ENTER:
mouseEntered(event);
break;
case MouseEvent.EXIT:
mouseExited(event);
break;
}
if ((event.getAction() == MouseEvent.DRAG) ||
(event.getAction() == MouseEvent.MOVE)) {
emouseX = mouseX;
emouseY = mouseY;
}
}
/**
* Figure out how to process a mouse event. When loop() has been
* called, the events will be queued up until drawing is complete.
* If noLoop() has been called, then events will happen immediately.
*/
protected void nativeMouseEvent(java.awt.event.MouseEvent nativeEvent) {
int peAction = 0;
switch (nativeEvent.getID()) {
case java.awt.event.MouseEvent.MOUSE_PRESSED:
peAction = MouseEvent.PRESS;
break;
case java.awt.event.MouseEvent.MOUSE_RELEASED:
peAction = MouseEvent.RELEASE;
break;
case java.awt.event.MouseEvent.MOUSE_CLICKED:
peAction = MouseEvent.CLICK;
break;
case java.awt.event.MouseEvent.MOUSE_DRAGGED:
peAction = MouseEvent.DRAG;
break;
case java.awt.event.MouseEvent.MOUSE_MOVED:
peAction = MouseEvent.MOVE;
break;
case java.awt.event.MouseEvent.MOUSE_ENTERED:
peAction = MouseEvent.ENTER;
break;
case java.awt.event.MouseEvent.MOUSE_EXITED:
peAction = MouseEvent.EXIT;
break;
}
//System.out.println(nativeEvent);
//int modifiers = nativeEvent.getModifiersEx();
// If using getModifiersEx(), the regular modifiers don't set properly.
int modifiers = nativeEvent.getModifiers();
int peModifiers = modifiers &
(InputEvent.SHIFT_MASK |
InputEvent.CTRL_MASK |
InputEvent.META_MASK |
InputEvent.ALT_MASK);
// Windows and OS X seem to disagree on how to handle this. Windows only
// sets BUTTON1_DOWN_MASK, while OS X seems to set BUTTON1_MASK.
// This is an issue in particular with mouse release events:
// http://code.google.com/p/processing/issues/detail?id=1294
// The fix for which led to a regression (fixed here by checking both):
// http://code.google.com/p/processing/issues/detail?id=1332
int peButton = 0;
// if ((modifiers & InputEvent.BUTTON1_MASK) != 0 ||
// (modifiers & InputEvent.BUTTON1_DOWN_MASK) != 0) {
// peButton = LEFT;
// } else if ((modifiers & InputEvent.BUTTON2_MASK) != 0 ||
// (modifiers & InputEvent.BUTTON2_DOWN_MASK) != 0) {
// peButton = CENTER;
// } else if ((modifiers & InputEvent.BUTTON3_MASK) != 0 ||
// (modifiers & InputEvent.BUTTON3_DOWN_MASK) != 0) {
// peButton = RIGHT;
// }
if ((modifiers & InputEvent.BUTTON1_MASK) != 0) {
peButton = LEFT;
} else if ((modifiers & InputEvent.BUTTON2_MASK) != 0) {
peButton = CENTER;
} else if ((modifiers & InputEvent.BUTTON3_MASK) != 0) {
peButton = RIGHT;
}
// If running on macos, allow ctrl-click as right mouse. Prior to 0215,
// this used isPopupTrigger() on the native event, but that doesn't work
// for mouseClicked and mouseReleased (or others).
if (platform == MACOSX) {
//if (nativeEvent.isPopupTrigger()) {
if ((modifiers & InputEvent.CTRL_MASK) != 0) {
peButton = RIGHT;
}
}
postEvent(new MouseEvent(nativeEvent, nativeEvent.getWhen(),
peAction, peModifiers,
nativeEvent.getX(), nativeEvent.getY(),
peButton,
nativeEvent.getClickCount()));
}
/**
* If you override this or any function that takes a "MouseEvent e"
* without calling its super.mouseXxxx() then mouseX, mouseY,
* mousePressed, and mouseEvent will no longer be set.
*
* @nowebref
*/
public void mousePressed(java.awt.event.MouseEvent e) {
nativeMouseEvent(e);
}
/**
* @nowebref
*/
public void mouseReleased(java.awt.event.MouseEvent e) {
nativeMouseEvent(e);
}
/**
* @nowebref
*/
public void mouseClicked(java.awt.event.MouseEvent e) {
nativeMouseEvent(e);
}
/**
* @nowebref
*/
public void mouseEntered(java.awt.event.MouseEvent e) {
nativeMouseEvent(e);
}
/**
* @nowebref
*/
public void mouseExited(java.awt.event.MouseEvent e) {
nativeMouseEvent(e);
}
/**
* @nowebref
*/
public void mouseDragged(java.awt.event.MouseEvent e) {
nativeMouseEvent(e);
}
/**
* @nowebref
*/
public void mouseMoved(java.awt.event.MouseEvent e) {
nativeMouseEvent(e);
}
/**
* ( begin auto-generated from mousePressed.xml )
*
* The <b>mousePressed()</b> function is called once after every time a
* mouse button is pressed. The <b>mouseButton</b> variable (see the
* related reference entry) can be used to determine which button has been pressed.
*
* ( end auto-generated )
* <h3>Advanced</h3>
*
* If you must, use
* int button = mouseEvent.getButton();
* to figure out which button was clicked. It will be one of:
* MouseEvent.BUTTON1, MouseEvent.BUTTON2, MouseEvent.BUTTON3
* Note, however, that this is completely inconsistent across
* platforms.
* @webref input:mouse
* @see PApplet#mouseX
* @see PApplet#mouseY
* @see PApplet#mousePressed
* @see PApplet#mouseButton
* @see PApplet#mouseReleased()
* @see PApplet#mouseMoved()
* @see PApplet#mouseDragged()
*/
public void mousePressed() { }
public void mousePressed(MouseEvent event) {
mousePressed();
}
/**
* ( begin auto-generated from mouseReleased.xml )
*
* The <b>mouseReleased()</b> function is called every time a mouse button
* is released.
*
* ( end auto-generated )
* @webref input:mouse
* @see PApplet#mouseX
* @see PApplet#mouseY
* @see PApplet#mousePressed
* @see PApplet#mouseButton
* @see PApplet#mousePressed()
* @see PApplet#mouseMoved()
* @see PApplet#mouseDragged()
*/
public void mouseReleased() { }
public void mouseReleased(MouseEvent event) {
mouseReleased();
}
/**
* ( begin auto-generated from mouseClicked.xml )
*
* The <b>mouseClicked()</b> function is called once after a mouse button
* has been pressed and then released.
*
* ( end auto-generated )
* <h3>Advanced</h3>
* When the mouse is clicked, mousePressed() will be called,
* then mouseReleased(), then mouseClicked(). Note that
* mousePressed is already false inside of mouseClicked().
* @webref input:mouse
* @see PApplet#mouseX
* @see PApplet#mouseY
* @see PApplet#mouseButton
* @see PApplet#mousePressed()
* @see PApplet#mouseReleased()
* @see PApplet#mouseMoved()
* @see PApplet#mouseDragged()
*/
public void mouseClicked() { }
public void mouseClicked(MouseEvent event) {
mouseClicked();
}
/**
* ( begin auto-generated from mouseDragged.xml )
*
* The <b>mouseDragged()</b> function is called once every time the mouse
* moves and a mouse button is pressed.
*
* ( end auto-generated )
* @webref input:mouse
* @see PApplet#mouseX
* @see PApplet#mouseY
* @see PApplet#mousePressed
* @see PApplet#mousePressed()
* @see PApplet#mouseReleased()
* @see PApplet#mouseMoved()
*/
public void mouseDragged() { }
public void mouseDragged(MouseEvent event) {
mouseDragged();
}
/**
* ( begin auto-generated from mouseMoved.xml )
*
* The <b>mouseMoved()</b> function is called every time the mouse moves
* and a mouse button is not pressed.
*
* ( end auto-generated )
* @webref input:mouse
* @see PApplet#mouseX
* @see PApplet#mouseY
* @see PApplet#mousePressed
* @see PApplet#mousePressed()
* @see PApplet#mouseReleased()
* @see PApplet#mouseDragged()
*/
public void mouseMoved() { }
public void mouseMoved(MouseEvent event) {
mouseMoved();
}
public void mouseEntered() { }
public void mouseEntered(MouseEvent event) {
mouseEntered();
}
public void mouseExited() { }
public void mouseExited(MouseEvent event) {
mouseExited();
}
//////////////////////////////////////////////////////////////
// KeyEvent keyEventQueue[] = new KeyEvent[10];
// int keyEventCount;
//
// protected void enqueueKeyEvent(KeyEvent e) {
// synchronized (keyEventQueue) {
// if (keyEventCount == keyEventQueue.length) {
// KeyEvent temp[] = new KeyEvent[keyEventCount << 1];
// System.arraycopy(keyEventQueue, 0, temp, 0, keyEventCount);
// keyEventQueue = temp;
// }
// keyEventQueue[keyEventCount++] = e;
// }
// }
//
// protected void dequeueKeyEvents() {
// synchronized (keyEventQueue) {
// for (int i = 0; i < keyEventCount; i++) {
// keyEvent = keyEventQueue[i];
// handleKeyEvent(keyEvent);
// }
// keyEventCount = 0;
// }
// }
// protected void handleKeyEvent(java.awt.event.KeyEvent event) {
// keyEvent = event;
// key = event.getKeyChar();
// keyCode = event.getKeyCode();
//
// if (keyEventMethods != null) {
// keyEventMethods.handle(new Object[] { event });
// }
//
// switch (event.getID()) {
// case KeyEvent.KEY_PRESSED:
// keyPressed = true;
// keyPressed();
// break;
// case KeyEvent.KEY_RELEASED:
// keyPressed = false;
// keyReleased();
// break;
// case KeyEvent.KEY_TYPED:
// keyTyped();
// break;
// }
//
// // if someone else wants to intercept the key, they should
// // set key to zero (or something besides the ESC).
// if (event.getID() == java.awt.event.KeyEvent.KEY_PRESSED) {
// if (key == java.awt.event.KeyEvent.VK_ESCAPE) {
// exit();
// }
// // When running tethered to the Processing application, respond to
// // Ctrl-W (or Cmd-W) events by closing the sketch. Disable this behavior
// // when running independently, because this sketch may be one component
// // embedded inside an application that has its own close behavior.
// if (external &&
// event.getModifiers() == MENU_SHORTCUT &&
// event.getKeyCode() == 'W') {
// exit();
// }
// }
// }
protected void handleKeyEvent(KeyEvent event) {
keyEvent = event;
key = event.getKey();
keyCode = event.getKeyCode();
switch (event.getAction()) {
case KeyEvent.PRESS:
keyPressed = true;
keyPressed(keyEvent);
break;
case KeyEvent.RELEASE:
keyPressed = false;
keyReleased(keyEvent);
break;
case KeyEvent.TYPE:
keyTyped(keyEvent);
break;
}
if (keyEventMethods != null) {
keyEventMethods.handle(new Object[] { event.getNative() });
}
handleMethods("keyEvent", new Object[] { event });
// if someone else wants to intercept the key, they should
// set key to zero (or something besides the ESC).
if (event.getAction() == KeyEvent.PRESS) {
//if (key == java.awt.event.KeyEvent.VK_ESCAPE) {
if (key == ESC) {
exit();
}
// When running tethered to the Processing application, respond to
// Ctrl-W (or Cmd-W) events by closing the sketch. Not enabled when
// running independently, because this sketch may be one component
// embedded inside an application that has its own close behavior.
if (external &&
event.getKeyCode() == 'W' &&
((event.isMetaDown() && platform == MACOSX) ||
(event.isControlDown() && platform != MACOSX))) {
// Can't use this native stuff b/c the native event might be NEWT
// if (external && event.getNative() instanceof java.awt.event.KeyEvent &&
// ((java.awt.event.KeyEvent) event.getNative()).getModifiers() ==
// Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() &&
// event.getKeyCode() == 'W') {
exit();
}
}
}
protected void nativeKeyEvent(java.awt.event.KeyEvent event) {
int peAction = 0;
switch (event.getID()) {
case java.awt.event.KeyEvent.KEY_PRESSED:
peAction = KeyEvent.PRESS;
break;
case java.awt.event.KeyEvent.KEY_RELEASED:
peAction = KeyEvent.RELEASE;
break;
case java.awt.event.KeyEvent.KEY_TYPED:
peAction = KeyEvent.TYPE;
break;
}
// int peModifiers = event.getModifiersEx() &
// (InputEvent.SHIFT_DOWN_MASK |
// InputEvent.CTRL_DOWN_MASK |
// InputEvent.META_DOWN_MASK |
// InputEvent.ALT_DOWN_MASK);
int peModifiers = event.getModifiers() &
(InputEvent.SHIFT_MASK |
InputEvent.CTRL_MASK |
InputEvent.META_MASK |
InputEvent.ALT_MASK);
postEvent(new KeyEvent(event, event.getWhen(), peAction, peModifiers,
event.getKeyChar(), event.getKeyCode()));
}
/**
* Overriding keyXxxxx(KeyEvent e) functions will cause the 'key',
* 'keyCode', and 'keyEvent' variables to no longer work;
* key events will no longer be queued until the end of draw();
* and the keyPressed(), keyReleased() and keyTyped() methods
* will no longer be called.
*
* @nowebref
*/
public void keyPressed(java.awt.event.KeyEvent e) {
nativeKeyEvent(e);
}
/**
* @nowebref
*/
public void keyReleased(java.awt.event.KeyEvent e) {
nativeKeyEvent(e);
}
/**
* @nowebref
*/
public void keyTyped(java.awt.event.KeyEvent e) {
nativeKeyEvent(e);
}
/**
*
* ( begin auto-generated from keyPressed.xml )
*
* The <b>keyPressed()</b> function is called once every time a key is
* pressed. The key that was pressed is stored in the <b>key</b> variable.
* <br/> <br/>
* For non-ASCII keys, use the <b>keyCode</b> variable. The keys included
* in the ASCII specification (BACKSPACE, TAB, ENTER, RETURN, ESC, and
* DELETE) do not require checking to see if they key is coded, and you
* should simply use the <b>key</b> variable instead of <b>keyCode</b> If
* you're making cross-platform projects, note that the ENTER key is
* commonly used on PCs and Unix and the RETURN key is used instead on
* Macintosh. Check for both ENTER and RETURN to make sure your program
* will work for all platforms.
* <br/> <br/>
* Because of how operating systems handle key repeats, holding down a key
* may cause multiple calls to keyPressed() (and keyReleased() as well).
* The rate of repeat is set by the operating system and how each computer
* is configured.
*
* ( end auto-generated )
* <h3>Advanced</h3>
*
* Called each time a single key on the keyboard is pressed.
* Because of how operating systems handle key repeats, holding
* down a key will cause multiple calls to keyPressed(), because
* the OS repeat takes over.
* <p>
* Examples for key handling:
* (Tested on Windows XP, please notify if different on other
* platforms, I have a feeling Mac OS and Linux may do otherwise)
* <PRE>
* 1. Pressing 'a' on the keyboard:
* keyPressed with key == 'a' and keyCode == 'A'
* keyTyped with key == 'a' and keyCode == 0
* keyReleased with key == 'a' and keyCode == 'A'
*
* 2. Pressing 'A' on the keyboard:
* keyPressed with key == 'A' and keyCode == 'A'
* keyTyped with key == 'A' and keyCode == 0
* keyReleased with key == 'A' and keyCode == 'A'
*
* 3. Pressing 'shift', then 'a' on the keyboard (caps lock is off):
* keyPressed with key == CODED and keyCode == SHIFT
* keyPressed with key == 'A' and keyCode == 'A'
* keyTyped with key == 'A' and keyCode == 0
* keyReleased with key == 'A' and keyCode == 'A'
* keyReleased with key == CODED and keyCode == SHIFT
*
* 4. Holding down the 'a' key.
* The following will happen several times,
* depending on your machine's "key repeat rate" settings:
* keyPressed with key == 'a' and keyCode == 'A'
* keyTyped with key == 'a' and keyCode == 0
* When you finally let go, you'll get:
* keyReleased with key == 'a' and keyCode == 'A'
*
* 5. Pressing and releasing the 'shift' key
* keyPressed with key == CODED and keyCode == SHIFT
* keyReleased with key == CODED and keyCode == SHIFT
* (note there is no keyTyped)
*
* 6. Pressing the tab key in an applet with Java 1.4 will
* normally do nothing, but PApplet dynamically shuts
* this behavior off if Java 1.4 is in use (tested 1.4.2_05 Windows).
* Java 1.1 (Microsoft VM) passes the TAB key through normally.
* Not tested on other platforms or for 1.3.
* </PRE>
* @webref input:keyboard
* @see PApplet#key
* @see PApplet#keyCode
* @see PApplet#keyPressed
* @see PApplet#keyReleased()
*/
public void keyPressed() { }
public void keyPressed(KeyEvent event) {
keyPressed();
}
/**
* ( begin auto-generated from keyReleased.xml )
*
* The <b>keyReleased()</b> function is called once every time a key is
* released. The key that was released will be stored in the <b>key</b>
* variable. See <b>key</b> and <b>keyReleased</b> for more information.
*
* ( end auto-generated )
* @webref input:keyboard
* @see PApplet#key
* @see PApplet#keyCode
* @see PApplet#keyPressed
* @see PApplet#keyPressed()
*/
public void keyReleased() { }
public void keyReleased(KeyEvent event) {
keyReleased();
}
/**
* ( begin auto-generated from keyTyped.xml )
*
* The <b>keyTyped()</b> function is called once every time a key is
* pressed, but action keys such as Ctrl, Shift, and Alt are ignored.
* Because of how operating systems handle key repeats, holding down a key
* will cause multiple calls to <b>keyTyped()</b>, the rate is set by the
* operating system and how each computer is configured.
*
* ( end auto-generated )
* @webref input:keyboard
* @see PApplet#keyPressed
* @see PApplet#key
* @see PApplet#keyCode
* @see PApplet#keyReleased()
*/
public void keyTyped() { }
public void keyTyped(KeyEvent event) {
keyTyped();
}
//////////////////////////////////////////////////////////////
// i am focused man, and i'm not afraid of death.
// and i'm going all out. i circle the vultures in a van
// and i run the block.
public void focusGained() { }
public void focusGained(FocusEvent e) {
focused = true;
focusGained();
}
public void focusLost() { }
public void focusLost(FocusEvent e) {
focused = false;
focusLost();
}
//////////////////////////////////////////////////////////////
// getting the time
/**
* ( begin auto-generated from millis.xml )
*
* Returns the number of milliseconds (thousandths of a second) since
* starting an applet. This information is often used for timing animation
* sequences.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* <p>
* This is a function, rather than a variable, because it may
* change multiple times per frame.
*
* @webref input:time_date
* @see PApplet#second()
* @see PApplet#minute()
* @see PApplet#hour()
* @see PApplet#day()
* @see PApplet#month()
* @see PApplet#year()
*
*/
public int millis() {
return (int) (System.currentTimeMillis() - millisOffset);
}
/**
* ( begin auto-generated from second.xml )
*
* Processing communicates with the clock on your computer. The
* <b>second()</b> function returns the current second as a value from 0 - 59.
*
* ( end auto-generated )
* @webref input:time_date
* @see PApplet#millis()
* @see PApplet#minute()
* @see PApplet#hour()
* @see PApplet#day()
* @see PApplet#month()
* @see PApplet#year()
* */
static public int second() {
return Calendar.getInstance().get(Calendar.SECOND);
}
/**
* ( begin auto-generated from minute.xml )
*
* Processing communicates with the clock on your computer. The
* <b>minute()</b> function returns the current minute as a value from 0 - 59.
*
* ( end auto-generated )
*
* @webref input:time_date
* @see PApplet#millis()
* @see PApplet#second()
* @see PApplet#hour()
* @see PApplet#day()
* @see PApplet#month()
* @see PApplet#year()
*
* */
static public int minute() {
return Calendar.getInstance().get(Calendar.MINUTE);
}
/**
* ( begin auto-generated from hour.xml )
*
* Processing communicates with the clock on your computer. The
* <b>hour()</b> function returns the current hour as a value from 0 - 23.
*
* ( end auto-generated )
* @webref input:time_date
* @see PApplet#millis()
* @see PApplet#second()
* @see PApplet#minute()
* @see PApplet#day()
* @see PApplet#month()
* @see PApplet#year()
*
*/
static public int hour() {
return Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
}
/**
* ( begin auto-generated from day.xml )
*
* Processing communicates with the clock on your computer. The
* <b>day()</b> function returns the current day as a value from 1 - 31.
*
* ( end auto-generated )
* <h3>Advanced</h3>
* Get the current day of the month (1 through 31).
* <p>
* If you're looking for the day of the week (M-F or whatever)
* or day of the year (1..365) then use java's Calendar.get()
*
* @webref input:time_date
* @see PApplet#millis()
* @see PApplet#second()
* @see PApplet#minute()
* @see PApplet#hour()
* @see PApplet#month()
* @see PApplet#year()
*/
static public int day() {
return Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
}
/**
* ( begin auto-generated from month.xml )
*
* Processing communicates with the clock on your computer. The
* <b>month()</b> function returns the current month as a value from 1 - 12.
*
* ( end auto-generated )
*
* @webref input:time_date
* @see PApplet#millis()
* @see PApplet#second()
* @see PApplet#minute()
* @see PApplet#hour()
* @see PApplet#day()
* @see PApplet#year()
*/
static public int month() {
// months are number 0..11 so change to colloquial 1..12
return Calendar.getInstance().get(Calendar.MONTH) + 1;
}
/**
* ( begin auto-generated from year.xml )
*
* Processing communicates with the clock on your computer. The
* <b>year()</b> function returns the current year as an integer (2003,
* 2004, 2005, etc).
*
* ( end auto-generated )
* The <b>year()</b> function returns the current year as an integer (2003, 2004, 2005, etc).
*
* @webref input:time_date
* @see PApplet#millis()
* @see PApplet#second()
* @see PApplet#minute()
* @see PApplet#hour()
* @see PApplet#day()
* @see PApplet#month()
*/
static public int year() {
return Calendar.getInstance().get(Calendar.YEAR);
}
//////////////////////////////////////////////////////////////
// controlling time (playing god)
/**
* The delay() function causes the program to halt for a specified time.
* Delay times are specified in thousandths of a second. For example,
* running delay(3000) will stop the program for three seconds and
* delay(500) will stop the program for a half-second.
*
* The screen only updates when the end of draw() is reached, so delay()
* cannot be used to slow down drawing. For instance, you cannot use delay()
* to control the timing of an animation.
*
* The delay() function should only be used for pausing scripts (i.e.
* a script that needs to pause a few seconds before attempting a download,
* or a sketch that needs to wait a few milliseconds before reading from
* the serial port).
*/
public void delay(int napTime) {
//if (frameCount != 0) {
//if (napTime > 0) {
try {
Thread.sleep(napTime);
} catch (InterruptedException e) { }
//}
//}
}
/**
* ( begin auto-generated from frameRate.xml )
*
* Specifies the number of frames to be displayed every second. If the
* processor is not fast enough to maintain the specified rate, it will not
* be achieved. For example, the function call <b>frameRate(30)</b> will
* attempt to refresh 30 times a second. It is recommended to set the frame
* rate within <b>setup()</b>. The default rate is 60 frames per second.
*
* ( end auto-generated )
* @webref environment
* @param fps number of desired frames per second
* @see PApplet#setup()
* @see PApplet#draw()
* @see PApplet#loop()
* @see PApplet#noLoop()
* @see PApplet#redraw()
*/
public void frameRate(float fps) {
frameRateTarget = fps;
frameRatePeriod = (long) (1000000000.0 / frameRateTarget);
g.setFrameRate(fps);
}
//////////////////////////////////////////////////////////////
/**
* Reads the value of a param. Values are always read as a String so if you
* want them to be an integer or other datatype they must be converted. The
* <b>param()</b> function will only work in a web browser. The function
* should be called inside <b>setup()</b>, otherwise the applet may not yet
* be initialized and connected to its parent web browser.
*
* @param name name of the param to read
* @deprecated no more applet support
*/
public String param(String name) {
if (online) {
return getParameter(name);
} else {
System.err.println("param() only works inside a web browser");
}
return null;
}
/**
* <h3>Advanced</h3>
* Show status in the status bar of a web browser, or in the
* System.out console. Eventually this might show status in the
* p5 environment itself, rather than relying on the console.
*
* @deprecated no more applet support
*/
public void status(String value) {
if (online) {
showStatus(value);
} else {
System.out.println(value); // something more interesting?
}
}
public void link(String url) {
// link(url, null);
try {
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().browse(new URI(url));
} else {
// Just pass it off to open() and hope for the best
open(url);
}
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
/**
* Links to a webpage either in the same window or in a new window. The
* complete URL must be specified.
*
* <h3>Advanced</h3>
* Link to an external page without all the muss.
* <p>
* When run with an applet, uses the browser to open the url,
* for applications, attempts to launch a browser with the url.
* <p>
* Works on Mac OS X and Windows. For Linux, use:
* <PRE>open(new String[] { "firefox", url });</PRE>
* or whatever you want as your browser, since Linux doesn't
* yet have a standard method for launching URLs.
*
* @param url the complete URL, as a String in quotes
* @param target the name of the window in which to load the URL, as a String in quotes
* @deprecated the 'target' parameter is no longer relevant with the removal of applets
*/
public void link(String url, String target) {
link(url);
/*
try {
if (platform == WINDOWS) {
// the following uses a shell execute to launch the .html file
// note that under cygwin, the .html files have to be chmodded +x
// after they're unpacked from the zip file. i don't know why,
// and don't understand what this does in terms of windows
// permissions. without the chmod, the command prompt says
// "Access is denied" in both cygwin and the "dos" prompt.
//Runtime.getRuntime().exec("cmd /c " + currentDir + "\\reference\\" +
// referenceFile + ".html");
// replace ampersands with control sequence for DOS.
// solution contributed by toxi on the bugs board.
url = url.replaceAll("&","^&");
// open dos prompt, give it 'start' command, which will
// open the url properly. start by itself won't work since
// it appears to need cmd
Runtime.getRuntime().exec("cmd /c start " + url);
} else if (platform == MACOSX) {
//com.apple.mrj.MRJFileUtils.openURL(url);
try {
// Class<?> mrjFileUtils = Class.forName("com.apple.mrj.MRJFileUtils");
// Method openMethod =
// mrjFileUtils.getMethod("openURL", new Class[] { String.class });
Class<?> eieio = Class.forName("com.apple.eio.FileManager");
Method openMethod =
eieio.getMethod("openURL", new Class[] { String.class });
openMethod.invoke(null, new Object[] { url });
} catch (Exception e) {
e.printStackTrace();
}
} else {
//throw new RuntimeException("Can't open URLs for this platform");
// Just pass it off to open() and hope for the best
open(url);
}
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("Could not open " + url);
}
*/
}
/**
* ( begin auto-generated from open.xml )
*
* Attempts to open an application or file using your platform's launcher.
* The <b>file</b> parameter is a String specifying the file name and
* location. The location parameter must be a full path name, or the name
* of an executable in the system's PATH. In most cases, using a full path
* is the best option, rather than relying on the system PATH. Be sure to
* make the file executable before attempting to open it (chmod +x).
* <br/> <br/>
* The <b>args</b> parameter is a String or String array which is passed to
* the command line. If you have multiple parameters, e.g. an application
* and a document, or a command with multiple switches, use the version
* that takes a String array, and place each individual item in a separate
* element.
* <br/> <br/>
* If args is a String (not an array), then it can only be a single file or
* application with no parameters. It's not the same as executing that
* String using a shell. For instance, open("jikes -help") will not work properly.
* <br/> <br/>
* This function behaves differently on each platform. On Windows, the
* parameters are sent to the Windows shell via "cmd /c". On Mac OS X, the
* "open" command is used (type "man open" in Terminal.app for
* documentation). On Linux, it first tries gnome-open, then kde-open, but
* if neither are available, it sends the command to the shell without any
* alterations.
* <br/> <br/>
* For users familiar with Java, this is not quite the same as
* Runtime.exec(), because the launcher command is prepended. Instead, the
* <b>exec(String[])</b> function is a shortcut for
* Runtime.getRuntime.exec(String[]).
*
* ( end auto-generated )
* @webref input:files
* @param filename name of the file
* @usage Application
*/
static public void open(String filename) {
open(new String[] { filename });
}
static String openLauncher;
/**
* Launch a process using a platforms shell. This version uses an array
* to make it easier to deal with spaces in the individual elements.
* (This avoids the situation of trying to put single or double quotes
* around different bits).
*
* @param argv list of commands passed to the command line
*/
static public Process open(String argv[]) {
String[] params = null;
if (platform == WINDOWS) {
// just launching the .html file via the shell works
// but make sure to chmod +x the .html files first
// also place quotes around it in case there's a space
// in the user.dir part of the url
params = new String[] { "cmd", "/c" };
} else if (platform == MACOSX) {
params = new String[] { "open" };
} else if (platform == LINUX) {
if (openLauncher == null) {
// Attempt to use gnome-open
try {
Process p = Runtime.getRuntime().exec(new String[] { "gnome-open" });
/*int result =*/ p.waitFor();
// Not installed will throw an IOException (JDK 1.4.2, Ubuntu 7.04)
openLauncher = "gnome-open";
} catch (Exception e) { }
}
if (openLauncher == null) {
// Attempt with kde-open
try {
Process p = Runtime.getRuntime().exec(new String[] { "kde-open" });
/*int result =*/ p.waitFor();
openLauncher = "kde-open";
} catch (Exception e) { }
}
if (openLauncher == null) {
System.err.println("Could not find gnome-open or kde-open, " +
"the open() command may not work.");
}
if (openLauncher != null) {
params = new String[] { openLauncher };
}
//} else { // give up and just pass it to Runtime.exec()
//open(new String[] { filename });
//params = new String[] { filename };
}
if (params != null) {
// If the 'open', 'gnome-open' or 'cmd' are already included
if (params[0].equals(argv[0])) {
// then don't prepend those params again
return exec(argv);
} else {
params = concat(params, argv);
return exec(params);
}
} else {
return exec(argv);
}
}
static public Process exec(String[] argv) {
try {
return Runtime.getRuntime().exec(argv);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Could not open " + join(argv, ' '));
}
}
//////////////////////////////////////////////////////////////
/**
* Function for an applet/application to kill itself and
* display an error. Mostly this is here to be improved later.
*/
public void die(String what) {
dispose();
throw new RuntimeException(what);
}
/**
* Same as above but with an exception. Also needs work.
*/
public void die(String what, Exception e) {
if (e != null) e.printStackTrace();
die(what);
}
/**
* ( begin auto-generated from exit.xml )
*
* Quits/stops/exits the program. Programs without a <b>draw()</b> function
* exit automatically after the last line has run, but programs with
* <b>draw()</b> run continuously until the program is manually stopped or
* <b>exit()</b> is run.<br />
* <br />
* Rather than terminating immediately, <b>exit()</b> will cause the sketch
* to exit after <b>draw()</b> has completed (or after <b>setup()</b>
* completes if called during the <b>setup()</b> function).<br />
* <br />
* For Java programmers, this is <em>not</em> the same as System.exit().
* Further, System.exit() should not be used because closing out an
* application while <b>draw()</b> is running may cause a crash
* (particularly with P3D).
*
* ( end auto-generated )
* @webref structure
*/
public void exit() {
if (thread == null) {
// exit immediately, dispose() has already been called,
// meaning that the main thread has long since exited
exitActual();
} else if (looping) {
// dispose() will be called as the thread exits
finished = true;
// tell the code to call exit2() to do a System.exit()
// once the next draw() has completed
exitCalled = true;
} else if (!looping) {
// if not looping, shut down things explicitly,
// because the main thread will be sleeping
dispose();
// now get out
exitActual();
}
}
void exitActual() {
try {
System.exit(0);
} catch (SecurityException e) {
// don't care about applet security exceptions
}
}
/**
* Called to dispose of resources and shut down the sketch.
* Destroys the thread, dispose the renderer,and notify listeners.
* <p>
* Not to be called or overriden by users. If called multiple times,
* will only notify listeners once. Register a dispose listener instead.
*/
public void dispose() {
// moved here from stop()
finished = true; // let the sketch know it is shut down time
// don't run the disposers twice
if (thread != null) {
thread = null;
// shut down renderer
if (g != null) {
g.dispose();
}
// run dispose() methods registered by libraries
handleMethods("dispose");
}
}
//////////////////////////////////////////////////////////////
/**
* Call a method in the current class based on its name.
* <p/>
* Note that the function being called must be public. Inside the PDE,
* 'public' is automatically added, but when used without the preprocessor,
* (like from Eclipse) you'll have to do it yourself.
*/
public void method(String name) {
try {
Method method = getClass().getMethod(name, new Class[] {});
method.invoke(this, new Object[] { });
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.getTargetException().printStackTrace();
} catch (NoSuchMethodException nsme) {
System.err.println("There is no public " + name + "() method " +
"in the class " + getClass().getName());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Launch a new thread and call the specified function from that new thread.
* This is a very simple way to do a thread without needing to get into
* classes, runnables, etc.
* <p/>
* Note that the function being called must be public. Inside the PDE,
* 'public' is automatically added, but when used without the preprocessor,
* (like from Eclipse) you'll have to do it yourself.
*/
public void thread(final String name) {
Thread later = new Thread() {
@Override
public void run() {
method(name);
}
};
later.start();
}
//////////////////////////////////////////////////////////////
// SCREEN GRABASS
/**
* ( begin auto-generated from save.xml )
*
* Saves an image from the display window. Images are saved in TIFF, TARGA,
* JPEG, and PNG format depending on the extension within the
* <b>filename</b> parameter. For example, "image.tif" will have a TIFF
* image and "image.png" will save a PNG image. If no extension is included
* in the filename, the image will save in TIFF format and <b>.tif</b> will
* be added to the name. These files are saved to the sketch's folder,
* which may be opened by selecting "Show sketch folder" from the "Sketch"
* menu. It is not possible to use <b>save()</b> while running the program
* in a web browser.
* <br/> images saved from the main drawing window will be opaque. To save
* images without a background, use <b>createGraphics()</b>.
*
* ( end auto-generated )
* @webref output:image
* @param filename any sequence of letters and numbers
* @see PApplet#saveFrame()
* @see PApplet#createGraphics(int, int, String)
*/
public void save(String filename) {
g.save(savePath(filename));
}
/**
*/
public void saveFrame() {
try {
g.save(savePath("screen-" + nf(frameCount, 4) + ".tif"));
} catch (SecurityException se) {
System.err.println("Can't use saveFrame() when running in a browser, " +
"unless using a signed applet.");
}
}
/**
* ( begin auto-generated from saveFrame.xml )
*
* Saves a numbered sequence of images, one image each time the function is
* run. To save an image that is identical to the display window, run the
* function at the end of <b>draw()</b> or within mouse and key events such
* as <b>mousePressed()</b> and <b>keyPressed()</b>. If <b>saveFrame()</b>
* is called without parameters, it will save the files as screen-0000.tif,
* screen-0001.tif, etc. It is possible to specify the name of the sequence
* with the <b>filename</b> parameter and make the choice of saving TIFF,
* TARGA, PNG, or JPEG files with the <b>ext</b> parameter. These image
* sequences can be loaded into programs such as Apple's QuickTime software
* and made into movies. These files are saved to the sketch's folder,
* which may be opened by selecting "Show sketch folder" from the "Sketch"
* menu.<br />
* <br />
* It is not possible to use saveXxxxx() functions inside a web browser
* unless the sketch is <a
* href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</A>. To
* save a file back to a server, see the <a
* href="http://wiki.processing.org/w/Saving_files_to_a_web-server">save to
* web</A> code snippet on the Processing Wiki.<br/>
* <br/ >
* All images saved from the main drawing window will be opaque. To save
* images without a background, use <b>createGraphics()</b>.
*
* ( end auto-generated )
* @webref output:image
* @see PApplet#save(String)
* @see PApplet#createGraphics(int, int, String, String)
* @param filename any sequence of letters or numbers that ends with either ".tif", ".tga", ".jpg", or ".png"
*/
public void saveFrame(String filename) {
try {
g.save(savePath(insertFrame(filename)));
} catch (SecurityException se) {
System.err.println("Can't use saveFrame() when running in a browser, " +
"unless using a signed applet.");
}
}
/**
* Check a string for #### signs to see if the frame number should be
* inserted. Used for functions like saveFrame() and beginRecord() to
* replace the # marks with the frame number. If only one # is used,
* it will be ignored, under the assumption that it's probably not
* intended to be the frame number.
*/
public String insertFrame(String what) {
int first = what.indexOf('#');
int last = what.lastIndexOf('#');
if ((first != -1) && (last - first > 0)) {
String prefix = what.substring(0, first);
int count = last - first + 1;
String suffix = what.substring(last + 1);
return prefix + nf(frameCount, count) + suffix;
}
return what; // no change
}
//////////////////////////////////////////////////////////////
// CURSOR
//
int cursorType = ARROW; // cursor type
boolean cursorVisible = true; // cursor visibility flag
// PImage invisibleCursor;
Cursor invisibleCursor;
/**
* Set the cursor type
* @param kind either ARROW, CROSS, HAND, MOVE, TEXT, or WAIT
*/
public void cursor(int kind) {
setCursor(Cursor.getPredefinedCursor(kind));
cursorVisible = true;
this.cursorType = kind;
}
/**
* Replace the cursor with the specified PImage. The x- and y-
* coordinate of the center will be the center of the image.
*/
public void cursor(PImage img) {
cursor(img, img.width/2, img.height/2);
}
/**
* ( begin auto-generated from cursor.xml )
*
* Sets the cursor to a predefined symbol, an image, or makes it visible if
* already hidden. If you are trying to set an image as the cursor, it is
* recommended to make the size 16x16 or 32x32 pixels. It is not possible
* to load an image as the cursor if you are exporting your program for the
* Web and not all MODES work with all Web browsers. The values for
* parameters <b>x</b> and <b>y</b> must be less than the dimensions of the image.
* <br /> <br />
* Setting or hiding the cursor generally does not work with "Present" mode
* (when running full-screen).
*
* ( end auto-generated )
* <h3>Advanced</h3>
* Set a custom cursor to an image with a specific hotspot.
* Only works with JDK 1.2 and later.
* Currently seems to be broken on Java 1.4 for Mac OS X
* <p>
* Based on code contributed by Amit Pitaru, plus additional
* code to handle Java versions via reflection by Jonathan Feinberg.
* Reflection removed for release 0128 and later.
* @webref environment
* @see PApplet#noCursor()
* @param img any variable of type PImage
* @param x the horizontal active spot of the cursor
* @param y the vertical active spot of the cursor
*/
public void cursor(PImage img, int x, int y) {
// don't set this as cursor type, instead use cursor_type
// to save the last cursor used in case cursor() is called
//cursor_type = Cursor.CUSTOM_CURSOR;
Image jimage =
createImage(new MemoryImageSource(img.width, img.height,
img.pixels, 0, img.width));
Point hotspot = new Point(x, y);
Toolkit tk = Toolkit.getDefaultToolkit();
Cursor cursor = tk.createCustomCursor(jimage, hotspot, "Custom Cursor");
setCursor(cursor);
cursorVisible = true;
}
/**
* Show the cursor after noCursor() was called.
* Notice that the program remembers the last set cursor type
*/
public void cursor() {
// maybe should always set here? seems dangerous, since
// it's likely that java will set the cursor to something
// else on its own, and the applet will be stuck b/c bagel
// thinks that the cursor is set to one particular thing
if (!cursorVisible) {
cursorVisible = true;
setCursor(Cursor.getPredefinedCursor(cursorType));
}
}
/**
* ( begin auto-generated from noCursor.xml )
*
* Hides the cursor from view. Will not work when running the program in a
* web browser or when running in full screen (Present) mode.
*
* ( end auto-generated )
* <h3>Advanced</h3>
* Hide the cursor by creating a transparent image
* and using it as a custom cursor.
* @webref environment
* @see PApplet#cursor()
* @usage Application
*/
public void noCursor() {
// in 0216, just re-hide it?
// if (!cursorVisible) return; // don't hide if already hidden.
if (invisibleCursor == null) {
BufferedImage cursorImg =
new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
invisibleCursor =
getToolkit().createCustomCursor(cursorImg, new Point(8, 8), "blank");
}
// was formerly 16x16, but the 0x0 was added by jdf as a fix
// for macosx, which wasn't honoring the invisible cursor
// cursor(invisibleCursor, 8, 8);
setCursor(invisibleCursor);
cursorVisible = false;
}
//////////////////////////////////////////////////////////////
/**
* ( begin auto-generated from print.xml )
*
* Writes to the console area of the Processing environment. This is often
* helpful for looking at the data a program is producing. The companion
* function <b>println()</b> works like <b>print()</b>, but creates a new
* line of text for each call to the function. Individual elements can be
* separated with quotes ("") and joined with the addition operator (+).<br />
* <br />
* Beginning with release 0125, to print the contents of an array, use
* println(). There's no sensible way to do a <b>print()</b> of an array,
* because there are too many possibilities for how to separate the data
* (spaces, commas, etc). If you want to print an array as a single line,
* use <b>join()</b>. With <b>join()</b>, you can choose any delimiter you
* like and <b>print()</b> the result.<br />
* <br />
* Using <b>print()</b> on an object will output <b>null</b>, a memory
* location that may look like "@10be08," or the result of the
* <b>toString()</b> method from the object that's being printed. Advanced
* users who want more useful output when calling <b>print()</b> on their
* own classes can add a <b>toString()</b> method to the class that returns
* a String.
*
* ( end auto-generated )
* @webref output:text_area
* @usage IDE
* @param what boolean, byte, char, color, int, float, String, Object
* @see PApplet#println(byte)
* @see PApplet#join(String[], char)
*/
static public void print(byte what) {
System.out.print(what);
System.out.flush();
}
static public void print(boolean what) {
System.out.print(what);
System.out.flush();
}
static public void print(char what) {
System.out.print(what);
System.out.flush();
}
static public void print(int what) {
System.out.print(what);
System.out.flush();
}
static public void print(long what) {
System.out.print(what);
System.out.flush();
}
static public void print(float what) {
System.out.print(what);
System.out.flush();
}
static public void print(double what) {
System.out.print(what);
System.out.flush();
}
static public void print(String what) {
System.out.print(what);
System.out.flush();
}
static public void print(Object what) {
if (what == null) {
// special case since this does fuggly things on > 1.1
System.out.print("null");
} else {
System.out.println(what.toString());
}
}
//
/**
* ( begin auto-generated from println.xml )
*
* Writes to the text area of the Processing environment's console. This is
* often helpful for looking at the data a program is producing. Each call
* to this function creates a new line of output. Individual elements can
* be separated with quotes ("") and joined with the string concatenation
* operator (+). See <b>print()</b> for more about what to expect in the output.
* <br/><br/> <b>println()</b> on an array (by itself) will write the
* contents of the array to the console. This is often helpful for looking
* at the data a program is producing. A new line is put between each
* element of the array. This function can only print one dimensional
* arrays. For arrays with higher dimensions, the result will be closer to
* that of <b>print()</b>.
*
* ( end auto-generated )
* @webref output:text_area
* @usage IDE
* @see PApplet#print(byte)
*/
static public void println() {
System.out.println();
}
//
/**
* @param what boolean, byte, char, color, int, float, String, Object
*/
static public void println(byte what) {
System.out.println(what);
System.out.flush();
}
static public void println(boolean what) {
System.out.println(what);
System.out.flush();
}
static public void println(char what) {
System.out.println(what);
System.out.flush();
}
static public void println(int what) {
System.out.println(what);
System.out.flush();
}
static public void println(long what) {
System.out.println(what);
System.out.flush();
}
static public void println(float what) {
System.out.println(what);
System.out.flush();
}
static public void println(double what) {
System.out.println(what);
System.out.flush();
}
static public void println(String what) {
System.out.println(what);
System.out.flush();
}
static public void println(Object what) {
if (what == null) {
// special case since this does fuggly things on > 1.1
System.out.println("null");
} else {
String name = what.getClass().getName();
if (name.charAt(0) == '[') {
switch (name.charAt(1)) {
case '[':
// don't even mess with multi-dimensional arrays (case '[')
// or anything else that's not int, float, boolean, char
System.out.println(what);
break;
case 'L':
// print a 1D array of objects as individual elements
Object poo[] = (Object[]) what;
for (int i = 0; i < poo.length; i++) {
if (poo[i] instanceof String) {
System.out.println("[" + i + "] \"" + poo[i] + "\"");
} else {
System.out.println("[" + i + "] " + poo[i]);
}
}
break;
case 'Z': // boolean
boolean zz[] = (boolean[]) what;
for (int i = 0; i < zz.length; i++) {
System.out.println("[" + i + "] " + zz[i]);
}
break;
case 'B': // byte
byte bb[] = (byte[]) what;
for (int i = 0; i < bb.length; i++) {
System.out.println("[" + i + "] " + bb[i]);
}
break;
case 'C': // char
char cc[] = (char[]) what;
for (int i = 0; i < cc.length; i++) {
System.out.println("[" + i + "] '" + cc[i] + "'");
}
break;
case 'I': // int
int ii[] = (int[]) what;
for (int i = 0; i < ii.length; i++) {
System.out.println("[" + i + "] " + ii[i]);
}
break;
case 'J': // int
long jj[] = (long[]) what;
for (int i = 0; i < jj.length; i++) {
System.out.println("[" + i + "] " + jj[i]);
}
break;
case 'F': // float
float ff[] = (float[]) what;
for (int i = 0; i < ff.length; i++) {
System.out.println("[" + i + "] " + ff[i]);
}
break;
case 'D': // double
double dd[] = (double[]) what;
for (int i = 0; i < dd.length; i++) {
System.out.println("[" + i + "] " + dd[i]);
}
break;
default:
System.out.println(what);
}
} else { // not an array
System.out.println(what);
}
}
}
static public void debug(String msg) {
if (DEBUG) println(msg);
}
//
/*
// not very useful, because it only works for public (and protected?)
// fields of a class, not local variables to methods
public void printvar(String name) {
try {
Field field = getClass().getDeclaredField(name);
println(name + " = " + field.get(this));
} catch (Exception e) {
e.printStackTrace();
}
}
*/
//////////////////////////////////////////////////////////////
// MATH
// lots of convenience methods for math with floats.
// doubles are overkill for processing applets, and casting
// things all the time is annoying, thus the functions below.
/**
* ( begin auto-generated from abs.xml )
*
* Calculates the absolute value (magnitude) of a number. The absolute
* value of a number is always positive.
*
* ( end auto-generated )
* @webref math:calculation
* @param n number to compute
*/
static public final float abs(float n) {
return (n < 0) ? -n : n;
}
static public final int abs(int n) {
return (n < 0) ? -n : n;
}
/**
* ( begin auto-generated from sq.xml )
*
* Squares a number (multiplies a number by itself). The result is always a
* positive number, as multiplying two negative numbers always yields a
* positive result. For example, -1 * -1 = 1.
*
* ( end auto-generated )
* @webref math:calculation
* @param n number to square
* @see PApplet#sqrt(float)
*/
static public final float sq(float n) {
return n*n;
}
/**
* ( begin auto-generated from sqrt.xml )
*
* Calculates the square root of a number. The square root of a number is
* always positive, even though there may be a valid negative root. The
* square root <b>s</b> of number <b>a</b> is such that <b>s*s = a</b>. It
* is the opposite of squaring.
*
* ( end auto-generated )
* @webref math:calculation
* @param n non-negative number
* @see PApplet#pow(float, float)
* @see PApplet#sq(float)
*/
static public final float sqrt(float n) {
return (float)Math.sqrt(n);
}
/**
* ( begin auto-generated from log.xml )
*
* Calculates the natural logarithm (the base-<i>e</i> logarithm) of a
* number. This function expects the values greater than 0.0.
*
* ( end auto-generated )
* @webref math:calculation
* @param n number greater than 0.0
*/
static public final float log(float n) {
return (float)Math.log(n);
}
/**
* ( begin auto-generated from exp.xml )
*
* Returns Euler's number <i>e</i> (2.71828...) raised to the power of the
* <b>value</b> parameter.
*
* ( end auto-generated )
* @webref math:calculation
* @param n exponent to raise
*/
static public final float exp(float n) {
return (float)Math.exp(n);
}
/**
* ( begin auto-generated from pow.xml )
*
* Facilitates exponential expressions. The <b>pow()</b> function is an
* efficient way of multiplying numbers by themselves (or their reciprocal)
* in large quantities. For example, <b>pow(3, 5)</b> is equivalent to the
* expression 3*3*3*3*3 and <b>pow(3, -5)</b> is equivalent to 1 / 3*3*3*3*3.
*
* ( end auto-generated )
* @webref math:calculation
* @param n base of the exponential expression
* @param e power by which to raise the base
* @see PApplet#sqrt(float)
*/
static public final float pow(float n, float e) {
return (float)Math.pow(n, e);
}
/**
* ( begin auto-generated from max.xml )
*
* Determines the largest value in a sequence of numbers.
*
* ( end auto-generated )
* @webref math:calculation
* @param a first number to compare
* @param b second number to compare
* @see PApplet#min(float, float, float)
*/
static public final int max(int a, int b) {
return (a > b) ? a : b;
}
static public final float max(float a, float b) {
return (a > b) ? a : b;
}
/*
static public final double max(double a, double b) {
return (a > b) ? a : b;
}
*/
/**
* @param c third number to compare
*/
static public final int max(int a, int b, int c) {
return (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
}
static public final float max(float a, float b, float c) {
return (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
}
/**
* @param list array of numbers to compare
*/
static public final int max(int[] list) {
if (list.length == 0) {
throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX);
}
int max = list[0];
for (int i = 1; i < list.length; i++) {
if (list[i] > max) max = list[i];
}
return max;
}
static public final float max(float[] list) {
if (list.length == 0) {
throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX);
}
float max = list[0];
for (int i = 1; i < list.length; i++) {
if (list[i] > max) max = list[i];
}
return max;
}
/**
* Find the maximum value in an array.
* Throws an ArrayIndexOutOfBoundsException if the array is length 0.
* @param list the source array
* @return The maximum value
*/
/*
static public final double max(double[] list) {
if (list.length == 0) {
throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX);
}
double max = list[0];
for (int i = 1; i < list.length; i++) {
if (list[i] > max) max = list[i];
}
return max;
}
*/
static public final int min(int a, int b) {
return (a < b) ? a : b;
}
static public final float min(float a, float b) {
return (a < b) ? a : b;
}
/*
static public final double min(double a, double b) {
return (a < b) ? a : b;
}
*/
static public final int min(int a, int b, int c) {
return (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c);
}
/**
* ( begin auto-generated from min.xml )
*
* Determines the smallest value in a sequence of numbers.
*
* ( end auto-generated )
* @webref math:calculation
* @param a first number
* @param b second number
* @param c third number
* @see PApplet#max(float, float, float)
*/
static public final float min(float a, float b, float c) {
return (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c);
}
/*
static public final double min(double a, double b, double c) {
return (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c);
}
*/
/**
* @param list array of numbers to compare
*/
static public final int min(int[] list) {
if (list.length == 0) {
throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX);
}
int min = list[0];
for (int i = 1; i < list.length; i++) {
if (list[i] < min) min = list[i];
}
return min;
}
static public final float min(float[] list) {
if (list.length == 0) {
throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX);
}
float min = list[0];
for (int i = 1; i < list.length; i++) {
if (list[i] < min) min = list[i];
}
return min;
}
/**
* Find the minimum value in an array.
* Throws an ArrayIndexOutOfBoundsException if the array is length 0.
* @param list the source array
* @return The minimum value
*/
/*
static public final double min(double[] list) {
if (list.length == 0) {
throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX);
}
double min = list[0];
for (int i = 1; i < list.length; i++) {
if (list[i] < min) min = list[i];
}
return min;
}
*/
static public final int constrain(int amt, int low, int high) {
return (amt < low) ? low : ((amt > high) ? high : amt);
}
/**
* ( begin auto-generated from constrain.xml )
*
* Constrains a value to not exceed a maximum and minimum value.
*
* ( end auto-generated )
* @webref math:calculation
* @param amt the value to constrain
* @param low minimum limit
* @param high maximum limit
* @see PApplet#max(float, float, float)
* @see PApplet#min(float, float, float)
*/
static public final float constrain(float amt, float low, float high) {
return (amt < low) ? low : ((amt > high) ? high : amt);
}
/**
* ( begin auto-generated from sin.xml )
*
* Calculates the sine of an angle. This function expects the values of the
* <b>angle</b> parameter to be provided in radians (values from 0 to
* 6.28). Values are returned in the range -1 to 1.
*
* ( end auto-generated )
* @webref math:trigonometry
* @param angle an angle in radians
* @see PApplet#cos(float)
* @see PApplet#tan(float)
* @see PApplet#radians(float)
*/
static public final float sin(float angle) {
return (float)Math.sin(angle);
}
/**
* ( begin auto-generated from cos.xml )
*
* Calculates the cosine of an angle. This function expects the values of
* the <b>angle</b> parameter to be provided in radians (values from 0 to
* PI*2). Values are returned in the range -1 to 1.
*
* ( end auto-generated )
* @webref math:trigonometry
* @param angle an angle in radians
* @see PApplet#sin(float)
* @see PApplet#tan(float)
* @see PApplet#radians(float)
*/
static public final float cos(float angle) {
return (float)Math.cos(angle);
}
/**
* ( begin auto-generated from tan.xml )
*
* Calculates the ratio of the sine and cosine of an angle. This function
* expects the values of the <b>angle</b> parameter to be provided in
* radians (values from 0 to PI*2). Values are returned in the range
* <b>infinity</b> to <b>-infinity</b>.
*
* ( end auto-generated )
* @webref math:trigonometry
* @param angle an angle in radians
* @see PApplet#cos(float)
* @see PApplet#sin(float)
* @see PApplet#radians(float)
*/
static public final float tan(float angle) {
return (float)Math.tan(angle);
}
/**
* ( begin auto-generated from asin.xml )
*
* The inverse of <b>sin()</b>, returns the arc sine of a value. This
* function expects the values in the range of -1 to 1 and values are
* returned in the range <b>-PI/2</b> to <b>PI/2</b>.
*
* ( end auto-generated )
* @webref math:trigonometry
* @param value the value whose arc sine is to be returned
* @see PApplet#sin(float)
* @see PApplet#acos(float)
* @see PApplet#atan(float)
*/
static public final float asin(float value) {
return (float)Math.asin(value);
}
/**
* ( begin auto-generated from acos.xml )
*
* The inverse of <b>cos()</b>, returns the arc cosine of a value. This
* function expects the values in the range of -1 to 1 and values are
* returned in the range <b>0</b> to <b>PI (3.1415927)</b>.
*
* ( end auto-generated )
* @webref math:trigonometry
* @param value the value whose arc cosine is to be returned
* @see PApplet#cos(float)
* @see PApplet#asin(float)
* @see PApplet#atan(float)
*/
static public final float acos(float value) {
return (float)Math.acos(value);
}
/**
* ( begin auto-generated from atan.xml )
*
* The inverse of <b>tan()</b>, returns the arc tangent of a value. This
* function expects the values in the range of -Infinity to Infinity
* (exclusive) and values are returned in the range <b>-PI/2</b> to <b>PI/2 </b>.
*
* ( end auto-generated )
* @webref math:trigonometry
* @param value -Infinity to Infinity (exclusive)
* @see PApplet#tan(float)
* @see PApplet#asin(float)
* @see PApplet#acos(float)
*/
static public final float atan(float value) {
return (float)Math.atan(value);
}
/**
* ( begin auto-generated from atan2.xml )
*
* Calculates the angle (in radians) from a specified point to the
* coordinate origin as measured from the positive x-axis. Values are
* returned as a <b>float</b> in the range from <b>PI</b> to <b>-PI</b>.
* The <b>atan2()</b> function is most often used for orienting geometry to
* the position of the cursor. Note: The y-coordinate of the point is the
* first parameter and the x-coordinate is the second due the the structure
* of calculating the tangent.
*
* ( end auto-generated )
* @webref math:trigonometry
* @param y y-coordinate of the point
* @param x x-coordinate of the point
* @see PApplet#tan(float)
*/
static public final float atan2(float y, float x) {
return (float)Math.atan2(y, x);
}
/**
* ( begin auto-generated from degrees.xml )
*
* Converts a radian measurement to its corresponding value in degrees.
* Radians and degrees are two ways of measuring the same thing. There are
* 360 degrees in a circle and 2*PI radians in a circle. For example,
* 90° = PI/2 = 1.5707964. All trigonometric functions in Processing
* require their parameters to be specified in radians.
*
* ( end auto-generated )
* @webref math:trigonometry
* @param radians radian value to convert to degrees
* @see PApplet#radians(float)
*/
static public final float degrees(float radians) {
return radians * RAD_TO_DEG;
}
/**
* ( begin auto-generated from radians.xml )
*
* Converts a degree measurement to its corresponding value in radians.
* Radians and degrees are two ways of measuring the same thing. There are
* 360 degrees in a circle and 2*PI radians in a circle. For example,
* 90° = PI/2 = 1.5707964. All trigonometric functions in Processing
* require their parameters to be specified in radians.
*
* ( end auto-generated )
* @webref math:trigonometry
* @param degrees degree value to convert to radians
* @see PApplet#degrees(float)
*/
static public final float radians(float degrees) {
return degrees * DEG_TO_RAD;
}
/**
* ( begin auto-generated from ceil.xml )
*
* Calculates the closest int value that is greater than or equal to the
* value of the parameter. For example, <b>ceil(9.03)</b> returns the value 10.
*
* ( end auto-generated )
* @webref math:calculation
* @param n number to round up
* @see PApplet#floor(float)
* @see PApplet#round(float)
*/
static public final int ceil(float n) {
return (int) Math.ceil(n);
}
/**
* ( begin auto-generated from floor.xml )
*
* Calculates the closest int value that is less than or equal to the value
* of the parameter.
*
* ( end auto-generated )
* @webref math:calculation
* @param n number to round down
* @see PApplet#ceil(float)
* @see PApplet#round(float)
*/
static public final int floor(float n) {
return (int) Math.floor(n);
}
/**
* ( begin auto-generated from round.xml )
*
* Calculates the integer closest to the <b>value</b> parameter. For
* example, <b>round(9.2)</b> returns the value 9.
*
* ( end auto-generated )
* @webref math:calculation
* @param n number to round
* @see PApplet#floor(float)
* @see PApplet#ceil(float)
*/
static public final int round(float n) {
return Math.round(n);
}
static public final float mag(float a, float b) {
return (float)Math.sqrt(a*a + b*b);
}
/**
* ( begin auto-generated from mag.xml )
*
* Calculates the magnitude (or length) of a vector. A vector is a
* direction in space commonly used in computer graphics and linear
* algebra. Because it has no "start" position, the magnitude of a vector
* can be thought of as the distance from coordinate (0,0) to its (x,y)
* value. Therefore, mag() is a shortcut for writing "dist(0, 0, x, y)".
*
* ( end auto-generated )
* @webref math:calculation
* @param a first value
* @param b second value
* @param c third value
* @see PApplet#dist(float, float, float, float)
*/
static public final float mag(float a, float b, float c) {
return (float)Math.sqrt(a*a + b*b + c*c);
}
static public final float dist(float x1, float y1, float x2, float y2) {
return sqrt(sq(x2-x1) + sq(y2-y1));
}
/**
* ( begin auto-generated from dist.xml )
*
* Calculates the distance between two points.
*
* ( end auto-generated )
* @webref math:calculation
* @param x1 x-coordinate of the first point
* @param y1 y-coordinate of the first point
* @param z1 z-coordinate of the first point
* @param x2 x-coordinate of the second point
* @param y2 y-coordinate of the second point
* @param z2 z-coordinate of the second point
*/
static public final float dist(float x1, float y1, float z1,
float x2, float y2, float z2) {
return sqrt(sq(x2-x1) + sq(y2-y1) + sq(z2-z1));
}
/**
* ( begin auto-generated from lerp.xml )
*
* Calculates a number between two numbers at a specific increment. The
* <b>amt</b> parameter is the amount to interpolate between the two values
* where 0.0 equal to the first point, 0.1 is very near the first point,
* 0.5 is half-way in between, etc. The lerp function is convenient for
* creating motion along a straight path and for drawing dotted lines.
*
* ( end auto-generated )
* @webref math:calculation
* @param start first value
* @param stop second value
* @param amt float between 0.0 and 1.0
* @see PGraphics#curvePoint(float, float, float, float, float)
* @see PGraphics#bezierPoint(float, float, float, float, float)
*/
static public final float lerp(float start, float stop, float amt) {
return start + (stop-start) * amt;
}
/**
* ( begin auto-generated from norm.xml )
*
* Normalizes a number from another range into a value between 0 and 1.
* <br/> <br/>
* Identical to map(value, low, high, 0, 1);
* <br/> <br/>
* Numbers outside the range are not clamped to 0 and 1, because
* out-of-range values are often intentional and useful.
*
* ( end auto-generated )
* @webref math:calculation
* @param value the incoming value to be converted
* @param start lower bound of the value's current range
* @param stop upper bound of the value's current range
* @see PApplet#map(float, float, float, float, float)
* @see PApplet#lerp(float, float, float)
*/
static public final float norm(float value, float start, float stop) {
return (value - start) / (stop - start);
}
/**
* ( begin auto-generated from map.xml )
*
* Re-maps a number from one range to another. In the example above,
* the number '25' is converted from a value in the range 0..100 into
* a value that ranges from the left edge (0) to the right edge (width)
* of the screen.
* <br/> <br/>
* Numbers outside the range are not clamped to 0 and 1, because
* out-of-range values are often intentional and useful.
*
* ( end auto-generated )
* @webref math:calculation
* @param value the incoming value to be converted
* @param start1 lower bound of the value's current range
* @param stop1 upper bound of the value's current range
* @param start2 lower bound of the value's target range
* @param stop2 upper bound of the value's target range
* @see PApplet#norm(float, float, float)
* @see PApplet#lerp(float, float, float)
*/
static public final float map(float value,
float start1, float stop1,
float start2, float stop2) {
return start2 + (stop2 - start2) * ((value - start1) / (stop1 - start1));
}
/*
static public final double map(double value,
double istart, double istop,
double ostart, double ostop) {
return ostart + (ostop - ostart) * ((value - istart) / (istop - istart));
}
*/
//////////////////////////////////////////////////////////////
// RANDOM NUMBERS
Random internalRandom;
/**
*
*/
public final float random(float high) {
// for some reason (rounding error?) Math.random() * 3
// can sometimes return '3' (once in ~30 million tries)
// so a check was added to avoid the inclusion of 'howbig'
// avoid an infinite loop
if (high == 0) return 0;
// internal random number object
if (internalRandom == null) internalRandom = new Random();
float value = 0;
do {
//value = (float)Math.random() * howbig;
value = internalRandom.nextFloat() * high;
} while (value == high);
return value;
}
/**
* ( begin auto-generated from random.xml )
*
* Generates random numbers. Each time the <b>random()</b> function is
* called, it returns an unexpected value within the specified range. If
* one parameter is passed to the function it will return a <b>float</b>
* between zero and the value of the <b>high</b> parameter. The function
* call <b>random(5)</b> returns values between 0 and 5 (starting at zero,
* up to but not including 5). If two parameters are passed, it will return
* a <b>float</b> with a value between the the parameters. The function
* call <b>random(-5, 10.2)</b> returns values starting at -5 up to (but
* not including) 10.2. To convert a floating-point random number to an
* integer, use the <b>int()</b> function.
*
* ( end auto-generated )
* @webref math:random
* @param low lower limit
* @param high upper limit
* @see PApplet#randomSeed(long)
* @see PApplet#noise(float, float, float)
*/
public final float random(float low, float high) {
if (low >= high) return low;
float diff = high - low;
return random(diff) + low;
}
/**
* ( begin auto-generated from randomSeed.xml )
*
* Sets the seed value for <b>random()</b>. By default, <b>random()</b>
* produces different results each time the program is run. Set the
* <b>value</b> parameter to a constant to return the same pseudo-random
* numbers each time the software is run.
*
* ( end auto-generated )
* @webref math:random
* @param seed seed value
* @see PApplet#random(float,float)
* @see PApplet#noise(float, float, float)
* @see PApplet#noiseSeed(long)
*/
public final void randomSeed(long seed) {
// internal random number object
if (internalRandom == null) internalRandom = new Random();
internalRandom.setSeed(seed);
}
//////////////////////////////////////////////////////////////
// PERLIN NOISE
// [toxi 040903]
// octaves and amplitude amount per octave are now user controlled
// via the noiseDetail() function.
// [toxi 030902]
// cleaned up code and now using bagel's cosine table to speed up
// [toxi 030901]
// implementation by the german demo group farbrausch
// as used in their demo "art": http://www.farb-rausch.de/fr010src.zip
static final int PERLIN_YWRAPB = 4;
static final int PERLIN_YWRAP = 1<<PERLIN_YWRAPB;
static final int PERLIN_ZWRAPB = 8;
static final int PERLIN_ZWRAP = 1<<PERLIN_ZWRAPB;
static final int PERLIN_SIZE = 4095;
int perlin_octaves = 4; // default to medium smooth
float perlin_amp_falloff = 0.5f; // 50% reduction/octave
// [toxi 031112]
// new vars needed due to recent change of cos table in PGraphics
int perlin_TWOPI, perlin_PI;
float[] perlin_cosTable;
float[] perlin;
Random perlinRandom;
/**
*/
public float noise(float x) {
// is this legit? it's a dumb way to do it (but repair it later)
return noise(x, 0f, 0f);
}
/**
*/
public float noise(float x, float y) {
return noise(x, y, 0f);
}
/**
* ( begin auto-generated from noise.xml )
*
* Returns the Perlin noise value at specified coordinates. Perlin noise is
* a random sequence generator producing a more natural ordered, harmonic
* succession of numbers compared to the standard <b>random()</b> function.
* It was invented by Ken Perlin in the 1980s and been used since in
* graphical applications to produce procedural textures, natural motion,
* shapes, terrains etc.<br /><br /> The main difference to the
* <b>random()</b> function is that Perlin noise is defined in an infinite
* n-dimensional space where each pair of coordinates corresponds to a
* fixed semi-random value (fixed only for the lifespan of the program).
* The resulting value will always be between 0.0 and 1.0. Processing can
* compute 1D, 2D and 3D noise, depending on the number of coordinates
* given. The noise value can be animated by moving through the noise space
* as demonstrated in the example above. The 2nd and 3rd dimension can also
* be interpreted as time.<br /><br />The actual noise is structured
* similar to an audio signal, in respect to the function's use of
* frequencies. Similar to the concept of harmonics in physics, perlin
* noise is computed over several octaves which are added together for the
* final result. <br /><br />Another way to adjust the character of the
* resulting sequence is the scale of the input coordinates. As the
* function works within an infinite space the value of the coordinates
* doesn't matter as such, only the distance between successive coordinates
* does (eg. when using <b>noise()</b> within a loop). As a general rule
* the smaller the difference between coordinates, the smoother the
* resulting noise sequence will be. Steps of 0.005-0.03 work best for most
* applications, but this will differ depending on use.
*
* ( end auto-generated )
*
* @webref math:random
* @param x x-coordinate in noise space
* @param y y-coordinate in noise space
* @param z z-coordinate in noise space
* @see PApplet#noiseSeed(long)
* @see PApplet#noiseDetail(int, float)
* @see PApplet#random(float,float)
*/
public float noise(float x, float y, float z) {
if (perlin == null) {
if (perlinRandom == null) {
perlinRandom = new Random();
}
perlin = new float[PERLIN_SIZE + 1];
for (int i = 0; i < PERLIN_SIZE + 1; i++) {
perlin[i] = perlinRandom.nextFloat(); //(float)Math.random();
}
// [toxi 031112]
// noise broke due to recent change of cos table in PGraphics
// this will take care of it
perlin_cosTable = PGraphics.cosLUT;
perlin_TWOPI = perlin_PI = PGraphics.SINCOS_LENGTH;
perlin_PI >>= 1;
}
if (x<0) x=-x;
if (y<0) y=-y;
if (z<0) z=-z;
int xi=(int)x, yi=(int)y, zi=(int)z;
float xf = x - xi;
float yf = y - yi;
float zf = z - zi;
float rxf, ryf;
float r=0;
float ampl=0.5f;
float n1,n2,n3;
for (int i=0; i<perlin_octaves; i++) {
int of=xi+(yi<<PERLIN_YWRAPB)+(zi<<PERLIN_ZWRAPB);
rxf=noise_fsc(xf);
ryf=noise_fsc(yf);
n1 = perlin[of&PERLIN_SIZE];
n1 += rxf*(perlin[(of+1)&PERLIN_SIZE]-n1);
n2 = perlin[(of+PERLIN_YWRAP)&PERLIN_SIZE];
n2 += rxf*(perlin[(of+PERLIN_YWRAP+1)&PERLIN_SIZE]-n2);
n1 += ryf*(n2-n1);
of += PERLIN_ZWRAP;
n2 = perlin[of&PERLIN_SIZE];
n2 += rxf*(perlin[(of+1)&PERLIN_SIZE]-n2);
n3 = perlin[(of+PERLIN_YWRAP)&PERLIN_SIZE];
n3 += rxf*(perlin[(of+PERLIN_YWRAP+1)&PERLIN_SIZE]-n3);
n2 += ryf*(n3-n2);
n1 += noise_fsc(zf)*(n2-n1);
r += n1*ampl;
ampl *= perlin_amp_falloff;
xi<<=1; xf*=2;
yi<<=1; yf*=2;
zi<<=1; zf*=2;
if (xf>=1.0f) { xi++; xf--; }
if (yf>=1.0f) { yi++; yf--; }
if (zf>=1.0f) { zi++; zf--; }
}
return r;
}
// [toxi 031112]
// now adjusts to the size of the cosLUT used via
// the new variables, defined above
private float noise_fsc(float i) {
// using bagel's cosine table instead
return 0.5f*(1.0f-perlin_cosTable[(int)(i*perlin_PI)%perlin_TWOPI]);
}
// [toxi 040903]
// make perlin noise quality user controlled to allow
// for different levels of detail. lower values will produce
// smoother results as higher octaves are surpressed
/**
* ( begin auto-generated from noiseDetail.xml )
*
* Adjusts the character and level of detail produced by the Perlin noise
* function. Similar to harmonics in physics, noise is computed over
* several octaves. Lower octaves contribute more to the output signal and
* as such define the overal intensity of the noise, whereas higher octaves
* create finer grained details in the noise sequence. By default, noise is
* computed over 4 octaves with each octave contributing exactly half than
* its predecessor, starting at 50% strength for the 1st octave. This
* falloff amount can be changed by adding an additional function
* parameter. Eg. a falloff factor of 0.75 means each octave will now have
* 75% impact (25% less) of the previous lower octave. Any value between
* 0.0 and 1.0 is valid, however note that values greater than 0.5 might
* result in greater than 1.0 values returned by <b>noise()</b>.<br /><br
* />By changing these parameters, the signal created by the <b>noise()</b>
* function can be adapted to fit very specific needs and characteristics.
*
* ( end auto-generated )
* @webref math:random
* @param lod number of octaves to be used by the noise
* @param falloff falloff factor for each octave
* @see PApplet#noise(float, float, float)
*/
public void noiseDetail(int lod) {
if (lod>0) perlin_octaves=lod;
}
/**
* @param falloff falloff factor for each octave
*/
public void noiseDetail(int lod, float falloff) {
if (lod>0) perlin_octaves=lod;
if (falloff>0) perlin_amp_falloff=falloff;
}
/**
* ( begin auto-generated from noiseSeed.xml )
*
* Sets the seed value for <b>noise()</b>. By default, <b>noise()</b>
* produces different results each time the program is run. Set the
* <b>value</b> parameter to a constant to return the same pseudo-random
* numbers each time the software is run.
*
* ( end auto-generated )
* @webref math:random
* @param seed seed value
* @see PApplet#noise(float, float, float)
* @see PApplet#noiseDetail(int, float)
* @see PApplet#random(float,float)
* @see PApplet#randomSeed(long)
*/
public void noiseSeed(long seed) {
if (perlinRandom == null) perlinRandom = new Random();
perlinRandom.setSeed(seed);
// force table reset after changing the random number seed [0122]
perlin = null;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
protected String[] loadImageFormats;
/**
* ( begin auto-generated from loadImage.xml )
*
* Loads an image into a variable of type <b>PImage</b>. Four types of
* images ( <b>.gif</b>, <b>.jpg</b>, <b>.tga</b>, <b>.png</b>) images may
* be loaded. To load correctly, images must be located in the data
* directory of the current sketch. In most cases, load all images in
* <b>setup()</b> to preload them at the start of the program. Loading
* images inside <b>draw()</b> will reduce the speed of a program.<br/>
* <br/> <b>filename</b> parameter can also be a URL to a file found
* online. For security reasons, a Processing sketch found online can only
* download files from the same server from which it came. Getting around
* this restriction requires a <a
* href="http://wiki.processing.org/w/Sign_an_Applet">signed
* applet</a>.<br/>
* <br/> <b>extension</b> parameter is used to determine the image type in
* cases where the image filename does not end with a proper extension.
* Specify the extension as the second parameter to <b>loadImage()</b>, as
* shown in the third example on this page.<br/>
* <br/> an image is not loaded successfully, the <b>null</b> value is
* returned and an error message will be printed to the console. The error
* message does not halt the program, however the null value may cause a
* NullPointerException if your code does not check whether the value
* returned from <b>loadImage()</b> is null.<br/>
* <br/> on the type of error, a <b>PImage</b> object may still be
* returned, but the width and height of the image will be set to -1. This
* happens if bad image data is returned or cannot be decoded properly.
* Sometimes this happens with image URLs that produce a 403 error or that
* redirect to a password prompt, because <b>loadImage()</b> will attempt
* to interpret the HTML as image data.
*
* ( end auto-generated )
*
* @webref image:loading_displaying
* @param filename name of file to load, can be .gif, .jpg, .tga, or a handful of other image types depending on your platform
* @see PImage#PImage
* @see PGraphics#image(PImage, float, float, float, float)
* @see PGraphics#imageMode(int)
* @see PGraphics#background(float, float, float, float)
*/
public PImage loadImage(String filename) {
// return loadImage(filename, null, null);
return loadImage(filename, null);
}
// /**
// * @param extension the type of image to load, for example "png", "gif", "jpg"
// */
// public PImage loadImage(String filename, String extension) {
// return loadImage(filename, extension, null);
// }
// /**
// * @nowebref
// */
// public PImage loadImage(String filename, Object params) {
// return loadImage(filename, null, params);
// }
/**
* @param extension type of image to load, for example "png", "gif", "jpg"
*/
public PImage loadImage(String filename, String extension) { //, Object params) {
if (extension == null) {
String lower = filename.toLowerCase();
int dot = filename.lastIndexOf('.');
if (dot == -1) {
extension = "unknown"; // no extension found
}
extension = lower.substring(dot + 1);
// check for, and strip any parameters on the url, i.e.
// filename.jpg?blah=blah&something=that
int question = extension.indexOf('?');
if (question != -1) {
extension = extension.substring(0, question);
}
}
// just in case. them users will try anything!
extension = extension.toLowerCase();
if (extension.equals("tga")) {
try {
PImage image = loadImageTGA(filename);
// if (params != null) {
// image.setParams(g, params);
// }
return image;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
if (extension.equals("tif") || extension.equals("tiff")) {
byte bytes[] = loadBytes(filename);
PImage image = (bytes == null) ? null : PImage.loadTIFF(bytes);
// if (params != null) {
// image.setParams(g, params);
// }
return image;
}
// For jpeg, gif, and png, load them using createImage(),
// because the javax.imageio code was found to be much slower.
// http://dev.processing.org/bugs/show_bug.cgi?id=392
try {
if (extension.equals("jpg") || extension.equals("jpeg") ||
extension.equals("gif") || extension.equals("png") ||
extension.equals("unknown")) {
byte bytes[] = loadBytes(filename);
if (bytes == null) {
return null;
} else {
Image awtImage = Toolkit.getDefaultToolkit().createImage(bytes);
PImage image = loadImageMT(awtImage);
if (image.width == -1) {
System.err.println("The file " + filename +
" contains bad image data, or may not be an image.");
}
// if it's a .gif image, test to see if it has transparency
if (extension.equals("gif") || extension.equals("png")) {
image.checkAlpha();
}
// if (params != null) {
// image.setParams(g, params);
// }
return image;
}
}
} catch (Exception e) {
// show error, but move on to the stuff below, see if it'll work
e.printStackTrace();
}
if (loadImageFormats == null) {
loadImageFormats = ImageIO.getReaderFormatNames();
}
if (loadImageFormats != null) {
for (int i = 0; i < loadImageFormats.length; i++) {
if (extension.equals(loadImageFormats[i])) {
return loadImageIO(filename);
// PImage image = loadImageIO(filename);
// if (params != null) {
// image.setParams(g, params);
// }
// return image;
}
}
}
// failed, could not load image after all those attempts
System.err.println("Could not find a method to load " + filename);
return null;
}
public PImage requestImage(String filename) {
// return requestImage(filename, null, null);
return requestImage(filename, null);
}
/**
* ( begin auto-generated from requestImage.xml )
*
* This function load images on a separate thread so that your sketch does
* not freeze while images load during <b>setup()</b>. While the image is
* loading, its width and height will be 0. If an error occurs while
* loading the image, its width and height will be set to -1. You'll know
* when the image has loaded properly because its width and height will be
* greater than 0. Asynchronous image loading (particularly when
* downloading from a server) can dramatically improve performance.<br />
* <br/> <b>extension</b> parameter is used to determine the image type in
* cases where the image filename does not end with a proper extension.
* Specify the extension as the second parameter to <b>requestImage()</b>.
*
* ( end auto-generated )
*
* @webref image:loading_displaying
* @param filename name of the file to load, can be .gif, .jpg, .tga, or a handful of other image types depending on your platform
* @param extension the type of image to load, for example "png", "gif", "jpg"
* @see PApplet#loadImage(String, String)
* @see PImage#PImage
*/
public PImage requestImage(String filename, String extension) {
PImage vessel = createImage(0, 0, ARGB);
AsyncImageLoader ail =
new AsyncImageLoader(filename, extension, vessel);
ail.start();
return vessel;
}
// /**
// * @nowebref
// */
// public PImage requestImage(String filename, String extension, Object params) {
// PImage vessel = createImage(0, 0, ARGB, params);
// AsyncImageLoader ail =
// new AsyncImageLoader(filename, extension, vessel);
// ail.start();
// return vessel;
// }
/**
* By trial and error, four image loading threads seem to work best when
* loading images from online. This is consistent with the number of open
* connections that web browsers will maintain. The variable is made public
* (however no accessor has been added since it's esoteric) if you really
* want to have control over the value used. For instance, when loading local
* files, it might be better to only have a single thread (or two) loading
* images so that you're disk isn't simply jumping around.
*/
public int requestImageMax = 4;
volatile int requestImageCount;
class AsyncImageLoader extends Thread {
String filename;
String extension;
PImage vessel;
public AsyncImageLoader(String filename, String extension, PImage vessel) {
this.filename = filename;
this.extension = extension;
this.vessel = vessel;
}
@Override
public void run() {
while (requestImageCount == requestImageMax) {
try {
Thread.sleep(10);
} catch (InterruptedException e) { }
}
requestImageCount++;
PImage actual = loadImage(filename, extension);
// An error message should have already printed
if (actual == null) {
vessel.width = -1;
vessel.height = -1;
} else {
vessel.width = actual.width;
vessel.height = actual.height;
vessel.format = actual.format;
vessel.pixels = actual.pixels;
}
requestImageCount--;
}
}
/**
* Load an AWT image synchronously by setting up a MediaTracker for
* a single image, and blocking until it has loaded.
*/
protected PImage loadImageMT(Image awtImage) {
MediaTracker tracker = new MediaTracker(this);
tracker.addImage(awtImage, 0);
try {
tracker.waitForAll();
} catch (InterruptedException e) {
//e.printStackTrace(); // non-fatal, right?
}
PImage image = new PImage(awtImage);
image.parent = this;
return image;
}
/**
* Use Java 1.4 ImageIO methods to load an image.
*/
protected PImage loadImageIO(String filename) {
InputStream stream = createInput(filename);
if (stream == null) {
System.err.println("The image " + filename + " could not be found.");
return null;
}
try {
BufferedImage bi = ImageIO.read(stream);
PImage outgoing = new PImage(bi.getWidth(), bi.getHeight());
outgoing.parent = this;
bi.getRGB(0, 0, outgoing.width, outgoing.height,
outgoing.pixels, 0, outgoing.width);
// check the alpha for this image
// was gonna call getType() on the image to see if RGB or ARGB,
// but it's not actually useful, since gif images will come through
// as TYPE_BYTE_INDEXED, which means it'll still have to check for
// the transparency. also, would have to iterate through all the other
// types and guess whether alpha was in there, so.. just gonna stick
// with the old method.
outgoing.checkAlpha();
// return the image
return outgoing;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Targa image loader for RLE-compressed TGA files.
* <p>
* Rewritten for 0115 to read/write RLE-encoded targa images.
* For 0125, non-RLE encoded images are now supported, along with
* images whose y-order is reversed (which is standard for TGA files).
*/
protected PImage loadImageTGA(String filename) throws IOException {
InputStream is = createInput(filename);
if (is == null) return null;
byte header[] = new byte[18];
int offset = 0;
do {
int count = is.read(header, offset, header.length - offset);
if (count == -1) return null;
offset += count;
} while (offset < 18);
/*
header[2] image type code
2 (0x02) - Uncompressed, RGB images.
3 (0x03) - Uncompressed, black and white images.
10 (0x0A) - Runlength encoded RGB images.
11 (0x0B) - Compressed, black and white images. (grayscale?)
header[16] is the bit depth (8, 24, 32)
header[17] image descriptor (packed bits)
0x20 is 32 = origin upper-left
0x28 is 32 + 8 = origin upper-left + 32 bits
7 6 5 4 3 2 1 0
128 64 32 16 8 4 2 1
*/
int format = 0;
if (((header[2] == 3) || (header[2] == 11)) && // B&W, plus RLE or not
(header[16] == 8) && // 8 bits
((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32 bit
format = ALPHA;
} else if (((header[2] == 2) || (header[2] == 10)) && // RGB, RLE or not
(header[16] == 24) && // 24 bits
((header[17] == 0x20) || (header[17] == 0))) { // origin
format = RGB;
} else if (((header[2] == 2) || (header[2] == 10)) &&
(header[16] == 32) &&
((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32
format = ARGB;
}
if (format == 0) {
System.err.println("Unknown .tga file format for " + filename);
//" (" + header[2] + " " +
//(header[16] & 0xff) + " " +
//hex(header[17], 2) + ")");
return null;
}
int w = ((header[13] & 0xff) << 8) + (header[12] & 0xff);
int h = ((header[15] & 0xff) << 8) + (header[14] & 0xff);
PImage outgoing = createImage(w, h, format);
// where "reversed" means upper-left corner (normal for most of
// the modernized world, but "reversed" for the tga spec)
boolean reversed = (header[17] & 0x20) != 0;
if ((header[2] == 2) || (header[2] == 3)) { // not RLE encoded
if (reversed) {
int index = (h-1) * w;
switch (format) {
case ALPHA:
for (int y = h-1; y >= 0; y--) {
for (int x = 0; x < w; x++) {
outgoing.pixels[index + x] = is.read();
}
index -= w;
}
break;
case RGB:
for (int y = h-1; y >= 0; y--) {
for (int x = 0; x < w; x++) {
outgoing.pixels[index + x] =
is.read() | (is.read() << 8) | (is.read() << 16) |
0xff000000;
}
index -= w;
}
break;
case ARGB:
for (int y = h-1; y >= 0; y--) {
for (int x = 0; x < w; x++) {
outgoing.pixels[index + x] =
is.read() | (is.read() << 8) | (is.read() << 16) |
(is.read() << 24);
}
index -= w;
}
}
} else { // not reversed
int count = w * h;
switch (format) {
case ALPHA:
for (int i = 0; i < count; i++) {
outgoing.pixels[i] = is.read();
}
break;
case RGB:
for (int i = 0; i < count; i++) {
outgoing.pixels[i] =
is.read() | (is.read() << 8) | (is.read() << 16) |
0xff000000;
}
break;
case ARGB:
for (int i = 0; i < count; i++) {
outgoing.pixels[i] =
is.read() | (is.read() << 8) | (is.read() << 16) |
(is.read() << 24);
}
break;
}
}
} else { // header[2] is 10 or 11
int index = 0;
int px[] = outgoing.pixels;
while (index < px.length) {
int num = is.read();
boolean isRLE = (num & 0x80) != 0;
if (isRLE) {
num -= 127; // (num & 0x7F) + 1
int pixel = 0;
switch (format) {
case ALPHA:
pixel = is.read();
break;
case RGB:
pixel = 0xFF000000 |
is.read() | (is.read() << 8) | (is.read() << 16);
//(is.read() << 16) | (is.read() << 8) | is.read();
break;
case ARGB:
pixel = is.read() |
(is.read() << 8) | (is.read() << 16) | (is.read() << 24);
break;
}
for (int i = 0; i < num; i++) {
px[index++] = pixel;
if (index == px.length) break;
}
} else { // write up to 127 bytes as uncompressed
num += 1;
switch (format) {
case ALPHA:
for (int i = 0; i < num; i++) {
px[index++] = is.read();
}
break;
case RGB:
for (int i = 0; i < num; i++) {
px[index++] = 0xFF000000 |
is.read() | (is.read() << 8) | (is.read() << 16);
//(is.read() << 16) | (is.read() << 8) | is.read();
}
break;
case ARGB:
for (int i = 0; i < num; i++) {
px[index++] = is.read() | //(is.read() << 24) |
(is.read() << 8) | (is.read() << 16) | (is.read() << 24);
//(is.read() << 16) | (is.read() << 8) | is.read();
}
break;
}
}
}
if (!reversed) {
int[] temp = new int[w];
for (int y = 0; y < h/2; y++) {
int z = (h-1) - y;
System.arraycopy(px, y*w, temp, 0, w);
System.arraycopy(px, z*w, px, y*w, w);
System.arraycopy(temp, 0, px, z*w, w);
}
}
}
return outgoing;
}
//////////////////////////////////////////////////////////////
// DATA I/O
/**
* @webref input:files
* @brief Creates a new XML object
* @param name the name to be given to the root element of the new XML object
* @return an XML object, or null
* @see PApplet#loadXML(String)
* @see PApplet#parseXML(String)
*/
public XML createXML(String name) {
try {
return new XML(name);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* @webref input:files
* @param filename name of a file in the data folder or a URL.
* @see PApplet#createXML(String)
* @see PApplet#parseXML(String)
* @see PApplet#saveXML(String)
* @see PApplet#loadBytes(String)
* @see PApplet#loadStrings(String)
* @see PApplet#loadTable(String)
*/
public XML loadXML(String filename) {
return loadXML(filename, null);
}
// version that uses 'options' though there are currently no supported options
public XML loadXML(String filename, String options) {
try {
return new XML(createInput(filename), options);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* @webref input:files
* @brief Converts String content to an XML object
* @param data the content to be parsed as XML
* @return an XML object, or null
* @see PApplet#createXML(String)
* @see PApplet#loadXML(String)
* @see PApplet#saveXML(String)
*/
public XML parseXML(String xmlString) {
return parseXML(xmlString, null);
}
public XML parseXML(String xmlString, String options) {
try {
return XML.parse(xmlString, options);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* @webref output:files
* @param xml the XML object to save to disk
* @param filename name of the file to write to
* @see PApplet#createXML(String)
* @see PApplet#loadXML(String)
* @see PApplet#parseXML(String)
*/
public boolean saveXML(XML xml, String filename) {
return saveXML(xml, filename, null);
}
public boolean saveXML(XML xml, String filename, String options) {
return xml.save(saveFile(filename), options);
}
/**
* @webref input:files
* @see PApplet#loadTable(String)
* @see PApplet#saveTable(Table, String)
*/
public Table createTable() {
return new Table();
}
/**
* @webref input:files
* @param filename name of a file in the data folder or a URL.
* @see PApplet#createTable()
* @see PApplet#saveTable(Table, String)
* @see PApplet#loadBytes(String)
* @see PApplet#loadStrings(String)
* @see PApplet#loadXML(String)
*/
public Table loadTable(String filename) {
return loadTable(filename, null);
}
/**
* @param options may contain "header", "tsv", or "csv" separated by commas
*/
public Table loadTable(String filename, String options) {
try {
String ext = checkExtension(filename);
if (ext != null) {
if (ext.equals("csv") || ext.equals("tsv") || ext.equals("bin")) {
if (options == null) {
options = ext;
} else {
options = ext + "," + options;
}
}
}
return new Table(createInput(filename), options);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* @webref input:files
* @param table the Table object to save to a file
* @param filename the filename to which the Table should be saved
* @see PApplet#createTable()
* @see PApplet#loadTable(String)
*/
public boolean saveTable(Table table, String filename) {
return saveTable(table, filename, null);
}
/**
* @param options may contain "header", "tsv", or "csv" separated by commas
*/
public boolean saveTable(Table table, String filename, String options) {
try {
table.save(saveFile(filename), options);
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
protected String checkExtension(String filename) {
int index = filename.lastIndexOf('.');
if (index == -1) {
return null;
}
return filename.substring(index + 1).toLowerCase();
}
//////////////////////////////////////////////////////////////
// FONT I/O
/**
* ( begin auto-generated from loadFont.xml )
*
* Loads a font into a variable of type <b>PFont</b>. To load correctly,
* fonts must be located in the data directory of the current sketch. To
* create a font to use with Processing, select "Create Font..." from the
* Tools menu. This will create a font in the format Processing requires
* and also adds it to the current sketch's data directory.<br />
* <br />
* Like <b>loadImage()</b> and other functions that load data, the
* <b>loadFont()</b> function should not be used inside <b>draw()</b>,
* because it will slow down the sketch considerably, as the font will be
* re-loaded from the disk (or network) on each frame.<br />
* <br />
* For most renderers, Processing displays fonts using the .vlw font
* format, which uses images for each letter, rather than defining them
* through vector data. When <b>hint(ENABLE_NATIVE_FONTS)</b> is used with
* the JAVA2D renderer, the native version of a font will be used if it is
* installed on the user's machine.<br />
* <br />
* Using <b>createFont()</b> (instead of loadFont) enables vector data to
* be used with the JAVA2D (default) renderer setting. This can be helpful
* when many font sizes are needed, or when using any renderer based on
* JAVA2D, such as the PDF library.
*
* ( end auto-generated )
* @webref typography:loading_displaying
* @param filename name of the font to load
* @see PFont#PFont(Font, boolean)
* @see PGraphics#textFont(PFont, float)
* @see PApplet#createFont(String, float, boolean, char[])
*/
public PFont loadFont(String filename) {
try {
InputStream input = createInput(filename);
return new PFont(input);
} catch (Exception e) {
die("Could not load font " + filename + ". " +
"Make sure that the font has been copied " +
"to the data folder of your sketch.", e);
}
return null;
}
/**
* Used by PGraphics to remove the requirement for loading a font!
*/
protected PFont createDefaultFont(float size) {
// Font f = new Font("SansSerif", Font.PLAIN, 12);
// println("n: " + f.getName());
// println("fn: " + f.getFontName());
// println("ps: " + f.getPSName());
return createFont("Lucida Sans", size, true, null);
}
public PFont createFont(String name, float size) {
return createFont(name, size, true, null);
}
public PFont createFont(String name, float size, boolean smooth) {
return createFont(name, size, smooth, null);
}
/**
* ( begin auto-generated from createFont.xml )
*
* Dynamically converts a font to the format used by Processing from either
* a font name that's installed on the computer, or from a .ttf or .otf
* file inside the sketches "data" folder. This function is an advanced
* feature for precise control. On most occasions you should create fonts
* through selecting "Create Font..." from the Tools menu.
* <br /><br />
* Use the <b>PFont.list()</b> method to first determine the names for the
* fonts recognized by the computer and are compatible with this function.
* Because of limitations in Java, not all fonts can be used and some might
* work with one operating system and not others. When sharing a sketch
* with other people or posting it on the web, you may need to include a
* .ttf or .otf version of your font in the data directory of the sketch
* because other people might not have the font installed on their
* computer. Only fonts that can legally be distributed should be included
* with a sketch.
* <br /><br />
* The <b>size</b> parameter states the font size you want to generate. The
* <b>smooth</b> parameter specifies if the font should be antialiased or
* not, and the <b>charset</b> parameter is an array of chars that
* specifies the characters to generate.
* <br /><br />
* This function creates a bitmapped version of a font in the same manner
* as the Create Font tool. It loads a font by name, and converts it to a
* series of images based on the size of the font. When possible, the
* <b>text()</b> function will use a native font rather than the bitmapped
* version created behind the scenes with <b>createFont()</b>. For
* instance, when using P2D, the actual native version of the font will be
* employed by the sketch, improving drawing quality and performance. With
* the P3D renderer, the bitmapped version will be used. While this can
* drastically improve speed and appearance, results are poor when
* exporting if the sketch does not include the .otf or .ttf file, and the
* requested font is not available on the machine running the sketch.
*
* ( end auto-generated )
* @webref typography:loading_displaying
* @param name name of the font to load
* @param size point size of the font
* @param smooth true for an antialiased font, false for aliased
* @param charset array containing characters to be generated
* @see PFont#PFont
* @see PGraphics#textFont(PFont, float)
* @see PGraphics#text(String, float, float, float, float, float)
* @see PApplet#loadFont(String)
*/
public PFont createFont(String name, float size,
boolean smooth, char charset[]) {
String lowerName = name.toLowerCase();
Font baseFont = null;
try {
InputStream stream = null;
if (lowerName.endsWith(".otf") || lowerName.endsWith(".ttf")) {
stream = createInput(name);
if (stream == null) {
System.err.println("The font \"" + name + "\" " +
"is missing or inaccessible, make sure " +
"the URL is valid or that the file has been " +
"added to your sketch and is readable.");
return null;
}
baseFont = Font.createFont(Font.TRUETYPE_FONT, createInput(name));
} else {
baseFont = PFont.findFont(name);
}
return new PFont(baseFont.deriveFont(size), smooth, charset,
stream != null);
} catch (Exception e) {
System.err.println("Problem createFont(" + name + ")");
e.printStackTrace();
return null;
}
}
//////////////////////////////////////////////////////////////
// FILE/FOLDER SELECTION
private Frame selectFrame;
private Frame selectFrame() {
if (frame != null) {
selectFrame = frame;
} else if (selectFrame == null) {
Component comp = getParent();
while (comp != null) {
if (comp instanceof Frame) {
selectFrame = (Frame) comp;
break;
}
comp = comp.getParent();
}
// Who you callin' a hack?
if (selectFrame == null) {
selectFrame = new Frame();
}
}
return selectFrame;
}
/**
* Open a platform-specific file chooser dialog to select a file for input.
* After the selection is made, the selected File will be passed to the
* 'callback' function. If the dialog is closed or canceled, null will be
* sent to the function, so that the program is not waiting for additional
* input. The callback is necessary because of how threading works.
*
* <pre>
* void setup() {
* selectInput("Select a file to process:", "fileSelected");
* }
*
* void fileSelected(File selection) {
* if (selection == null) {
* println("Window was closed or the user hit cancel.");
* } else {
* println("User selected " + fileSeleted.getAbsolutePath());
* }
* }
* </pre>
*
* For advanced users, the method must be 'public', which is true for all
* methods inside a sketch when run from the PDE, but must explicitly be
* set when using Eclipse or other development environments.
*
* @webref input:files
* @param prompt message to the user
* @param callback name of the method to be called when the selection is made
*/
public void selectInput(String prompt, String callback) {
selectInput(prompt, callback, null);
}
public void selectInput(String prompt, String callback, File file) {
selectInput(prompt, callback, file, this);
}
public void selectInput(String prompt, String callback,
File file, Object callbackObject) {
selectInput(prompt, callback, file, callbackObject, selectFrame());
}
static public void selectInput(String prompt, String callbackMethod,
File file, Object callbackObject, Frame parent) {
selectImpl(prompt, callbackMethod, file, callbackObject, parent, FileDialog.LOAD);
}
/**
* See selectInput() for details.
*
* @webref output:files
* @param prompt message to the user
* @param callback name of the method to be called when the selection is made
*/
public void selectOutput(String prompt, String callback) {
selectOutput(prompt, callback, null);
}
public void selectOutput(String prompt, String callback, File file) {
selectOutput(prompt, callback, file, this);
}
public void selectOutput(String prompt, String callback,
File file, Object callbackObject) {
selectOutput(prompt, callback, file, callbackObject, selectFrame());
}
static public void selectOutput(String prompt, String callbackMethod,
File file, Object callbackObject, Frame parent) {
selectImpl(prompt, callbackMethod, file, callbackObject, parent, FileDialog.SAVE);
}
static protected void selectImpl(final String prompt,
final String callbackMethod,
final File defaultSelection,
final Object callbackObject,
final Frame parentFrame,
final int mode) {
EventQueue.invokeLater(new Runnable() {
public void run() {
File selectedFile = null;
if (useNativeSelect) {
FileDialog dialog = new FileDialog(parentFrame, prompt, mode);
if (defaultSelection != null) {
dialog.setDirectory(defaultSelection.getParent());
dialog.setFile(defaultSelection.getName());
}
dialog.setVisible(true);
String directory = dialog.getDirectory();
String filename = dialog.getFile();
if (filename != null) {
selectedFile = new File(directory, filename);
}
} else {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle(prompt);
if (defaultSelection != null) {
chooser.setSelectedFile(defaultSelection);
}
int result = -1;
if (mode == FileDialog.SAVE) {
result = chooser.showSaveDialog(parentFrame);
} else if (mode == FileDialog.LOAD) {
result = chooser.showOpenDialog(parentFrame);
}
if (result == JFileChooser.APPROVE_OPTION) {
selectedFile = chooser.getSelectedFile();
}
}
selectCallback(selectedFile, callbackMethod, callbackObject);
}
});
}
/**
* See selectInput() for details.
*
* @webref input:files
* @param prompt message to the user
* @param callback name of the method to be called when the selection is made
*/
public void selectFolder(String prompt, String callback) {
selectFolder(prompt, callback, null);
}
public void selectFolder(String prompt, String callback, File file) {
selectFolder(prompt, callback, file, this);
}
public void selectFolder(String prompt, String callback,
File file, Object callbackObject) {
selectFolder(prompt, callback, file, callbackObject, selectFrame());
}
static public void selectFolder(final String prompt,
final String callbackMethod,
final File defaultSelection,
final Object callbackObject,
final Frame parentFrame) {
EventQueue.invokeLater(new Runnable() {
public void run() {
File selectedFile = null;
if (platform == MACOSX && useNativeSelect != false) {
FileDialog fileDialog =
new FileDialog(parentFrame, prompt, FileDialog.LOAD);
System.setProperty("apple.awt.fileDialogForDirectories", "true");
fileDialog.setVisible(true);
System.setProperty("apple.awt.fileDialogForDirectories", "false");
String filename = fileDialog.getFile();
if (filename != null) {
selectedFile = new File(fileDialog.getDirectory(), fileDialog.getFile());
}
} else {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle(prompt);
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (defaultSelection != null) {
fileChooser.setSelectedFile(defaultSelection);
}
int result = fileChooser.showOpenDialog(parentFrame);
if (result == JFileChooser.APPROVE_OPTION) {
selectedFile = fileChooser.getSelectedFile();
}
}
selectCallback(selectedFile, callbackMethod, callbackObject);
}
});
}
static private void selectCallback(File selectedFile,
String callbackMethod,
Object callbackObject) {
try {
Class<?> callbackClass = callbackObject.getClass();
Method selectMethod =
callbackClass.getMethod(callbackMethod, new Class[] { File.class });
selectMethod.invoke(callbackObject, new Object[] { selectedFile });
} catch (IllegalAccessException iae) {
System.err.println(callbackMethod + "() must be public");
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (NoSuchMethodException nsme) {
System.err.println(callbackMethod + "() could not be found");
}
}
//////////////////////////////////////////////////////////////
// READERS AND WRITERS
/**
* ( begin auto-generated from createReader.xml )
*
* Creates a <b>BufferedReader</b> object that can be used to read files
* line-by-line as individual <b>String</b> objects. This is the complement
* to the <b>createWriter()</b> function.
* <br/> <br/>
* Starting with Processing release 0134, all files loaded and saved by the
* Processing API use UTF-8 encoding. In previous releases, the default
* encoding for your platform was used, which causes problems when files
* are moved to other platforms.
*
* ( end auto-generated )
* @webref input:files
* @param filename name of the file to be opened
* @see BufferedReader
* @see PApplet#createWriter(String)
* @see PrintWriter
*/
public BufferedReader createReader(String filename) {
try {
InputStream is = createInput(filename);
if (is == null) {
System.err.println(filename + " does not exist or could not be read");
return null;
}
return createReader(is);
} catch (Exception e) {
if (filename == null) {
System.err.println("Filename passed to reader() was null");
} else {
System.err.println("Couldn't create a reader for " + filename);
}
}
return null;
}
/**
* @nowebref
*/
static public BufferedReader createReader(File file) {
try {
InputStream is = new FileInputStream(file);
if (file.getName().toLowerCase().endsWith(".gz")) {
is = new GZIPInputStream(is);
}
return createReader(is);
} catch (Exception e) {
if (file == null) {
throw new RuntimeException("File passed to createReader() was null");
} else {
e.printStackTrace();
throw new RuntimeException("Couldn't create a reader for " +
file.getAbsolutePath());
}
}
//return null;
}
/**
* @nowebref
* I want to read lines from a stream. If I have to type the
* following lines any more I'm gonna send Sun my medical bills.
*/
static public BufferedReader createReader(InputStream input) {
InputStreamReader isr = null;
try {
isr = new InputStreamReader(input, "UTF-8");
} catch (UnsupportedEncodingException e) { } // not gonna happen
return new BufferedReader(isr);
}
/**
* ( begin auto-generated from createWriter.xml )
*
* Creates a new file in the sketch folder, and a <b>PrintWriter</b> object
* to write to it. For the file to be made correctly, it should be flushed
* and must be closed with its <b>flush()</b> and <b>close()</b> methods
* (see above example).
* <br/> <br/>
* Starting with Processing release 0134, all files loaded and saved by the
* Processing API use UTF-8 encoding. In previous releases, the default
* encoding for your platform was used, which causes problems when files
* are moved to other platforms.
*
* ( end auto-generated )
*
* @webref output:files
* @param filename name of the file to be created
* @see PrintWriter
* @see PApplet#createReader
* @see BufferedReader
*/
public PrintWriter createWriter(String filename) {
return createWriter(saveFile(filename));
}
/**
* @nowebref
* I want to print lines to a file. I have RSI from typing these
* eight lines of code so many times.
*/
static public PrintWriter createWriter(File file) {
try {
createPath(file); // make sure in-between folders exist
OutputStream output = new FileOutputStream(file);
if (file.getName().toLowerCase().endsWith(".gz")) {
output = new GZIPOutputStream(output);
}
return createWriter(output);
} catch (Exception e) {
if (file == null) {
throw new RuntimeException("File passed to createWriter() was null");
} else {
e.printStackTrace();
throw new RuntimeException("Couldn't create a writer for " +
file.getAbsolutePath());
}
}
//return null;
}
/**
* @nowebref
* I want to print lines to a file. Why am I always explaining myself?
* It's the JavaSoft API engineers who need to explain themselves.
*/
static public PrintWriter createWriter(OutputStream output) {
try {
BufferedOutputStream bos = new BufferedOutputStream(output, 8192);
OutputStreamWriter osw = new OutputStreamWriter(bos, "UTF-8");
return new PrintWriter(osw);
} catch (UnsupportedEncodingException e) { } // not gonna happen
return null;
}
//////////////////////////////////////////////////////////////
// FILE INPUT
/**
* @deprecated As of release 0136, use createInput() instead.
*/
public InputStream openStream(String filename) {
return createInput(filename);
}
/**
* ( begin auto-generated from createInput.xml )
*
* This is a function for advanced programmers to open a Java InputStream.
* It's useful if you want to use the facilities provided by PApplet to
* easily open files from the data folder or from a URL, but want an
* InputStream object so that you can use other parts of Java to take more
* control of how the stream is read.<br />
* <br />
* The filename passed in can be:<br />
* - A URL, for instance <b>openStream("http://processing.org/")</b><br />
* - A file in the sketch's <b>data</b> folder<br />
* - The full path to a file to be opened locally (when running as an
* application)<br />
* <br />
* If the requested item doesn't exist, null is returned. If not online,
* this will also check to see if the user is asking for a file whose name
* isn't properly capitalized. If capitalization is different, an error
* will be printed to the console. This helps prevent issues that appear
* when a sketch is exported to the web, where case sensitivity matters, as
* opposed to running from inside the Processing Development Environment on
* Windows or Mac OS, where case sensitivity is preserved but ignored.<br />
* <br />
* If the file ends with <b>.gz</b>, the stream will automatically be gzip
* decompressed. If you don't want the automatic decompression, use the
* related function <b>createInputRaw()</b>.
* <br />
* In earlier releases, this function was called <b>openStream()</b>.<br />
* <br />
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Simplified method to open a Java InputStream.
* <p>
* This method is useful if you want to use the facilities provided
* by PApplet to easily open things from the data folder or from a URL,
* but want an InputStream object so that you can use other Java
* methods to take more control of how the stream is read.
* <p>
* If the requested item doesn't exist, null is returned.
* (Prior to 0096, die() would be called, killing the applet)
* <p>
* For 0096+, the "data" folder is exported intact with subfolders,
* and openStream() properly handles subdirectories from the data folder
* <p>
* If not online, this will also check to see if the user is asking
* for a file whose name isn't properly capitalized. This helps prevent
* issues when a sketch is exported to the web, where case sensitivity
* matters, as opposed to Windows and the Mac OS default where
* case sensitivity is preserved but ignored.
* <p>
* It is strongly recommended that libraries use this method to open
* data files, so that the loading sequence is handled in the same way
* as functions like loadBytes(), loadImage(), etc.
* <p>
* The filename passed in can be:
* <UL>
* <LI>A URL, for instance openStream("http://processing.org/");
* <LI>A file in the sketch's data folder
* <LI>Another file to be opened locally (when running as an application)
* </UL>
*
* @webref input:files
* @param filename the name of the file to use as input
* @see PApplet#createOutput(String)
* @see PApplet#selectOutput(String)
* @see PApplet#selectInput(String)
*
*/
public InputStream createInput(String filename) {
InputStream input = createInputRaw(filename);
if ((input != null) && filename.toLowerCase().endsWith(".gz")) {
try {
return new GZIPInputStream(input);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
return input;
}
/**
* Call openStream() without automatic gzip decompression.
*/
public InputStream createInputRaw(String filename) {
InputStream stream = null;
if (filename == null) return null;
if (filename.length() == 0) {
// an error will be called by the parent function
//System.err.println("The filename passed to openStream() was empty.");
return null;
}
// safe to check for this as a url first. this will prevent online
// access logs from being spammed with GET /sketchfolder/http://blahblah
if (filename.contains(":")) { // at least smells like URL
try {
URL url = new URL(filename);
stream = url.openStream();
return stream;
} catch (MalformedURLException mfue) {
// not a url, that's fine
} catch (FileNotFoundException fnfe) {
// Java 1.5 likes to throw this when URL not available. (fix for 0119)
// http://dev.processing.org/bugs/show_bug.cgi?id=403
} catch (IOException e) {
// changed for 0117, shouldn't be throwing exception
e.printStackTrace();
//System.err.println("Error downloading from URL " + filename);
return null;
//throw new RuntimeException("Error downloading from URL " + filename);
}
}
// Moved this earlier than the getResourceAsStream() checks, because
// calling getResourceAsStream() on a directory lists its contents.
// http://dev.processing.org/bugs/show_bug.cgi?id=716
try {
// First see if it's in a data folder. This may fail by throwing
// a SecurityException. If so, this whole block will be skipped.
File file = new File(dataPath(filename));
if (!file.exists()) {
// next see if it's just in the sketch folder
file = new File(sketchPath, filename);
}
if (file.isDirectory()) {
return null;
}
if (file.exists()) {
try {
// handle case sensitivity check
String filePath = file.getCanonicalPath();
String filenameActual = new File(filePath).getName();
// make sure there isn't a subfolder prepended to the name
String filenameShort = new File(filename).getName();
// if the actual filename is the same, but capitalized
// differently, warn the user.
//if (filenameActual.equalsIgnoreCase(filenameShort) &&
//!filenameActual.equals(filenameShort)) {
if (!filenameActual.equals(filenameShort)) {
throw new RuntimeException("This file is named " +
filenameActual + " not " +
filename + ". Rename the file " +
"or change your code.");
}
} catch (IOException e) { }
}
// if this file is ok, may as well just load it
stream = new FileInputStream(file);
if (stream != null) return stream;
// have to break these out because a general Exception might
// catch the RuntimeException being thrown above
} catch (IOException ioe) {
} catch (SecurityException se) { }
// Using getClassLoader() prevents java from converting dots
// to slashes or requiring a slash at the beginning.
// (a slash as a prefix means that it'll load from the root of
// the jar, rather than trying to dig into the package location)
ClassLoader cl = getClass().getClassLoader();
// by default, data files are exported to the root path of the jar.
// (not the data folder) so check there first.
stream = cl.getResourceAsStream("data/" + filename);
if (stream != null) {
String cn = stream.getClass().getName();
// this is an irritation of sun's java plug-in, which will return
// a non-null stream for an object that doesn't exist. like all good
// things, this is probably introduced in java 1.5. awesome!
// http://dev.processing.org/bugs/show_bug.cgi?id=359
if (!cn.equals("sun.plugin.cache.EmptyInputStream")) {
return stream;
}
}
// When used with an online script, also need to check without the
// data folder, in case it's not in a subfolder called 'data'.
// http://dev.processing.org/bugs/show_bug.cgi?id=389
stream = cl.getResourceAsStream(filename);
if (stream != null) {
String cn = stream.getClass().getName();
if (!cn.equals("sun.plugin.cache.EmptyInputStream")) {
return stream;
}
}
// Finally, something special for the Internet Explorer users. Turns out
// that we can't get files that are part of the same folder using the
// methods above when using IE, so we have to resort to the old skool
// getDocumentBase() from teh applet dayz. 1996, my brotha.
try {
URL base = getDocumentBase();
if (base != null) {
URL url = new URL(base, filename);
URLConnection conn = url.openConnection();
return conn.getInputStream();
// if (conn instanceof HttpURLConnection) {
// HttpURLConnection httpConnection = (HttpURLConnection) conn;
// // test for 401 result (HTTP only)
// int responseCode = httpConnection.getResponseCode();
// }
}
} catch (Exception e) { } // IO or NPE or...
// Now try it with a 'data' subfolder. getting kinda desperate for data...
try {
URL base = getDocumentBase();
if (base != null) {
URL url = new URL(base, "data/" + filename);
URLConnection conn = url.openConnection();
return conn.getInputStream();
}
} catch (Exception e) { }
try {
// attempt to load from a local file, used when running as
// an application, or as a signed applet
try { // first try to catch any security exceptions
try {
stream = new FileInputStream(dataPath(filename));
if (stream != null) return stream;
} catch (IOException e2) { }
try {
stream = new FileInputStream(sketchPath(filename));
if (stream != null) return stream;
} catch (Exception e) { } // ignored
try {
stream = new FileInputStream(filename);
if (stream != null) return stream;
} catch (IOException e1) { }
} catch (SecurityException se) { } // online, whups
} catch (Exception e) {
//die(e.getMessage(), e);
e.printStackTrace();
}
return null;
}
/**
* @nowebref
*/
static public InputStream createInput(File file) {
if (file == null) {
throw new IllegalArgumentException("File passed to createInput() was null");
}
try {
InputStream input = new FileInputStream(file);
if (file.getName().toLowerCase().endsWith(".gz")) {
return new GZIPInputStream(input);
}
return input;
} catch (IOException e) {
System.err.println("Could not createInput() for " + file);
e.printStackTrace();
return null;
}
}
/**
* ( begin auto-generated from loadBytes.xml )
*
* Reads the contents of a file or url and places it in a byte array. If a
* file is specified, it must be located in the sketch's "data"
* directory/folder.<br />
* <br />
* The filename parameter can also be a URL to a file found online. For
* security reasons, a Processing sketch found online can only download
* files from the same server from which it came. Getting around this
* restriction requires a <a
* href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</a>.
*
* ( end auto-generated )
* @webref input:files
* @param filename name of a file in the data folder or a URL.
* @see PApplet#loadStrings(String)
* @see PApplet#saveStrings(String, String[])
* @see PApplet#saveBytes(String, byte[])
*
*/
public byte[] loadBytes(String filename) {
InputStream is = createInput(filename);
- if (is != null) return loadBytes(is);
+ if (is != null) {
+ byte[] outgoing = loadBytes(is);
+ try {
+ is.close();
+ } catch (IOException e) {
+ e.printStackTrace(); // shouldn't happen
+ }
+ return outgoing;
+ }
System.err.println("The file \"" + filename + "\" " +
"is missing or inaccessible, make sure " +
"the URL is valid or that the file has been " +
"added to your sketch and is readable.");
return null;
}
/**
* @nowebref
*/
static public byte[] loadBytes(InputStream input) {
try {
BufferedInputStream bis = new BufferedInputStream(input);
ByteArrayOutputStream out = new ByteArrayOutputStream();
int c = bis.read();
while (c != -1) {
out.write(c);
c = bis.read();
}
return out.toByteArray();
} catch (IOException e) {
e.printStackTrace();
//throw new RuntimeException("Couldn't load bytes from stream");
}
return null;
}
/**
* @nowebref
*/
static public byte[] loadBytes(File file) {
InputStream is = createInput(file);
return loadBytes(is);
}
/**
* @nowebref
*/
static public String[] loadStrings(File file) {
InputStream is = createInput(file);
- if (is != null) return loadStrings(is);
+ if (is != null) {
+ String[] outgoing = loadStrings(is);
+ try {
+ is.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ return outgoing;
+ }
return null;
}
/**
* ( begin auto-generated from loadStrings.xml )
*
* Reads the contents of a file or url and creates a String array of its
* individual lines. If a file is specified, it must be located in the
* sketch's "data" directory/folder.<br />
* <br />
* The filename parameter can also be a URL to a file found online. For
* security reasons, a Processing sketch found online can only download
* files from the same server from which it came. Getting around this
* restriction requires a <a
* href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</a>.
* <br />
* If the file is not available or an error occurs, <b>null</b> will be
* returned and an error message will be printed to the console. The error
* message does not halt the program, however the null value may cause a
* NullPointerException if your code does not check whether the value
* returned is null.
* <br/> <br/>
* Starting with Processing release 0134, all files loaded and saved by the
* Processing API use UTF-8 encoding. In previous releases, the default
* encoding for your platform was used, which causes problems when files
* are moved to other platforms.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Load data from a file and shove it into a String array.
* <p>
* Exceptions are handled internally, when an error, occurs, an
* exception is printed to the console and 'null' is returned,
* but the program continues running. This is a tradeoff between
* 1) showing the user that there was a problem but 2) not requiring
* that all i/o code is contained in try/catch blocks, for the sake
* of new users (or people who are just trying to get things done
* in a "scripting" fashion. If you want to handle exceptions,
* use Java methods for I/O.
*
* @webref input:files
* @param filename name of the file or url to load
* @see PApplet#loadBytes(String)
* @see PApplet#saveStrings(String, String[])
* @see PApplet#saveBytes(String, byte[])
*/
public String[] loadStrings(String filename) {
InputStream is = createInput(filename);
if (is != null) return loadStrings(is);
System.err.println("The file \"" + filename + "\" " +
"is missing or inaccessible, make sure " +
"the URL is valid or that the file has been " +
"added to your sketch and is readable.");
return null;
}
/**
* @nowebref
*/
static public String[] loadStrings(InputStream input) {
try {
BufferedReader reader =
new BufferedReader(new InputStreamReader(input, "UTF-8"));
return loadStrings(reader);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
static public String[] loadStrings(BufferedReader reader) {
try {
String lines[] = new String[100];
int lineCount = 0;
String line = null;
while ((line = reader.readLine()) != null) {
if (lineCount == lines.length) {
String temp[] = new String[lineCount << 1];
System.arraycopy(lines, 0, temp, 0, lineCount);
lines = temp;
}
lines[lineCount++] = line;
}
reader.close();
if (lineCount == lines.length) {
return lines;
}
// resize array to appropriate amount for these lines
String output[] = new String[lineCount];
System.arraycopy(lines, 0, output, 0, lineCount);
return output;
} catch (IOException e) {
e.printStackTrace();
//throw new RuntimeException("Error inside loadStrings()");
}
return null;
}
//////////////////////////////////////////////////////////////
// FILE OUTPUT
/**
* ( begin auto-generated from createOutput.xml )
*
* Similar to <b>createInput()</b>, this creates a Java <b>OutputStream</b>
* for a given filename or path. The file will be created in the sketch
* folder, or in the same folder as an exported application.
* <br /><br />
* If the path does not exist, intermediate folders will be created. If an
* exception occurs, it will be printed to the console, and <b>null</b>
* will be returned.
* <br /><br />
* This function is a convenience over the Java approach that requires you
* to 1) create a FileOutputStream object, 2) determine the exact file
* location, and 3) handle exceptions. Exceptions are handled internally by
* the function, which is more appropriate for "sketch" projects.
* <br /><br />
* If the output filename ends with <b>.gz</b>, the output will be
* automatically GZIP compressed as it is written.
*
* ( end auto-generated )
* @webref output:files
* @param filename name of the file to open
* @see PApplet#createInput(String)
* @see PApplet#selectOutput()
*/
public OutputStream createOutput(String filename) {
return createOutput(saveFile(filename));
}
/**
* @nowebref
*/
static public OutputStream createOutput(File file) {
try {
createPath(file); // make sure the path exists
FileOutputStream fos = new FileOutputStream(file);
if (file.getName().toLowerCase().endsWith(".gz")) {
return new GZIPOutputStream(fos);
}
return fos;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* ( begin auto-generated from saveStream.xml )
*
* Save the contents of a stream to a file in the sketch folder. This is
* basically <b>saveBytes(blah, loadBytes())</b>, but done more efficiently
* (and with less confusing syntax).<br />
* <br />
* When using the <b>targetFile</b> parameter, it writes to a <b>File</b>
* object for greater control over the file location. (Note that unlike
* some other functions, this will not automatically compress or uncompress
* gzip files.)
*
* ( end auto-generated )
*
* @webref output:files
* @param target name of the file to write to
* @param source location to read from (a filename, path, or URL)
* @see PApplet#createOutput(String)
*/
public boolean saveStream(String target, String source) {
return saveStream(saveFile(target), source);
}
/**
* Identical to the other saveStream(), but writes to a File
* object, for greater control over the file location.
* <p/>
* Note that unlike other api methods, this will not automatically
* compress or uncompress gzip files.
*/
public boolean saveStream(File target, String source) {
return saveStream(target, createInputRaw(source));
}
/**
* @nowebref
*/
public boolean saveStream(String target, InputStream source) {
return saveStream(saveFile(target), source);
}
/**
* @nowebref
*/
static public boolean saveStream(File target, InputStream source) {
File tempFile = null;
try {
File parentDir = target.getParentFile();
// make sure that this path actually exists before writing
createPath(target);
tempFile = File.createTempFile(target.getName(), null, parentDir);
FileOutputStream targetStream = new FileOutputStream(tempFile);
saveStream(targetStream, source);
targetStream.close();
targetStream = null;
if (target.exists()) {
if (!target.delete()) {
System.err.println("Could not replace " +
target.getAbsolutePath() + ".");
}
}
if (!tempFile.renameTo(target)) {
System.err.println("Could not rename temporary file " +
tempFile.getAbsolutePath());
return false;
}
return true;
} catch (IOException e) {
if (tempFile != null) {
tempFile.delete();
}
e.printStackTrace();
return false;
}
}
/**
* @nowebref
*/
static public void saveStream(OutputStream target,
InputStream source) throws IOException {
BufferedInputStream bis = new BufferedInputStream(source, 16384);
BufferedOutputStream bos = new BufferedOutputStream(target);
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = bis.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.flush();
}
/**
* ( begin auto-generated from saveBytes.xml )
*
* Opposite of <b>loadBytes()</b>, will write an entire array of bytes to a
* file. The data is saved in binary format. This file is saved to the
* sketch's folder, which is opened by selecting "Show sketch folder" from
* the "Sketch" menu.<br />
* <br />
* It is not possible to use saveXxxxx() functions inside a web browser
* unless the sketch is <a
* href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</A>. To
* save a file back to a server, see the <a
* href="http://wiki.processing.org/w/Saving_files_to_a_web-server">save to
* web</A> code snippet on the Processing Wiki.
*
* ( end auto-generated )
*
* @webref output:files
* @param filename name of the file to write to
* @param data array of bytes to be written
* @see PApplet#loadStrings(String)
* @see PApplet#loadBytes(String)
* @see PApplet#saveStrings(String, String[])
*/
public void saveBytes(String filename, byte[] data) {
saveBytes(saveFile(filename), data);
}
/**
* @nowebref
* Saves bytes to a specific File location specified by the user.
*/
static public void saveBytes(File file, byte[] data) {
File tempFile = null;
try {
File parentDir = file.getParentFile();
tempFile = File.createTempFile(file.getName(), null, parentDir);
OutputStream output = createOutput(tempFile);
saveBytes(output, data);
output.close();
output = null;
if (file.exists()) {
if (!file.delete()) {
System.err.println("Could not replace " + file.getAbsolutePath());
}
}
if (!tempFile.renameTo(file)) {
System.err.println("Could not rename temporary file " +
tempFile.getAbsolutePath());
}
} catch (IOException e) {
System.err.println("error saving bytes to " + file);
if (tempFile != null) {
tempFile.delete();
}
e.printStackTrace();
}
}
/**
* @nowebref
* Spews a buffer of bytes to an OutputStream.
*/
static public void saveBytes(OutputStream output, byte[] data) {
try {
output.write(data);
output.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
//
/**
* ( begin auto-generated from saveStrings.xml )
*
* Writes an array of strings to a file, one line per string. This file is
* saved to the sketch's folder, which is opened by selecting "Show sketch
* folder" from the "Sketch" menu.<br />
* <br />
* It is not possible to use saveXxxxx() functions inside a web browser
* unless the sketch is <a
* href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</A>. To
* save a file back to a server, see the <a
* href="http://wiki.processing.org/w/Saving_files_to_a_web-server">save to
* web</A> code snippet on the Processing Wiki.<br/>
* <br/ >
* Starting with Processing 1.0, all files loaded and saved by the
* Processing API use UTF-8 encoding. In previous releases, the default
* encoding for your platform was used, which causes problems when files
* are moved to other platforms.
*
* ( end auto-generated )
* @webref output:files
* @param filename filename for output
* @param data string array to be written
* @see PApplet#loadStrings(String)
* @see PApplet#loadBytes(String)
* @see PApplet#saveBytes(String, byte[])
*/
public void saveStrings(String filename, String data[]) {
saveStrings(saveFile(filename), data);
}
/**
* @nowebref
*/
static public void saveStrings(File file, String data[]) {
saveStrings(createOutput(file), data);
}
/**
* @nowebref
*/
static public void saveStrings(OutputStream output, String[] data) {
PrintWriter writer = createWriter(output);
for (int i = 0; i < data.length; i++) {
writer.println(data[i]);
}
writer.flush();
writer.close();
}
//////////////////////////////////////////////////////////////
/**
* Prepend the sketch folder path to the filename (or path) that is
* passed in. External libraries should use this function to save to
* the sketch folder.
* <p/>
* Note that when running as an applet inside a web browser,
* the sketchPath will be set to null, because security restrictions
* prevent applets from accessing that information.
* <p/>
* This will also cause an error if the sketch is not inited properly,
* meaning that init() was never called on the PApplet when hosted
* my some other main() or by other code. For proper use of init(),
* see the examples in the main description text for PApplet.
*/
public String sketchPath(String where) {
if (sketchPath == null) {
return where;
// throw new RuntimeException("The applet was not inited properly, " +
// "or security restrictions prevented " +
// "it from determining its path.");
}
// isAbsolute() could throw an access exception, but so will writing
// to the local disk using the sketch path, so this is safe here.
// for 0120, added a try/catch anyways.
try {
if (new File(where).isAbsolute()) return where;
} catch (Exception e) { }
return sketchPath + File.separator + where;
}
public File sketchFile(String where) {
return new File(sketchPath(where));
}
/**
* Returns a path inside the applet folder to save to. Like sketchPath(),
* but creates any in-between folders so that things save properly.
* <p/>
* All saveXxxx() functions use the path to the sketch folder, rather than
* its data folder. Once exported, the data folder will be found inside the
* jar file of the exported application or applet. In this case, it's not
* possible to save data into the jar file, because it will often be running
* from a server, or marked in-use if running from a local file system.
* With this in mind, saving to the data path doesn't make sense anyway.
* If you know you're running locally, and want to save to the data folder,
* use <TT>saveXxxx("data/blah.dat")</TT>.
*/
public String savePath(String where) {
if (where == null) return null;
String filename = sketchPath(where);
createPath(filename);
return filename;
}
/**
* Identical to savePath(), but returns a File object.
*/
public File saveFile(String where) {
return new File(savePath(where));
}
/**
* Return a full path to an item in the data folder.
* <p>
* This is only available with applications, not applets or Android.
* On Windows and Linux, this is simply the data folder, which is located
* in the same directory as the EXE file and lib folders. On Mac OS X, this
* is a path to the data folder buried inside Contents/Resources/Java.
* For the latter point, that also means that the data folder should not be
* considered writable. Use sketchPath() for now, or inputPath() and
* outputPath() once they're available in the 2.0 release.
* <p>
* dataPath() is not supported with applets because applets have their data
* folder wrapped into the JAR file. To read data from the data folder that
* works with an applet, you should use other methods such as createInput(),
* createReader(), or loadStrings().
*/
public String dataPath(String where) {
return dataFile(where).getAbsolutePath();
}
/**
* Return a full path to an item in the data folder as a File object.
* See the dataPath() method for more information.
*/
public File dataFile(String where) {
// isAbsolute() could throw an access exception, but so will writing
// to the local disk using the sketch path, so this is safe here.
File why = new File(where);
if (why.isAbsolute()) return why;
String jarPath =
getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
if (jarPath.contains("Contents/Resources/Java/")) {
// The path will be URL encoded (%20 for spaces) coming from above
// http://code.google.com/p/processing/issues/detail?id=1073
File containingFolder = new File(urlDecode(jarPath)).getParentFile();
File dataFolder = new File(containingFolder, "data");
return new File(dataFolder, where);
}
// Windows, Linux, or when not using a Mac OS X .app file
return new File(sketchPath + File.separator + "data" + File.separator + where);
}
/**
* On Windows and Linux, this is simply the data folder. On Mac OS X, this is
* the path to the data folder buried inside Contents/Resources/Java
*/
// public File inputFile(String where) {
// }
// public String inputPath(String where) {
// }
/**
* Takes a path and creates any in-between folders if they don't
* already exist. Useful when trying to save to a subfolder that
* may not actually exist.
*/
static public void createPath(String path) {
createPath(new File(path));
}
static public void createPath(File file) {
try {
String parent = file.getParent();
if (parent != null) {
File unit = new File(parent);
if (!unit.exists()) unit.mkdirs();
}
} catch (SecurityException se) {
System.err.println("You don't have permissions to create " +
file.getAbsolutePath());
}
}
static public String getExtension(String filename) {
String extension;
String lower = filename.toLowerCase();
int dot = filename.lastIndexOf('.');
if (dot == -1) {
extension = "unknown"; // no extension found
}
extension = lower.substring(dot + 1);
// check for, and strip any parameters on the url, i.e.
// filename.jpg?blah=blah&something=that
int question = extension.indexOf('?');
if (question != -1) {
extension = extension.substring(0, question);
}
return extension;
}
//////////////////////////////////////////////////////////////
// URL ENCODING
static public String urlEncode(String str) {
try {
return URLEncoder.encode(str, "UTF-8");
} catch (UnsupportedEncodingException e) { // oh c'mon
return null;
}
}
static public String urlDecode(String str) {
try {
return URLDecoder.decode(str, "UTF-8");
} catch (UnsupportedEncodingException e) { // safe per the JDK source
return null;
}
}
//////////////////////////////////////////////////////////////
// SORT
/**
* ( begin auto-generated from sort.xml )
*
* Sorts an array of numbers from smallest to largest and puts an array of
* words in alphabetical order. The original array is not modified, a
* re-ordered array is returned. The <b>count</b> parameter states the
* number of elements to sort. For example if there are 12 elements in an
* array and if count is the value 5, only the first five elements on the
* array will be sorted. <!--As of release 0126, the alphabetical ordering
* is case insensitive.-->
*
* ( end auto-generated )
* @webref data:array_functions
* @param list array to sort
* @see PApplet#reverse(boolean[])
*/
static public byte[] sort(byte list[]) {
return sort(list, list.length);
}
/**
* @param count number of elements to sort, starting from 0
*/
static public byte[] sort(byte[] list, int count) {
byte[] outgoing = new byte[list.length];
System.arraycopy(list, 0, outgoing, 0, list.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public char[] sort(char list[]) {
return sort(list, list.length);
}
static public char[] sort(char[] list, int count) {
char[] outgoing = new char[list.length];
System.arraycopy(list, 0, outgoing, 0, list.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public int[] sort(int list[]) {
return sort(list, list.length);
}
static public int[] sort(int[] list, int count) {
int[] outgoing = new int[list.length];
System.arraycopy(list, 0, outgoing, 0, list.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public float[] sort(float list[]) {
return sort(list, list.length);
}
static public float[] sort(float[] list, int count) {
float[] outgoing = new float[list.length];
System.arraycopy(list, 0, outgoing, 0, list.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public String[] sort(String list[]) {
return sort(list, list.length);
}
static public String[] sort(String[] list, int count) {
String[] outgoing = new String[list.length];
System.arraycopy(list, 0, outgoing, 0, list.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
//////////////////////////////////////////////////////////////
// ARRAY UTILITIES
/**
* ( begin auto-generated from arrayCopy.xml )
*
* Copies an array (or part of an array) to another array. The <b>src</b>
* array is copied to the <b>dst</b> array, beginning at the position
* specified by <b>srcPos</b> and into the position specified by
* <b>dstPos</b>. The number of elements to copy is determined by
* <b>length</b>. The simplified version with two arguments copies an
* entire array to another of the same size. It is equivalent to
* "arrayCopy(src, 0, dst, 0, src.length)". This function is far more
* efficient for copying array data than iterating through a <b>for</b> and
* copying each element.
*
* ( end auto-generated )
* @webref data:array_functions
* @param src the source array
* @param srcPosition starting position in the source array
* @param dst the destination array of the same data type as the source array
* @param dstPosition starting position in the destination array
* @param length number of array elements to be copied
* @see PApplet#concat(boolean[], boolean[])
*/
static public void arrayCopy(Object src, int srcPosition,
Object dst, int dstPosition,
int length) {
System.arraycopy(src, srcPosition, dst, dstPosition, length);
}
/**
* Convenience method for arraycopy().
* Identical to <CODE>arraycopy(src, 0, dst, 0, length);</CODE>
*/
static public void arrayCopy(Object src, Object dst, int length) {
System.arraycopy(src, 0, dst, 0, length);
}
/**
* Shortcut to copy the entire contents of
* the source into the destination array.
* Identical to <CODE>arraycopy(src, 0, dst, 0, src.length);</CODE>
*/
static public void arrayCopy(Object src, Object dst) {
System.arraycopy(src, 0, dst, 0, Array.getLength(src));
}
//
/**
* @deprecated Use arrayCopy() instead.
*/
static public void arraycopy(Object src, int srcPosition,
Object dst, int dstPosition,
int length) {
System.arraycopy(src, srcPosition, dst, dstPosition, length);
}
/**
* @deprecated Use arrayCopy() instead.
*/
static public void arraycopy(Object src, Object dst, int length) {
System.arraycopy(src, 0, dst, 0, length);
}
/**
* @deprecated Use arrayCopy() instead.
*/
static public void arraycopy(Object src, Object dst) {
System.arraycopy(src, 0, dst, 0, Array.getLength(src));
}
/**
* ( begin auto-generated from expand.xml )
*
* Increases the size of an array. By default, this function doubles the
* size of the array, but the optional <b>newSize</b> parameter provides
* precise control over the increase in size.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) expand(originalArray)</em>.
*
* ( end auto-generated )
*
* @webref data:array_functions
* @param list the array to expand
* @see PApplet#shorten(boolean[])
*/
static public boolean[] expand(boolean list[]) {
return expand(list, list.length << 1);
}
/**
* @param newSize new size for the array
*/
static public boolean[] expand(boolean list[], int newSize) {
boolean temp[] = new boolean[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public byte[] expand(byte list[]) {
return expand(list, list.length << 1);
}
static public byte[] expand(byte list[], int newSize) {
byte temp[] = new byte[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public char[] expand(char list[]) {
return expand(list, list.length << 1);
}
static public char[] expand(char list[], int newSize) {
char temp[] = new char[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public int[] expand(int list[]) {
return expand(list, list.length << 1);
}
static public int[] expand(int list[], int newSize) {
int temp[] = new int[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public long[] expand(long list[]) {
return expand(list, list.length << 1);
}
static public long[] expand(long list[], int newSize) {
long temp[] = new long[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public float[] expand(float list[]) {
return expand(list, list.length << 1);
}
static public float[] expand(float list[], int newSize) {
float temp[] = new float[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public double[] expand(double list[]) {
return expand(list, list.length << 1);
}
static public double[] expand(double list[], int newSize) {
double temp[] = new double[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public String[] expand(String list[]) {
return expand(list, list.length << 1);
}
static public String[] expand(String list[], int newSize) {
String temp[] = new String[newSize];
// in case the new size is smaller than list.length
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
/**
* @nowebref
*/
static public Object expand(Object array) {
return expand(array, Array.getLength(array) << 1);
}
static public Object expand(Object list, int newSize) {
Class<?> type = list.getClass().getComponentType();
Object temp = Array.newInstance(type, newSize);
System.arraycopy(list, 0, temp, 0,
Math.min(Array.getLength(list), newSize));
return temp;
}
// contract() has been removed in revision 0124, use subset() instead.
// (expand() is also functionally equivalent)
/**
* ( begin auto-generated from append.xml )
*
* Expands an array by one element and adds data to the new position. The
* datatype of the <b>element</b> parameter must be the same as the
* datatype of the array.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) append(originalArray, element)</em>.
*
* ( end auto-generated )
*
* @webref data:array_functions
* @param array array to append
* @param value new data for the array
* @see PApplet#shorten(boolean[])
* @see PApplet#expand(boolean[])
*/
static public byte[] append(byte array[], byte value) {
array = expand(array, array.length + 1);
array[array.length-1] = value;
return array;
}
static public char[] append(char array[], char value) {
array = expand(array, array.length + 1);
array[array.length-1] = value;
return array;
}
static public int[] append(int array[], int value) {
array = expand(array, array.length + 1);
array[array.length-1] = value;
return array;
}
static public float[] append(float array[], float value) {
array = expand(array, array.length + 1);
array[array.length-1] = value;
return array;
}
static public String[] append(String array[], String value) {
array = expand(array, array.length + 1);
array[array.length-1] = value;
return array;
}
static public Object append(Object array, Object value) {
int length = Array.getLength(array);
array = expand(array, length + 1);
Array.set(array, length, value);
return array;
}
/**
* ( begin auto-generated from shorten.xml )
*
* Decreases an array by one element and returns the shortened array.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) shorten(originalArray)</em>.
*
* ( end auto-generated )
*
* @webref data:array_functions
* @param list array to shorten
* @see PApplet#append(byte[], byte)
* @see PApplet#expand(boolean[])
*/
static public boolean[] shorten(boolean list[]) {
return subset(list, 0, list.length-1);
}
static public byte[] shorten(byte list[]) {
return subset(list, 0, list.length-1);
}
static public char[] shorten(char list[]) {
return subset(list, 0, list.length-1);
}
static public int[] shorten(int list[]) {
return subset(list, 0, list.length-1);
}
static public float[] shorten(float list[]) {
return subset(list, 0, list.length-1);
}
static public String[] shorten(String list[]) {
return subset(list, 0, list.length-1);
}
static public Object shorten(Object list) {
int length = Array.getLength(list);
return subset(list, 0, length - 1);
}
/**
* ( begin auto-generated from splice.xml )
*
* Inserts a value or array of values into an existing array. The first two
* parameters must be of the same datatype. The <b>array</b> parameter
* defines the array which will be modified and the second parameter
* defines the data which will be inserted.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) splice(array1, array2, index)</em>.
*
* ( end auto-generated )
* @webref data:array_functions
* @param list array to splice into
* @param value value to be spliced in
* @param index position in the array from which to insert data
* @see PApplet#concat(boolean[], boolean[])
* @see PApplet#subset(boolean[], int, int)
*/
static final public boolean[] splice(boolean list[],
boolean value, int index) {
boolean outgoing[] = new boolean[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public boolean[] splice(boolean list[],
boolean value[], int index) {
boolean outgoing[] = new boolean[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public byte[] splice(byte list[],
byte value, int index) {
byte outgoing[] = new byte[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public byte[] splice(byte list[],
byte value[], int index) {
byte outgoing[] = new byte[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public char[] splice(char list[],
char value, int index) {
char outgoing[] = new char[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public char[] splice(char list[],
char value[], int index) {
char outgoing[] = new char[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public int[] splice(int list[],
int value, int index) {
int outgoing[] = new int[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public int[] splice(int list[],
int value[], int index) {
int outgoing[] = new int[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public float[] splice(float list[],
float value, int index) {
float outgoing[] = new float[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public float[] splice(float list[],
float value[], int index) {
float outgoing[] = new float[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public String[] splice(String list[],
String value, int index) {
String outgoing[] = new String[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public String[] splice(String list[],
String value[], int index) {
String outgoing[] = new String[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public Object splice(Object list, Object value, int index) {
Object[] outgoing = null;
int length = Array.getLength(list);
// check whether item being spliced in is an array
if (value.getClass().getName().charAt(0) == '[') {
int vlength = Array.getLength(value);
outgoing = new Object[length + vlength];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, vlength);
System.arraycopy(list, index, outgoing, index + vlength, length - index);
} else {
outgoing = new Object[length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
Array.set(outgoing, index, value);
System.arraycopy(list, index, outgoing, index + 1, length - index);
}
return outgoing;
}
static public boolean[] subset(boolean list[], int start) {
return subset(list, start, list.length - start);
}
/**
* ( begin auto-generated from subset.xml )
*
* Extracts an array of elements from an existing array. The <b>array</b>
* parameter defines the array from which the elements will be copied and
* the <b>offset</b> and <b>length</b> parameters determine which elements
* to extract. If no <b>length</b> is given, elements will be extracted
* from the <b>offset</b> to the end of the array. When specifying the
* <b>offset</b> remember the first array element is 0. This function does
* not change the source array.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) subset(originalArray, 0, 4)</em>.
*
* ( end auto-generated )
* @webref data:array_functions
* @param list array to extract from
* @param start position to begin
* @param count number of values to extract
* @see PApplet#splice(boolean[], boolean, int)
*/
static public boolean[] subset(boolean list[], int start, int count) {
boolean output[] = new boolean[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public byte[] subset(byte list[], int start) {
return subset(list, start, list.length - start);
}
static public byte[] subset(byte list[], int start, int count) {
byte output[] = new byte[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public char[] subset(char list[], int start) {
return subset(list, start, list.length - start);
}
static public char[] subset(char list[], int start, int count) {
char output[] = new char[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public int[] subset(int list[], int start) {
return subset(list, start, list.length - start);
}
static public int[] subset(int list[], int start, int count) {
int output[] = new int[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public float[] subset(float list[], int start) {
return subset(list, start, list.length - start);
}
static public float[] subset(float list[], int start, int count) {
float output[] = new float[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public String[] subset(String list[], int start) {
return subset(list, start, list.length - start);
}
static public String[] subset(String list[], int start, int count) {
String output[] = new String[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public Object subset(Object list, int start) {
int length = Array.getLength(list);
return subset(list, start, length - start);
}
static public Object subset(Object list, int start, int count) {
Class<?> type = list.getClass().getComponentType();
Object outgoing = Array.newInstance(type, count);
System.arraycopy(list, start, outgoing, 0, count);
return outgoing;
}
/**
* ( begin auto-generated from concat.xml )
*
* Concatenates two arrays. For example, concatenating the array { 1, 2, 3
* } and the array { 4, 5, 6 } yields { 1, 2, 3, 4, 5, 6 }. Both parameters
* must be arrays of the same datatype.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) concat(array1, array2)</em>.
*
* ( end auto-generated )
* @webref data:array_functions
* @param a first array to concatenate
* @param b second array to concatenate
* @see PApplet#splice(boolean[], boolean, int)
* @see PApplet#arrayCopy(Object, int, Object, int, int)
*/
static public boolean[] concat(boolean a[], boolean b[]) {
boolean c[] = new boolean[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public byte[] concat(byte a[], byte b[]) {
byte c[] = new byte[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public char[] concat(char a[], char b[]) {
char c[] = new char[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public int[] concat(int a[], int b[]) {
int c[] = new int[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public float[] concat(float a[], float b[]) {
float c[] = new float[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public String[] concat(String a[], String b[]) {
String c[] = new String[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public Object concat(Object a, Object b) {
Class<?> type = a.getClass().getComponentType();
int alength = Array.getLength(a);
int blength = Array.getLength(b);
Object outgoing = Array.newInstance(type, alength + blength);
System.arraycopy(a, 0, outgoing, 0, alength);
System.arraycopy(b, 0, outgoing, alength, blength);
return outgoing;
}
//
/**
* ( begin auto-generated from reverse.xml )
*
* Reverses the order of an array.
*
* ( end auto-generated )
* @webref data:array_functions
* @param list booleans[], bytes[], chars[], ints[], floats[], or Strings[]
* @see PApplet#sort(String[], int)
*/
static public boolean[] reverse(boolean list[]) {
boolean outgoing[] = new boolean[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public byte[] reverse(byte list[]) {
byte outgoing[] = new byte[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public char[] reverse(char list[]) {
char outgoing[] = new char[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public int[] reverse(int list[]) {
int outgoing[] = new int[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public float[] reverse(float list[]) {
float outgoing[] = new float[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public String[] reverse(String list[]) {
String outgoing[] = new String[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public Object reverse(Object list) {
Class<?> type = list.getClass().getComponentType();
int length = Array.getLength(list);
Object outgoing = Array.newInstance(type, length);
for (int i = 0; i < length; i++) {
Array.set(outgoing, i, Array.get(list, (length - 1) - i));
}
return outgoing;
}
//////////////////////////////////////////////////////////////
// STRINGS
/**
* ( begin auto-generated from trim.xml )
*
* Removes whitespace characters from the beginning and end of a String. In
* addition to standard whitespace characters such as space, carriage
* return, and tab, this function also removes the Unicode "nbsp" character.
*
* ( end auto-generated )
* @webref data:string_functions
* @param str any string
* @see PApplet#split(String, String)
* @see PApplet#join(String[], char)
*/
static public String trim(String str) {
return str.replace('\u00A0', ' ').trim();
}
/**
* @param array a String array
*/
static public String[] trim(String[] array) {
String[] outgoing = new String[array.length];
for (int i = 0; i < array.length; i++) {
if (array[i] != null) {
outgoing[i] = array[i].replace('\u00A0', ' ').trim();
}
}
return outgoing;
}
/**
* ( begin auto-generated from join.xml )
*
* Combines an array of Strings into one String, each separated by the
* character(s) used for the <b>separator</b> parameter. To join arrays of
* ints or floats, it's necessary to first convert them to strings using
* <b>nf()</b> or <b>nfs()</b>.
*
* ( end auto-generated )
* @webref data:string_functions
* @param list array of Strings
* @param separator char or String to be placed between each item
* @see PApplet#split(String, String)
* @see PApplet#trim(String)
* @see PApplet#nf(float, int, int)
* @see PApplet#nfs(float, int, int)
*/
static public String join(String[] list, char separator) {
return join(list, String.valueOf(separator));
}
static public String join(String[] list, String separator) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < list.length; i++) {
if (i != 0) buffer.append(separator);
buffer.append(list[i]);
}
return buffer.toString();
}
static public String[] splitTokens(String value) {
return splitTokens(value, WHITESPACE);
}
/**
* ( begin auto-generated from splitTokens.xml )
*
* The splitTokens() function splits a String at one or many character
* "tokens." The <b>tokens</b> parameter specifies the character or
* characters to be used as a boundary.
* <br/> <br/>
* If no <b>tokens</b> character is specified, any whitespace character is
* used to split. Whitespace characters include tab (\\t), line feed (\\n),
* carriage return (\\r), form feed (\\f), and space. To convert a String
* to an array of integers or floats, use the datatype conversion functions
* <b>int()</b> and <b>float()</b> to convert the array of Strings.
*
* ( end auto-generated )
* @webref data:string_functions
* @param value the String to be split
* @param delim list of individual characters that will be used as separators
* @see PApplet#split(String, String)
* @see PApplet#join(String[], String)
* @see PApplet#trim(String)
*/
static public String[] splitTokens(String value, String delim) {
StringTokenizer toker = new StringTokenizer(value, delim);
String pieces[] = new String[toker.countTokens()];
int index = 0;
while (toker.hasMoreTokens()) {
pieces[index++] = toker.nextToken();
}
return pieces;
}
/**
* ( begin auto-generated from split.xml )
*
* The split() function breaks a string into pieces using a character or
* string as the divider. The <b>delim</b> parameter specifies the
* character or characters that mark the boundaries between each piece. A
* String[] array is returned that contains each of the pieces.
* <br/> <br/>
* If the result is a set of numbers, you can convert the String[] array to
* to a float[] or int[] array using the datatype conversion functions
* <b>int()</b> and <b>float()</b> (see example above).
* <br/> <br/>
* The <b>splitTokens()</b> function works in a similar fashion, except
* that it splits using a range of characters instead of a specific
* character or sequence.
* <!-- /><br />
* This function uses regular expressions to determine how the <b>delim</b>
* parameter divides the <b>str</b> parameter. Therefore, if you use
* characters such parentheses and brackets that are used with regular
* expressions as a part of the <b>delim</b> parameter, you'll need to put
* two blackslashes (\\\\) in front of the character (see example above).
* You can read more about <a
* href="http://en.wikipedia.org/wiki/Regular_expression">regular
* expressions</a> and <a
* href="http://en.wikipedia.org/wiki/Escape_character">escape
* characters</a> on Wikipedia.
* -->
*
* ( end auto-generated )
* @webref data:string_functions
* @usage web_application
* @param value the String to be split
* @param delim the character or String used to separate the data
*/
static public String[] split(String value, char delim) {
// do this so that the exception occurs inside the user's
// program, rather than appearing to be a bug inside split()
if (value == null) return null;
//return split(what, String.valueOf(delim)); // huh
char chars[] = value.toCharArray();
int splitCount = 0; //1;
for (int i = 0; i < chars.length; i++) {
if (chars[i] == delim) splitCount++;
}
// make sure that there is something in the input string
//if (chars.length > 0) {
// if the last char is a delimeter, get rid of it..
//if (chars[chars.length-1] == delim) splitCount--;
// on second thought, i don't agree with this, will disable
//}
if (splitCount == 0) {
String splits[] = new String[1];
splits[0] = new String(value);
return splits;
}
//int pieceCount = splitCount + 1;
String splits[] = new String[splitCount + 1];
int splitIndex = 0;
int startIndex = 0;
for (int i = 0; i < chars.length; i++) {
if (chars[i] == delim) {
splits[splitIndex++] =
new String(chars, startIndex, i-startIndex);
startIndex = i + 1;
}
}
//if (startIndex != chars.length) {
splits[splitIndex] =
new String(chars, startIndex, chars.length-startIndex);
//}
return splits;
}
static public String[] split(String value, String delim) {
ArrayList<String> items = new ArrayList<String>();
int index;
int offset = 0;
while ((index = value.indexOf(delim, offset)) != -1) {
items.add(value.substring(offset, index));
offset = index + delim.length();
}
items.add(value.substring(offset));
String[] outgoing = new String[items.size()];
items.toArray(outgoing);
return outgoing;
}
static protected HashMap<String, Pattern> matchPatterns;
static Pattern matchPattern(String regexp) {
Pattern p = null;
if (matchPatterns == null) {
matchPatterns = new HashMap<String, Pattern>();
} else {
p = matchPatterns.get(regexp);
}
if (p == null) {
if (matchPatterns.size() == 10) {
// Just clear out the match patterns here if more than 10 are being
// used. It's not terribly efficient, but changes that you have >10
// different match patterns are very slim, unless you're doing
// something really tricky (like custom match() methods), in which
// case match() won't be efficient anyway. (And you should just be
// using your own Java code.) The alternative is using a queue here,
// but that's a silly amount of work for negligible benefit.
matchPatterns.clear();
}
p = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL);
matchPatterns.put(regexp, p);
}
return p;
}
/**
* ( begin auto-generated from match.xml )
*
* The match() function is used to apply a regular expression to a piece of
* text, and return matching groups (elements found inside parentheses) as
* a String array. No match will return null. If no groups are specified in
* the regexp, but the sequence matches, an array of length one (with the
* matched text as the first element of the array) will be returned.<br />
* <br />
* To use the function, first check to see if the result is null. If the
* result is null, then the sequence did not match. If the sequence did
* match, an array is returned.
* If there are groups (specified by sets of parentheses) in the regexp,
* then the contents of each will be returned in the array.
* Element [0] of a regexp match returns the entire matching string, and
* the match groups start at element [1] (the first group is [1], the
* second [2], and so on).<br />
* <br />
* The syntax can be found in the reference for Java's <a
* href="http://download.oracle.com/javase/6/docs/api/">Pattern</a> class.
* For regular expression syntax, read the <a
* href="http://download.oracle.com/javase/tutorial/essential/regex/">Java
* Tutorial</a> on the topic.
*
* ( end auto-generated )
* @webref data:string_functions
* @param str the String to be searched
* @param regexp the regexp to be used for matching
* @see PApplet#matchAll(String, String)
* @see PApplet#split(String, String)
* @see PApplet#splitTokens(String, String)
* @see PApplet#join(String[], String)
* @see PApplet#trim(String)
*/
static public String[] match(String str, String regexp) {
Pattern p = matchPattern(regexp);
Matcher m = p.matcher(str);
if (m.find()) {
int count = m.groupCount() + 1;
String[] groups = new String[count];
for (int i = 0; i < count; i++) {
groups[i] = m.group(i);
}
return groups;
}
return null;
}
/**
* ( begin auto-generated from matchAll.xml )
*
* This function is used to apply a regular expression to a piece of text,
* and return a list of matching groups (elements found inside parentheses)
* as a two-dimensional String array. No matches will return null. If no
* groups are specified in the regexp, but the sequence matches, a two
* dimensional array is still returned, but the second dimension is only of
* length one.<br />
* <br />
* To use the function, first check to see if the result is null. If the
* result is null, then the sequence did not match at all. If the sequence
* did match, a 2D array is returned. If there are groups (specified by
* sets of parentheses) in the regexp, then the contents of each will be
* returned in the array.
* Assuming, a loop with counter variable i, element [i][0] of a regexp
* match returns the entire matching string, and the match groups start at
* element [i][1] (the first group is [i][1], the second [i][2], and so
* on).<br />
* <br />
* The syntax can be found in the reference for Java's <a
* href="http://download.oracle.com/javase/6/docs/api/">Pattern</a> class.
* For regular expression syntax, read the <a
* href="http://download.oracle.com/javase/tutorial/essential/regex/">Java
* Tutorial</a> on the topic.
*
* ( end auto-generated )
* @webref data:string_functions
* @param str the String to be searched
* @param regexp the regexp to be used for matching
* @see PApplet#match(String, String)
* @see PApplet#split(String, String)
* @see PApplet#splitTokens(String, String)
* @see PApplet#join(String[], String)
* @see PApplet#trim(String)
*/
static public String[][] matchAll(String str, String regexp) {
Pattern p = matchPattern(regexp);
Matcher m = p.matcher(str);
ArrayList<String[]> results = new ArrayList<String[]>();
int count = m.groupCount() + 1;
while (m.find()) {
String[] groups = new String[count];
for (int i = 0; i < count; i++) {
groups[i] = m.group(i);
}
results.add(groups);
}
if (results.isEmpty()) {
return null;
}
String[][] matches = new String[results.size()][count];
for (int i = 0; i < matches.length; i++) {
matches[i] = results.get(i);
}
return matches;
}
//////////////////////////////////////////////////////////////
// CASTING FUNCTIONS, INSERTED BY PREPROC
/**
* Convert a char to a boolean. 'T', 't', and '1' will become the
* boolean value true, while 'F', 'f', or '0' will become false.
*/
/*
static final public boolean parseBoolean(char what) {
return ((what == 't') || (what == 'T') || (what == '1'));
}
*/
/**
* <p>Convert an integer to a boolean. Because of how Java handles upgrading
* numbers, this will also cover byte and char (as they will upgrade to
* an int without any sort of explicit cast).</p>
* <p>The preprocessor will convert boolean(what) to parseBoolean(what).</p>
* @return false if 0, true if any other number
*/
static final public boolean parseBoolean(int what) {
return (what != 0);
}
/*
// removed because this makes no useful sense
static final public boolean parseBoolean(float what) {
return (what != 0);
}
*/
/**
* Convert the string "true" or "false" to a boolean.
* @return true if 'what' is "true" or "TRUE", false otherwise
*/
static final public boolean parseBoolean(String what) {
return new Boolean(what).booleanValue();
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
// removed, no need to introduce strange syntax from other languages
static final public boolean[] parseBoolean(char what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] =
((what[i] == 't') || (what[i] == 'T') || (what[i] == '1'));
}
return outgoing;
}
*/
/**
* Convert a byte array to a boolean array. Each element will be
* evaluated identical to the integer case, where a byte equal
* to zero will return false, and any other value will return true.
* @return array of boolean elements
*/
/*
static final public boolean[] parseBoolean(byte what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (what[i] != 0);
}
return outgoing;
}
*/
/**
* Convert an int array to a boolean array. An int equal
* to zero will return false, and any other value will return true.
* @return array of boolean elements
*/
static final public boolean[] parseBoolean(int what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (what[i] != 0);
}
return outgoing;
}
/*
// removed, not necessary... if necessary, convert to int array first
static final public boolean[] parseBoolean(float what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (what[i] != 0);
}
return outgoing;
}
*/
static final public boolean[] parseBoolean(String what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = new Boolean(what[i]).booleanValue();
}
return outgoing;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public byte parseByte(boolean what) {
return what ? (byte)1 : 0;
}
static final public byte parseByte(char what) {
return (byte) what;
}
static final public byte parseByte(int what) {
return (byte) what;
}
static final public byte parseByte(float what) {
return (byte) what;
}
/*
// nixed, no precedent
static final public byte[] parseByte(String what) { // note: array[]
return what.getBytes();
}
*/
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public byte[] parseByte(boolean what[]) {
byte outgoing[] = new byte[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = what[i] ? (byte)1 : 0;
}
return outgoing;
}
static final public byte[] parseByte(char what[]) {
byte outgoing[] = new byte[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (byte) what[i];
}
return outgoing;
}
static final public byte[] parseByte(int what[]) {
byte outgoing[] = new byte[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (byte) what[i];
}
return outgoing;
}
static final public byte[] parseByte(float what[]) {
byte outgoing[] = new byte[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (byte) what[i];
}
return outgoing;
}
/*
static final public byte[][] parseByte(String what[]) { // note: array[][]
byte outgoing[][] = new byte[what.length][];
for (int i = 0; i < what.length; i++) {
outgoing[i] = what[i].getBytes();
}
return outgoing;
}
*/
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
static final public char parseChar(boolean what) { // 0/1 or T/F ?
return what ? 't' : 'f';
}
*/
static final public char parseChar(byte what) {
return (char) (what & 0xff);
}
static final public char parseChar(int what) {
return (char) what;
}
/*
static final public char parseChar(float what) { // nonsensical
return (char) what;
}
static final public char[] parseChar(String what) { // note: array[]
return what.toCharArray();
}
*/
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
static final public char[] parseChar(boolean what[]) { // 0/1 or T/F ?
char outgoing[] = new char[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = what[i] ? 't' : 'f';
}
return outgoing;
}
*/
static final public char[] parseChar(byte what[]) {
char outgoing[] = new char[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (char) (what[i] & 0xff);
}
return outgoing;
}
static final public char[] parseChar(int what[]) {
char outgoing[] = new char[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (char) what[i];
}
return outgoing;
}
/*
static final public char[] parseChar(float what[]) { // nonsensical
char outgoing[] = new char[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (char) what[i];
}
return outgoing;
}
static final public char[][] parseChar(String what[]) { // note: array[][]
char outgoing[][] = new char[what.length][];
for (int i = 0; i < what.length; i++) {
outgoing[i] = what[i].toCharArray();
}
return outgoing;
}
*/
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public int parseInt(boolean what) {
return what ? 1 : 0;
}
/**
* Note that parseInt() will un-sign a signed byte value.
*/
static final public int parseInt(byte what) {
return what & 0xff;
}
/**
* Note that parseInt('5') is unlike String in the sense that it
* won't return 5, but the ascii value. This is because ((int) someChar)
* returns the ascii value, and parseInt() is just longhand for the cast.
*/
static final public int parseInt(char what) {
return what;
}
/**
* Same as floor(), or an (int) cast.
*/
static final public int parseInt(float what) {
return (int) what;
}
/**
* Parse a String into an int value. Returns 0 if the value is bad.
*/
static final public int parseInt(String what) {
return parseInt(what, 0);
}
/**
* Parse a String to an int, and provide an alternate value that
* should be used when the number is invalid.
*/
static final public int parseInt(String what, int otherwise) {
try {
int offset = what.indexOf('.');
if (offset == -1) {
return Integer.parseInt(what);
} else {
return Integer.parseInt(what.substring(0, offset));
}
} catch (NumberFormatException e) { }
return otherwise;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public int[] parseInt(boolean what[]) {
int list[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
list[i] = what[i] ? 1 : 0;
}
return list;
}
static final public int[] parseInt(byte what[]) { // note this unsigns
int list[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
list[i] = (what[i] & 0xff);
}
return list;
}
static final public int[] parseInt(char what[]) {
int list[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
list[i] = what[i];
}
return list;
}
static public int[] parseInt(float what[]) {
int inties[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
inties[i] = (int)what[i];
}
return inties;
}
/**
* Make an array of int elements from an array of String objects.
* If the String can't be parsed as a number, it will be set to zero.
*
* String s[] = { "1", "300", "44" };
* int numbers[] = parseInt(s);
*
* numbers will contain { 1, 300, 44 }
*/
static public int[] parseInt(String what[]) {
return parseInt(what, 0);
}
/**
* Make an array of int elements from an array of String objects.
* If the String can't be parsed as a number, its entry in the
* array will be set to the value of the "missing" parameter.
*
* String s[] = { "1", "300", "apple", "44" };
* int numbers[] = parseInt(s, 9999);
*
* numbers will contain { 1, 300, 9999, 44 }
*/
static public int[] parseInt(String what[], int missing) {
int output[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
try {
output[i] = Integer.parseInt(what[i]);
} catch (NumberFormatException e) {
output[i] = missing;
}
}
return output;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
static final public float parseFloat(boolean what) {
return what ? 1 : 0;
}
*/
/**
* Convert an int to a float value. Also handles bytes because of
* Java's rules for upgrading values.
*/
static final public float parseFloat(int what) { // also handles byte
return what;
}
static final public float parseFloat(String what) {
return parseFloat(what, Float.NaN);
}
static final public float parseFloat(String what, float otherwise) {
try {
return new Float(what).floatValue();
} catch (NumberFormatException e) { }
return otherwise;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
static final public float[] parseFloat(boolean what[]) {
float floaties[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
floaties[i] = what[i] ? 1 : 0;
}
return floaties;
}
static final public float[] parseFloat(char what[]) {
float floaties[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
floaties[i] = (char) what[i];
}
return floaties;
}
*/
static final public float[] parseByte(byte what[]) {
float floaties[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
floaties[i] = what[i];
}
return floaties;
}
static final public float[] parseFloat(int what[]) {
float floaties[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
floaties[i] = what[i];
}
return floaties;
}
static final public float[] parseFloat(String what[]) {
return parseFloat(what, Float.NaN);
}
static final public float[] parseFloat(String what[], float missing) {
float output[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
try {
output[i] = new Float(what[i]).floatValue();
} catch (NumberFormatException e) {
output[i] = missing;
}
}
return output;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public String str(boolean x) {
return String.valueOf(x);
}
static final public String str(byte x) {
return String.valueOf(x);
}
static final public String str(char x) {
return String.valueOf(x);
}
static final public String str(int x) {
return String.valueOf(x);
}
static final public String str(float x) {
return String.valueOf(x);
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public String[] str(boolean x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
static final public String[] str(byte x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
static final public String[] str(char x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
static final public String[] str(int x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
static final public String[] str(float x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
//////////////////////////////////////////////////////////////
// INT NUMBER FORMATTING
/**
* Integer number formatter.
*/
static private NumberFormat int_nf;
static private int int_nf_digits;
static private boolean int_nf_commas;
static public String[] nf(int num[], int digits) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nf(num[i], digits);
}
return formatted;
}
/**
* ( begin auto-generated from nf.xml )
*
* Utility function for formatting numbers into strings. There are two
* versions, one for formatting floats and one for formatting ints. The
* values for the <b>digits</b>, <b>left</b>, and <b>right</b> parameters
* should always be positive integers.<br /><br />As shown in the above
* example, <b>nf()</b> is used to add zeros to the left and/or right of a
* number. This is typically for aligning a list of numbers. To
* <em>remove</em> digits from a floating-point number, use the
* <b>int()</b>, <b>ceil()</b>, <b>floor()</b>, or <b>round()</b>
* functions.
*
* ( end auto-generated )
* @webref data:string_functions
* @param num the number(s) to format
* @param digits number of digits to pad with zero
* @see PApplet#nfs(float, int, int)
* @see PApplet#nfp(float, int, int)
* @see PApplet#nfc(float, int)
* @see PApplet#int(float)
*/
static public String nf(int num, int digits) {
if ((int_nf != null) &&
(int_nf_digits == digits) &&
!int_nf_commas) {
return int_nf.format(num);
}
int_nf = NumberFormat.getInstance();
int_nf.setGroupingUsed(false); // no commas
int_nf_commas = false;
int_nf.setMinimumIntegerDigits(digits);
int_nf_digits = digits;
return int_nf.format(num);
}
/**
* ( begin auto-generated from nfc.xml )
*
* Utility function for formatting numbers into strings and placing
* appropriate commas to mark units of 1000. There are two versions, one
* for formatting ints and one for formatting an array of ints. The value
* for the <b>digits</b> parameter should always be a positive integer.
* <br/> <br/>
* For a non-US locale, this will insert periods instead of commas, or
* whatever is apprioriate for that region.
*
* ( end auto-generated )
* @webref data:string_functions
* @param num the number(s) to format
* @see PApplet#nf(float, int, int)
* @see PApplet#nfp(float, int, int)
* @see PApplet#nfc(float, int)
*/
static public String[] nfc(int num[]) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfc(num[i]);
}
return formatted;
}
/**
* nfc() or "number format with commas". This is an unfortunate misnomer
* because in locales where a comma is not the separator for numbers, it
* won't actually be outputting a comma, it'll use whatever makes sense for
* the locale.
*/
static public String nfc(int num) {
if ((int_nf != null) &&
(int_nf_digits == 0) &&
int_nf_commas) {
return int_nf.format(num);
}
int_nf = NumberFormat.getInstance();
int_nf.setGroupingUsed(true);
int_nf_commas = true;
int_nf.setMinimumIntegerDigits(0);
int_nf_digits = 0;
return int_nf.format(num);
}
/**
* number format signed (or space)
* Formats a number but leaves a blank space in the front
* when it's positive so that it can be properly aligned with
* numbers that have a negative sign in front of them.
*/
/**
* ( begin auto-generated from nfs.xml )
*
* Utility function for formatting numbers into strings. Similar to
* <b>nf()</b> but leaves a blank space in front of positive numbers so
* they align with negative numbers in spite of the minus symbol. There are
* two versions, one for formatting floats and one for formatting ints. The
* values for the <b>digits</b>, <b>left</b>, and <b>right</b> parameters
* should always be positive integers.
*
* ( end auto-generated )
* @webref data:string_functions
* @param num the number(s) to format
* @param digits number of digits to pad with zeroes
* @see PApplet#nf(float, int, int)
* @see PApplet#nfp(float, int, int)
* @see PApplet#nfc(float, int)
*/
static public String nfs(int num, int digits) {
return (num < 0) ? nf(num, digits) : (' ' + nf(num, digits));
}
static public String[] nfs(int num[], int digits) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfs(num[i], digits);
}
return formatted;
}
//
/**
* number format positive (or plus)
* Formats a number, always placing a - or + sign
* in the front when it's negative or positive.
*/
/**
* ( begin auto-generated from nfp.xml )
*
* Utility function for formatting numbers into strings. Similar to
* <b>nf()</b> but puts a "+" in front of positive numbers and a "-" in
* front of negative numbers. There are two versions, one for formatting
* floats and one for formatting ints. The values for the <b>digits</b>,
* <b>left</b>, and <b>right</b> parameters should always be positive integers.
*
* ( end auto-generated )
* @webref data:string_functions
* @param num the number(s) to format
* @param digits number of digits to pad with zeroes
* @see PApplet#nf(float, int, int)
* @see PApplet#nfs(float, int, int)
* @see PApplet#nfc(float, int)
*/
static public String nfp(int num, int digits) {
return (num < 0) ? nf(num, digits) : ('+' + nf(num, digits));
}
static public String[] nfp(int num[], int digits) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfp(num[i], digits);
}
return formatted;
}
//////////////////////////////////////////////////////////////
// FLOAT NUMBER FORMATTING
static private NumberFormat float_nf;
static private int float_nf_left, float_nf_right;
static private boolean float_nf_commas;
static public String[] nf(float num[], int left, int right) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nf(num[i], left, right);
}
return formatted;
}
/**
* @param num[] the number(s) to format
* @param left number of digits to the left of the decimal point
* @param right number of digits to the right of the decimal point
*/
static public String nf(float num, int left, int right) {
if ((float_nf != null) &&
(float_nf_left == left) &&
(float_nf_right == right) &&
!float_nf_commas) {
return float_nf.format(num);
}
float_nf = NumberFormat.getInstance();
float_nf.setGroupingUsed(false);
float_nf_commas = false;
if (left != 0) float_nf.setMinimumIntegerDigits(left);
if (right != 0) {
float_nf.setMinimumFractionDigits(right);
float_nf.setMaximumFractionDigits(right);
}
float_nf_left = left;
float_nf_right = right;
return float_nf.format(num);
}
/**
* @param num[] the number(s) to format
* @param right number of digits to the right of the decimal point
*/
static public String[] nfc(float num[], int right) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfc(num[i], right);
}
return formatted;
}
static public String nfc(float num, int right) {
if ((float_nf != null) &&
(float_nf_left == 0) &&
(float_nf_right == right) &&
float_nf_commas) {
return float_nf.format(num);
}
float_nf = NumberFormat.getInstance();
float_nf.setGroupingUsed(true);
float_nf_commas = true;
if (right != 0) {
float_nf.setMinimumFractionDigits(right);
float_nf.setMaximumFractionDigits(right);
}
float_nf_left = 0;
float_nf_right = right;
return float_nf.format(num);
}
/**
* @param num[] the number(s) to format
* @param left the number of digits to the left of the decimal point
* @param right the number of digits to the right of the decimal point
*/
static public String[] nfs(float num[], int left, int right) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfs(num[i], left, right);
}
return formatted;
}
static public String nfs(float num, int left, int right) {
return (num < 0) ? nf(num, left, right) : (' ' + nf(num, left, right));
}
/**
* @param left the number of digits to the left of the decimal point
* @param right the number of digits to the right of the decimal point
*/
static public String[] nfp(float num[], int left, int right) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfp(num[i], left, right);
}
return formatted;
}
static public String nfp(float num, int left, int right) {
return (num < 0) ? nf(num, left, right) : ('+' + nf(num, left, right));
}
//////////////////////////////////////////////////////////////
// HEX/BINARY CONVERSION
/**
* ( begin auto-generated from hex.xml )
*
* Converts a byte, char, int, or color to a String containing the
* equivalent hexadecimal notation. For example color(0, 102, 153) will
* convert to the String "FF006699". This function can help make your geeky
* debugging sessions much happier.
* <br/> <br/>
* Note that the maximum number of digits is 8, because an int value can
* only represent up to 32 bits. Specifying more than eight digits will
* simply shorten the string to eight anyway.
*
* ( end auto-generated )
* @webref data:conversion
* @param value the value to convert
* @see PApplet#unhex(String)
* @see PApplet#binary(byte)
* @see PApplet#unbinary(String)
*/
static final public String hex(byte value) {
return hex(value, 2);
}
static final public String hex(char value) {
return hex(value, 4);
}
static final public String hex(int value) {
return hex(value, 8);
}
/**
* @param digits the number of digits (maximum 8)
*/
static final public String hex(int value, int digits) {
String stuff = Integer.toHexString(value).toUpperCase();
if (digits > 8) {
digits = 8;
}
int length = stuff.length();
if (length > digits) {
return stuff.substring(length - digits);
} else if (length < digits) {
return "00000000".substring(8 - (digits-length)) + stuff;
}
return stuff;
}
/**
* ( begin auto-generated from unhex.xml )
*
* Converts a String representation of a hexadecimal number to its
* equivalent integer value.
*
* ( end auto-generated )
*
* @webref data:conversion
* @param value String to convert to an integer
* @see PApplet#hex(int, int)
* @see PApplet#binary(byte)
* @see PApplet#unbinary(String)
*/
static final public int unhex(String value) {
// has to parse as a Long so that it'll work for numbers bigger than 2^31
return (int) (Long.parseLong(value, 16));
}
//
/**
* Returns a String that contains the binary value of a byte.
* The returned value will always have 8 digits.
*/
static final public String binary(byte value) {
return binary(value, 8);
}
/**
* Returns a String that contains the binary value of a char.
* The returned value will always have 16 digits because chars
* are two bytes long.
*/
static final public String binary(char value) {
return binary(value, 16);
}
/**
* Returns a String that contains the binary value of an int. The length
* depends on the size of the number itself. If you want a specific number
* of digits use binary(int what, int digits) to specify how many.
*/
static final public String binary(int value) {
return binary(value, 32);
}
/*
* Returns a String that contains the binary value of an int.
* The digits parameter determines how many digits will be used.
*/
/**
* ( begin auto-generated from binary.xml )
*
* Converts a byte, char, int, or color to a String containing the
* equivalent binary notation. For example color(0, 102, 153, 255) will
* convert to the String "11111111000000000110011010011001". This function
* can help make your geeky debugging sessions much happier.
* <br/> <br/>
* Note that the maximum number of digits is 32, because an int value can
* only represent up to 32 bits. Specifying more than 32 digits will simply
* shorten the string to 32 anyway.
*
* ( end auto-generated )
* @webref data:conversion
* @param value value to convert
* @param digits number of digits to return
* @see PApplet#unbinary(String)
* @see PApplet#hex(int,int)
* @see PApplet#unhex(String)
*/
static final public String binary(int value, int digits) {
String stuff = Integer.toBinaryString(value);
if (digits > 32) {
digits = 32;
}
int length = stuff.length();
if (length > digits) {
return stuff.substring(length - digits);
} else if (length < digits) {
int offset = 32 - (digits-length);
return "00000000000000000000000000000000".substring(offset) + stuff;
}
return stuff;
}
/**
* ( begin auto-generated from unbinary.xml )
*
* Converts a String representation of a binary number to its equivalent
* integer value. For example, unbinary("00001000") will return 8.
*
* ( end auto-generated )
* @webref data:conversion
* @param value String to convert to an integer
* @see PApplet#binary(byte)
* @see PApplet#hex(int,int)
* @see PApplet#unhex(String)
*/
static final public int unbinary(String value) {
return Integer.parseInt(value, 2);
}
//////////////////////////////////////////////////////////////
// COLOR FUNCTIONS
// moved here so that they can work without
// the graphics actually being instantiated (outside setup)
/**
* ( begin auto-generated from color.xml )
*
* Creates colors for storing in variables of the <b>color</b> datatype.
* The parameters are interpreted as RGB or HSB values depending on the
* current <b>colorMode()</b>. The default mode is RGB values from 0 to 255
* and therefore, the function call <b>color(255, 204, 0)</b> will return a
* bright yellow color. More about how colors are stored can be found in
* the reference for the <a href="color_datatype.html">color</a> datatype.
*
* ( end auto-generated )
* @webref color:creating_reading
* @param gray number specifying value between white and black
* @see PApplet#colorMode(int)
*/
public final int color(int gray) {
if (g == null) {
if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
return 0xff000000 | (gray << 16) | (gray << 8) | gray;
}
return g.color(gray);
}
/**
* @nowebref
* @param fgray number specifying value between white and black
*/
public final int color(float fgray) {
if (g == null) {
int gray = (int) fgray;
if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
return 0xff000000 | (gray << 16) | (gray << 8) | gray;
}
return g.color(fgray);
}
/**
* As of 0116 this also takes color(#FF8800, alpha)
* @param alpha relative to current color range
*/
public final int color(int gray, int alpha) {
if (g == null) {
if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
if (gray > 255) {
// then assume this is actually a #FF8800
return (alpha << 24) | (gray & 0xFFFFFF);
} else {
//if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
return (alpha << 24) | (gray << 16) | (gray << 8) | gray;
}
}
return g.color(gray, alpha);
}
/**
* @nowebref
*/
public final int color(float fgray, float falpha) {
if (g == null) {
int gray = (int) fgray;
int alpha = (int) falpha;
if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
return 0xff000000 | (gray << 16) | (gray << 8) | gray;
}
return g.color(fgray, falpha);
}
/**
* @param v1 red or hue values relative to the current color range
* @param v2 green or saturation values relative to the current color range
* @param v3 blue or brightness values relative to the current color range
*/
public final int color(int v1, int v2, int v3) {
if (g == null) {
if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0;
if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0;
if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0;
return 0xff000000 | (v1 << 16) | (v2 << 8) | v3;
}
return g.color(v1, v2, v3);
}
public final int color(int v1, int v2, int v3, int alpha) {
if (g == null) {
if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0;
if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0;
if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0;
return (alpha << 24) | (v1 << 16) | (v2 << 8) | v3;
}
return g.color(v1, v2, v3, alpha);
}
public final int color(float v1, float v2, float v3) {
if (g == null) {
if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0;
if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0;
if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0;
return 0xff000000 | ((int)v1 << 16) | ((int)v2 << 8) | (int)v3;
}
return g.color(v1, v2, v3);
}
public final int color(float v1, float v2, float v3, float alpha) {
if (g == null) {
if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0;
if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0;
if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0;
return ((int)alpha << 24) | ((int)v1 << 16) | ((int)v2 << 8) | (int)v3;
}
return g.color(v1, v2, v3, alpha);
}
static public int blendColor(int c1, int c2, int mode) {
return PImage.blendColor(c1, c2, mode);
}
//////////////////////////////////////////////////////////////
// MAIN
/**
* Set this sketch to communicate its state back to the PDE.
* <p/>
* This uses the stderr stream to write positions of the window
* (so that it will be saved by the PDE for the next run) and
* notify on quit. See more notes in the Worker class.
*/
public void setupExternalMessages() {
frame.addComponentListener(new ComponentAdapter() {
@Override
public void componentMoved(ComponentEvent e) {
Point where = ((Frame) e.getSource()).getLocation();
System.err.println(PApplet.EXTERNAL_MOVE + " " +
where.x + " " + where.y);
System.err.flush(); // doesn't seem to help or hurt
}
});
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
// System.err.println(PApplet.EXTERNAL_QUIT);
// System.err.flush(); // important
// System.exit(0);
exit(); // don't quit, need to just shut everything down (0133)
}
});
}
/**
* Set up a listener that will fire proper component resize events
* in cases where frame.setResizable(true) is called.
*/
public void setupFrameResizeListener() {
frame.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
// Ignore bad resize events fired during setup to fix
// http://dev.processing.org/bugs/show_bug.cgi?id=341
// This should also fix the blank screen on Linux bug
// http://dev.processing.org/bugs/show_bug.cgi?id=282
if (frame.isResizable()) {
// might be multiple resize calls before visible (i.e. first
// when pack() is called, then when it's resized for use).
// ignore them because it's not the user resizing things.
Frame farm = (Frame) e.getComponent();
if (farm.isVisible()) {
Insets insets = farm.getInsets();
Dimension windowSize = farm.getSize();
Rectangle newBounds =
new Rectangle(insets.left, insets.top,
windowSize.width - insets.left - insets.right,
windowSize.height - insets.top - insets.bottom);
Rectangle oldBounds = getBounds();
if (!newBounds.equals(oldBounds)) {
// the ComponentListener in PApplet will handle calling size()
setBounds(newBounds);
}
}
}
}
});
}
// /**
// * GIF image of the Processing logo.
// */
// static public final byte[] ICON_IMAGE = {
// 71, 73, 70, 56, 57, 97, 16, 0, 16, 0, -77, 0, 0, 0, 0, 0, -1, -1, -1, 12,
// 12, 13, -15, -15, -14, 45, 57, 74, 54, 80, 111, 47, 71, 97, 62, 88, 117,
// 1, 14, 27, 7, 41, 73, 15, 52, 85, 2, 31, 55, 4, 54, 94, 18, 69, 109, 37,
// 87, 126, -1, -1, -1, 33, -7, 4, 1, 0, 0, 15, 0, 44, 0, 0, 0, 0, 16, 0, 16,
// 0, 0, 4, 122, -16, -107, 114, -86, -67, 83, 30, -42, 26, -17, -100, -45,
// 56, -57, -108, 48, 40, 122, -90, 104, 67, -91, -51, 32, -53, 77, -78, -100,
// 47, -86, 12, 76, -110, -20, -74, -101, 97, -93, 27, 40, 20, -65, 65, 48,
// -111, 99, -20, -112, -117, -123, -47, -105, 24, 114, -112, 74, 69, 84, 25,
// 93, 88, -75, 9, 46, 2, 49, 88, -116, -67, 7, -19, -83, 60, 38, 3, -34, 2,
// 66, -95, 27, -98, 13, 4, -17, 55, 33, 109, 11, 11, -2, -128, 121, 123, 62,
// 91, 120, -128, 127, 122, 115, 102, 2, 119, 0, -116, -113, -119, 6, 102,
// 121, -108, -126, 5, 18, 6, 4, -102, -101, -100, 114, 15, 17, 0, 59
// };
static ArrayList<Image> iconImages;
protected void setIconImage(Frame frame) {
// On OS X, this only affects what shows up in the dock when minimized.
// So this is actually a step backwards. Brilliant.
if (platform != MACOSX) {
//Image image = Toolkit.getDefaultToolkit().createImage(ICON_IMAGE);
//frame.setIconImage(image);
try {
if (iconImages == null) {
iconImages = new ArrayList<Image>();
final int[] sizes = { 16, 24, 32, 48, 64 };
for (int sz : sizes) {
URL url = getClass().getResource("/icon/icon-" + sz + ".png");
Image image = Toolkit.getDefaultToolkit().getImage(url);
iconImages.add(image);
//iconImages.add(Toolkit.getLibImage("icons/pde-" + sz + ".png", frame));
}
}
frame.setIconImages(iconImages);
} catch (Exception e) {
//e.printStackTrace(); // more or less harmless; don't spew errors
}
}
}
// Not gonna do this dynamically, only on startup. Too much headache.
// public void fullscreen() {
// if (frame != null) {
// if (PApplet.platform == MACOSX) {
// japplemenubar.JAppleMenuBar.hide();
// }
// GraphicsConfiguration gc = frame.getGraphicsConfiguration();
// Rectangle rect = gc.getBounds();
//// GraphicsDevice device = gc.getDevice();
// frame.setBounds(rect.x, rect.y, rect.width, rect.height);
// }
// }
/**
* main() method for running this class from the command line.
* <p>
* <B>The options shown here are not yet finalized and will be
* changing over the next several releases.</B>
* <p>
* The simplest way to turn and applet into an application is to
* add the following code to your program:
* <PRE>static public void main(String args[]) {
* PApplet.main("YourSketchName", args);
* }</PRE>
* This will properly launch your applet from a double-clickable
* .jar or from the command line.
* <PRE>
* Parameters useful for launching or also used by the PDE:
*
* --location=x,y upper-lefthand corner of where the applet
* should appear on screen. if not used,
* the default is to center on the main screen.
*
* --full-screen put the applet into full screen "present" mode.
*
* --hide-stop use to hide the stop button in situations where
* you don't want to allow users to exit. also
* see the FAQ on information for capturing the ESC
* key when running in presentation mode.
*
* --stop-color=#xxxxxx color of the 'stop' text used to quit an
* sketch when it's in present mode.
*
* --bgcolor=#xxxxxx background color of the window.
*
* --sketch-path location of where to save files from functions
* like saveStrings() or saveFrame(). defaults to
* the folder that the java application was
* launched from, which means if this isn't set by
* the pde, everything goes into the same folder
* as processing.exe.
*
* --display=n set what display should be used by this sketch.
* displays are numbered starting from 0.
*
* Parameters used by Processing when running via the PDE
*
* --external set when the applet is being used by the PDE
*
* --editor-location=x,y position of the upper-lefthand corner of the
* editor window, for placement of applet window
* </PRE>
*/
static public void main(final String[] args) {
runSketch(args, null);
}
/**
* Convenience method so that PApplet.main("YourSketch") launches a sketch,
* rather than having to wrap it into a String array.
* @param mainClass name of the class to load (with package if any)
*/
static public void main(final String mainClass) {
main(mainClass, null);
}
/**
* Convenience method so that PApplet.main("YourSketch", args) launches a
* sketch, rather than having to wrap it into a String array, and appending
* the 'args' array when not null.
* @param mainClass name of the class to load (with package if any)
* @param args command line arguments to pass to the sketch
*/
static public void main(final String mainClass, final String[] passedArgs) {
String[] args = new String[] { mainClass };
if (passedArgs != null) {
args = concat(args, passedArgs);
}
runSketch(args, null);
}
static public void runSketch(final String args[], final PApplet constructedApplet) {
// Disable abyssmally slow Sun renderer on OS X 10.5.
if (platform == MACOSX) {
// Only run this on OS X otherwise it can cause a permissions error.
// http://dev.processing.org/bugs/show_bug.cgi?id=976
System.setProperty("apple.awt.graphics.UseQuartz",
String.valueOf(useQuartz));
}
// Doesn't seem to do much to help avoid flicker
System.setProperty("sun.awt.noerasebackground", "true");
// This doesn't do anything.
// if (platform == WINDOWS) {
// // For now, disable the D3D renderer on Java 6u10 because
// // it causes problems with Present mode.
// // http://dev.processing.org/bugs/show_bug.cgi?id=1009
// System.setProperty("sun.java2d.d3d", "false");
// }
if (args.length < 1) {
System.err.println("Usage: PApplet <appletname>");
System.err.println("For additional options, " +
"see the Javadoc for PApplet");
System.exit(1);
}
// EventQueue.invokeLater(new Runnable() {
// public void run() {
// runSketchEDT(args, constructedApplet);
// }
// });
// }
//
//
// static public void runSketchEDT(final String args[], final PApplet constructedApplet) {
boolean external = false;
int[] location = null;
int[] editorLocation = null;
String name = null;
boolean present = false;
// boolean exclusive = false;
// Color backgroundColor = Color.BLACK;
Color backgroundColor = null; //Color.BLACK;
Color stopColor = Color.GRAY;
GraphicsDevice displayDevice = null;
boolean hideStop = false;
String param = null, value = null;
// try to get the user folder. if running under java web start,
// this may cause a security exception if the code is not signed.
// http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Integrate;action=display;num=1159386274
String folder = null;
try {
folder = System.getProperty("user.dir");
} catch (Exception e) { }
int argIndex = 0;
while (argIndex < args.length) {
int equals = args[argIndex].indexOf('=');
if (equals != -1) {
param = args[argIndex].substring(0, equals);
value = args[argIndex].substring(equals + 1);
if (param.equals(ARGS_EDITOR_LOCATION)) {
external = true;
editorLocation = parseInt(split(value, ','));
} else if (param.equals(ARGS_DISPLAY)) {
int deviceIndex = Integer.parseInt(value);
GraphicsEnvironment environment =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice devices[] = environment.getScreenDevices();
if ((deviceIndex >= 0) && (deviceIndex < devices.length)) {
displayDevice = devices[deviceIndex];
} else {
System.err.println("Display " + value + " does not exist, " +
"using the default display instead.");
for (int i = 0; i < devices.length; i++) {
System.err.println(i + " is " + devices[i]);
}
}
} else if (param.equals(ARGS_BGCOLOR)) {
if (value.charAt(0) == '#') value = value.substring(1);
backgroundColor = new Color(Integer.parseInt(value, 16));
} else if (param.equals(ARGS_STOP_COLOR)) {
if (value.charAt(0) == '#') value = value.substring(1);
stopColor = new Color(Integer.parseInt(value, 16));
} else if (param.equals(ARGS_SKETCH_FOLDER)) {
folder = value;
} else if (param.equals(ARGS_LOCATION)) {
location = parseInt(split(value, ','));
}
} else {
if (args[argIndex].equals(ARGS_PRESENT)) { // keep for compatability
present = true;
} else if (args[argIndex].equals(ARGS_FULL_SCREEN)) {
present = true;
// } else if (args[argIndex].equals(ARGS_EXCLUSIVE)) {
// exclusive = true;
} else if (args[argIndex].equals(ARGS_HIDE_STOP)) {
hideStop = true;
} else if (args[argIndex].equals(ARGS_EXTERNAL)) {
external = true;
} else {
name = args[argIndex];
break; // because of break, argIndex won't increment again
}
}
argIndex++;
}
// Set this property before getting into any GUI init code
//System.setProperty("com.apple.mrj.application.apple.menu.about.name", name);
// This )*)(*@#$ Apple crap don't work no matter where you put it
// (static method of the class, at the top of main, wherever)
if (displayDevice == null) {
GraphicsEnvironment environment =
GraphicsEnvironment.getLocalGraphicsEnvironment();
displayDevice = environment.getDefaultScreenDevice();
}
Frame frame = new Frame(displayDevice.getDefaultConfiguration());
// JFrame frame = new JFrame(displayDevice.getDefaultConfiguration());
/*
Frame frame = null;
if (displayDevice != null) {
frame = new Frame(displayDevice.getDefaultConfiguration());
} else {
frame = new Frame();
}
*/
//Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
// remove the grow box by default
// users who want it back can call frame.setResizable(true)
// frame.setResizable(false);
// moved later (issue #467)
final PApplet applet;
if (constructedApplet != null) {
applet = constructedApplet;
} else {
try {
Class<?> c = Thread.currentThread().getContextClassLoader().loadClass(name);
applet = (PApplet) c.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// Set the trimmings around the image
applet.setIconImage(frame);
frame.setTitle(name);
// frame.setIgnoreRepaint(true); // does nothing
// frame.addComponentListener(new ComponentAdapter() {
// public void componentResized(ComponentEvent e) {
// Component c = e.getComponent();
//// Rectangle bounds = c.getBounds();
// System.out.println(" " + c.getName() + " wants to be: " + c.getSize());
// }
// });
// frame.addComponentListener(new ComponentListener() {
//
// public void componentShown(ComponentEvent e) {
// debug("frame: " + e);
// debug(" applet valid? " + applet.isValid());
//// ((PGraphicsJava2D) applet.g).redraw();
// }
//
// public void componentResized(ComponentEvent e) {
// println("frame: " + e + " " + applet.frame.getInsets());
// Insets insets = applet.frame.getInsets();
// int wide = e.getComponent().getWidth() - (insets.left + insets.right);
// int high = e.getComponent().getHeight() - (insets.top + insets.bottom);
// if (applet.getWidth() != wide || applet.getHeight() != high) {
// debug("Frame.componentResized() setting applet size " + wide + " " + high);
// applet.setSize(wide, high);
// }
// }
//
// public void componentMoved(ComponentEvent e) {
// //println("frame: " + e + " " + applet.frame.getInsets());
// Insets insets = applet.frame.getInsets();
// int wide = e.getComponent().getWidth() - (insets.left + insets.right);
// int high = e.getComponent().getHeight() - (insets.top + insets.bottom);
// //applet.g.setsi
// if (applet.getWidth() != wide || applet.getHeight() != high) {
// debug("Frame.componentMoved() setting applet size " + wide + " " + high);
// applet.setSize(wide, high);
// }
// }
//
// public void componentHidden(ComponentEvent e) {
// debug("frame: " + e);
// }
// });
// A handful of things that need to be set before init/start.
applet.frame = frame;
applet.sketchPath = folder;
// If the applet doesn't call for full screen, but the command line does,
// enable it. Conversely, if the command line does not, don't disable it.
// applet.fullScreen |= present;
// Query the applet to see if it wants to be full screen all the time.
present |= applet.sketchFullScreen();
// pass everything after the class name in as args to the sketch itself
// (fixed for 2.0a5, this was just subsetting by 1, which didn't skip opts)
applet.args = PApplet.subset(args, argIndex + 1);
applet.external = external;
// Need to save the window bounds at full screen,
// because pack() will cause the bounds to go to zero.
// http://dev.processing.org/bugs/show_bug.cgi?id=923
Rectangle screenRect =
displayDevice.getDefaultConfiguration().getBounds();
// DisplayMode doesn't work here, because we can't get the upper-left
// corner of the display, which is important for multi-display setups.
// Sketch has already requested to be the same as the screen's
// width and height, so let's roll with full screen mode.
if (screenRect.width == applet.sketchWidth() &&
screenRect.height == applet.sketchHeight()) {
present = true;
}
// For 0149, moving this code (up to the pack() method) before init().
// For OpenGL (and perhaps other renderers in the future), a peer is
// needed before a GLDrawable can be created. So pack() needs to be
// called on the Frame before applet.init(), which itself calls size(),
// and launches the Thread that will kick off setup().
// http://dev.processing.org/bugs/show_bug.cgi?id=891
// http://dev.processing.org/bugs/show_bug.cgi?id=908
if (present) {
// if (platform == MACOSX) {
// // Call some native code to remove the menu bar on OS X. Not necessary
// // on Linux and Windows, who are happy to make full screen windows.
// japplemenubar.JAppleMenuBar.hide();
// }
frame.setUndecorated(true);
if (backgroundColor != null) {
frame.setBackground(backgroundColor);
}
// if (exclusive) {
// displayDevice.setFullScreenWindow(frame);
// // this trashes the location of the window on os x
// //frame.setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
// fullScreenRect = frame.getBounds();
// } else {
frame.setBounds(screenRect);
frame.setVisible(true);
// }
}
frame.setLayout(null);
frame.add(applet);
if (present) {
frame.invalidate();
} else {
frame.pack();
}
// insufficient, places the 100x100 sketches offset strangely
//frame.validate();
// disabling resize has to happen after pack() to avoid apparent Apple bug
// http://code.google.com/p/processing/issues/detail?id=467
frame.setResizable(false);
applet.init();
// applet.start();
// Wait until the applet has figured out its width.
// In a static mode app, this will be after setup() has completed,
// and the empty draw() has set "finished" to true.
// TODO make sure this won't hang if the applet has an exception.
while (applet.defaultSize && !applet.finished) {
//System.out.println("default size");
try {
Thread.sleep(5);
} catch (InterruptedException e) {
//System.out.println("interrupt");
}
}
// // If 'present' wasn't already set, but the applet initializes
// // to full screen, attempt to make things full screen anyway.
// if (!present &&
// applet.width == screenRect.width &&
// applet.height == screenRect.height) {
// // bounds will be set below, but can't change to setUndecorated() now
// present = true;
// }
// // Opting not to do this, because we can't remove the decorations on the
// // window at this point. And re-opening a new winodw is a lot of mess.
// // Better all around to just encourage the use of sketchFullScreen()
// // or cmd/ctrl-shift-R in the PDE.
if (present) {
if (platform == MACOSX) {
// Call some native code to remove the menu bar on OS X. Not necessary
// on Linux and Windows, who are happy to make full screen windows.
japplemenubar.JAppleMenuBar.hide();
}
// After the pack(), the screen bounds are gonna be 0s
frame.setBounds(screenRect);
applet.setBounds((screenRect.width - applet.width) / 2,
(screenRect.height - applet.height) / 2,
applet.width, applet.height);
if (!hideStop) {
Label label = new Label("stop");
label.setForeground(stopColor);
label.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(java.awt.event.MouseEvent e) {
System.exit(0);
}
});
frame.add(label);
Dimension labelSize = label.getPreferredSize();
// sometimes shows up truncated on mac
//System.out.println("label width is " + labelSize.width);
labelSize = new Dimension(100, labelSize.height);
label.setSize(labelSize);
label.setLocation(20, screenRect.height - labelSize.height - 20);
}
// not always running externally when in present mode
if (external) {
applet.setupExternalMessages();
}
} else { // if not presenting
// can't do pack earlier cuz present mode don't like it
// (can't go full screen with a frame after calling pack)
// frame.pack(); // get insets. get more.
Insets insets = frame.getInsets();
int windowW = Math.max(applet.width, MIN_WINDOW_WIDTH) +
insets.left + insets.right;
int windowH = Math.max(applet.height, MIN_WINDOW_HEIGHT) +
insets.top + insets.bottom;
frame.setSize(windowW, windowH);
if (location != null) {
// a specific location was received from the Runner
// (applet has been run more than once, user placed window)
frame.setLocation(location[0], location[1]);
} else if (external && editorLocation != null) {
int locationX = editorLocation[0] - 20;
int locationY = editorLocation[1];
if (locationX - windowW > 10) {
// if it fits to the left of the window
frame.setLocation(locationX - windowW, locationY);
} else { // doesn't fit
// if it fits inside the editor window,
// offset slightly from upper lefthand corner
// so that it's plunked inside the text area
locationX = editorLocation[0] + 66;
locationY = editorLocation[1] + 66;
if ((locationX + windowW > applet.displayWidth - 33) ||
(locationY + windowH > applet.displayHeight - 33)) {
// otherwise center on screen
locationX = (applet.displayWidth - windowW) / 2;
locationY = (applet.displayHeight - windowH) / 2;
}
frame.setLocation(locationX, locationY);
}
} else { // just center on screen
// Can't use frame.setLocationRelativeTo(null) because it sends the
// frame to the main display, which undermines the --display setting.
frame.setLocation(screenRect.x + (screenRect.width - applet.width) / 2,
screenRect.y + (screenRect.height - applet.height) / 2);
}
Point frameLoc = frame.getLocation();
if (frameLoc.y < 0) {
// Windows actually allows you to place frames where they can't be
// closed. Awesome. http://dev.processing.org/bugs/show_bug.cgi?id=1508
frame.setLocation(frameLoc.x, 30);
}
if (backgroundColor != null) {
// if (backgroundColor == Color.black) { //BLACK) {
// // this means no bg color unless specified
// backgroundColor = SystemColor.control;
// }
frame.setBackground(backgroundColor);
}
int usableWindowH = windowH - insets.top - insets.bottom;
applet.setBounds((windowW - applet.width)/2,
insets.top + (usableWindowH - applet.height)/2,
applet.width, applet.height);
if (external) {
applet.setupExternalMessages();
} else { // !external
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
}
// handle frame resizing events
applet.setupFrameResizeListener();
// all set for rockin
if (applet.displayable()) {
frame.setVisible(true);
}
}
// Disabling for 0185, because it causes an assertion failure on OS X
// http://code.google.com/p/processing/issues/detail?id=258
// (Although this doesn't seem to be the one that was causing problems.)
//applet.requestFocus(); // ask for keydowns
}
/**
* These methods provide a means for running an already-constructed
* sketch. In particular, it makes it easy to launch a sketch in
* Jython:
*
* <pre>class MySketch(PApplet):
* pass
*
*MySketch().runSketch();</pre>
*/
protected void runSketch(final String[] args) {
final String[] argsWithSketchName = new String[args.length + 1];
System.arraycopy(args, 0, argsWithSketchName, 0, args.length);
final String className = this.getClass().getSimpleName();
final String cleanedClass =
className.replaceAll("__[^_]+__\\$", "").replaceAll("\\$\\d+", "");
argsWithSketchName[args.length] = cleanedClass;
runSketch(argsWithSketchName, this);
}
protected void runSketch() {
runSketch(new String[0]);
}
//////////////////////////////////////////////////////////////
/**
* ( begin auto-generated from beginRecord.xml )
*
* Opens a new file and all subsequent drawing functions are echoed to this
* file as well as the display window. The <b>beginRecord()</b> function
* requires two parameters, the first is the renderer and the second is the
* file name. This function is always used with <b>endRecord()</b> to stop
* the recording process and close the file.
* <br /> <br />
* Note that beginRecord() will only pick up any settings that happen after
* it has been called. For instance, if you call textFont() before
* beginRecord(), then that font will not be set for the file that you're
* recording to.
*
* ( end auto-generated )
*
* @webref output:files
* @param renderer for example, PDF
* @param filename filename for output
* @see PApplet#endRecord()
*/
public PGraphics beginRecord(String renderer, String filename) {
filename = insertFrame(filename);
PGraphics rec = createGraphics(width, height, renderer, filename);
beginRecord(rec);
return rec;
}
/**
* @nowebref
* Begin recording (echoing) commands to the specified PGraphics object.
*/
public void beginRecord(PGraphics recorder) {
this.recorder = recorder;
recorder.beginDraw();
}
/**
* ( begin auto-generated from endRecord.xml )
*
* Stops the recording process started by <b>beginRecord()</b> and closes
* the file.
*
* ( end auto-generated )
* @webref output:files
* @see PApplet#beginRecord(String, String)
*/
public void endRecord() {
if (recorder != null) {
recorder.endDraw();
recorder.dispose();
recorder = null;
}
}
/**
* ( begin auto-generated from beginRaw.xml )
*
* To create vectors from 3D data, use the <b>beginRaw()</b> and
* <b>endRaw()</b> commands. These commands will grab the shape data just
* before it is rendered to the screen. At this stage, your entire scene is
* nothing but a long list of individual lines and triangles. This means
* that a shape created with <b>sphere()</b> function will be made up of
* hundreds of triangles, rather than a single object. Or that a
* multi-segment line shape (such as a curve) will be rendered as
* individual segments.
* <br /><br />
* When using <b>beginRaw()</b> and <b>endRaw()</b>, it's possible to write
* to either a 2D or 3D renderer. For instance, <b>beginRaw()</b> with the
* PDF library will write the geometry as flattened triangles and lines,
* even if recording from the <b>P3D</b> renderer.
* <br /><br />
* If you want a background to show up in your files, use <b>rect(0, 0,
* width, height)</b> after setting the <b>fill()</b> to the background
* color. Otherwise the background will not be rendered to the file because
* the background is not shape.
* <br /><br />
* Using <b>hint(ENABLE_DEPTH_SORT)</b> can improve the appearance of 3D
* geometry drawn to 2D file formats. See the <b>hint()</b> reference for
* more details.
* <br /><br />
* See examples in the reference for the <b>PDF</b> and <b>DXF</b>
* libraries for more information.
*
* ( end auto-generated )
*
* @webref output:files
* @param renderer for example, PDF or DXF
* @param filename filename for output
* @see PApplet#endRaw()
* @see PApplet#hint(int)
*/
public PGraphics beginRaw(String renderer, String filename) {
filename = insertFrame(filename);
PGraphics rec = createGraphics(width, height, renderer, filename);
g.beginRaw(rec);
return rec;
}
/**
* @nowebref
* Begin recording raw shape data to the specified renderer.
*
* This simply echoes to g.beginRaw(), but since is placed here (rather than
* generated by preproc.pl) for clarity and so that it doesn't echo the
* command should beginRecord() be in use.
*
* @param rawGraphics ???
*/
public void beginRaw(PGraphics rawGraphics) {
g.beginRaw(rawGraphics);
}
/**
* ( begin auto-generated from endRaw.xml )
*
* Complement to <b>beginRaw()</b>; they must always be used together. See
* the <b>beginRaw()</b> reference for details.
*
* ( end auto-generated )
*
* @webref output:files
* @see PApplet#beginRaw(String, String)
*/
public void endRaw() {
g.endRaw();
}
/**
* Starts shape recording and returns the PShape object that will
* contain the geometry.
*/
/*
public PShape beginRecord() {
return g.beginRecord();
}
*/
//////////////////////////////////////////////////////////////
/**
* ( begin auto-generated from loadPixels.xml )
*
* Loads the pixel data for the display window into the <b>pixels[]</b>
* array. This function must always be called before reading from or
* writing to <b>pixels[]</b>.
* <br/><br/> renderers may or may not seem to require <b>loadPixels()</b>
* or <b>updatePixels()</b>. However, the rule is that any time you want to
* manipulate the <b>pixels[]</b> array, you must first call
* <b>loadPixels()</b>, and after changes have been made, call
* <b>updatePixels()</b>. Even if the renderer may not seem to use this
* function in the current Processing release, this will always be subject
* to change.
*
* ( end auto-generated )
* <h3>Advanced</h3>
* Override the g.pixels[] function to set the pixels[] array
* that's part of the PApplet object. Allows the use of
* pixels[] in the code, rather than g.pixels[].
*
* @webref image:pixels
* @see PApplet#pixels
* @see PApplet#updatePixels()
*/
public void loadPixels() {
g.loadPixels();
pixels = g.pixels;
}
/**
* ( begin auto-generated from updatePixels.xml )
*
* Updates the display window with the data in the <b>pixels[]</b> array.
* Use in conjunction with <b>loadPixels()</b>. If you're only reading
* pixels from the array, there's no need to call <b>updatePixels()</b>
* unless there are changes.
* <br/><br/> renderers may or may not seem to require <b>loadPixels()</b>
* or <b>updatePixels()</b>. However, the rule is that any time you want to
* manipulate the <b>pixels[]</b> array, you must first call
* <b>loadPixels()</b>, and after changes have been made, call
* <b>updatePixels()</b>. Even if the renderer may not seem to use this
* function in the current Processing release, this will always be subject
* to change.
* <br/> <br/>
* Currently, none of the renderers use the additional parameters to
* <b>updatePixels()</b>, however this may be implemented in the future.
*
* ( end auto-generated )
* @webref image:pixels
* @see PApplet#loadPixels()
* @see PApplet#pixels
*/
public void updatePixels() {
g.updatePixels();
}
/**
* @nowebref
* @param x1 x-coordinate of the upper-left corner
* @param y1 y-coordinate of the upper-left corner
* @param x2 width of the region
* @param y2 height of the region
*/
public void updatePixels(int x1, int y1, int x2, int y2) {
g.updatePixels(x1, y1, x2, y2);
}
//////////////////////////////////////////////////////////////
// EVERYTHING BELOW THIS LINE IS AUTOMATICALLY GENERATED. DO NOT TOUCH!
// This includes the Javadoc comments, which are automatically copied from
// the PImage and PGraphics source code files.
// public functions for processing.core
/**
* Store data of some kind for the renderer that requires extra metadata of
* some kind. Usually this is a renderer-specific representation of the
* image data, for instance a BufferedImage with tint() settings applied for
* PGraphicsJava2D, or resized image data and OpenGL texture indices for
* PGraphicsOpenGL.
* @param renderer The PGraphics renderer associated to the image
* @param storage The metadata required by the renderer
*/
public void setCache(PImage image, Object storage) {
if (recorder != null) recorder.setCache(image, storage);
g.setCache(image, storage);
}
/**
* Get cache storage data for the specified renderer. Because each renderer
* will cache data in different formats, it's necessary to store cache data
* keyed by the renderer object. Otherwise, attempting to draw the same
* image to both a PGraphicsJava2D and a PGraphicsOpenGL will cause errors.
* @param renderer The PGraphics renderer associated to the image
* @return metadata stored for the specified renderer
*/
public Object getCache(PImage image) {
return g.getCache(image);
}
/**
* Remove information associated with this renderer from the cache, if any.
* @param renderer The PGraphics renderer whose cache data should be removed
*/
public void removeCache(PImage image) {
if (recorder != null) recorder.removeCache(image);
g.removeCache(image);
}
public PGL beginPGL() {
return g.beginPGL();
}
public void endPGL() {
if (recorder != null) recorder.endPGL();
g.endPGL();
}
public void flush() {
if (recorder != null) recorder.flush();
g.flush();
}
public void hint(int which) {
if (recorder != null) recorder.hint(which);
g.hint(which);
}
/**
* Start a new shape of type POLYGON
*/
public void beginShape() {
if (recorder != null) recorder.beginShape();
g.beginShape();
}
/**
* ( begin auto-generated from beginShape.xml )
*
* Using the <b>beginShape()</b> and <b>endShape()</b> functions allow
* creating more complex forms. <b>beginShape()</b> begins recording
* vertices for a shape and <b>endShape()</b> stops recording. The value of
* the <b>MODE</b> parameter tells it which types of shapes to create from
* the provided vertices. With no mode specified, the shape can be any
* irregular polygon. The parameters available for beginShape() are POINTS,
* LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, and QUAD_STRIP.
* After calling the <b>beginShape()</b> function, a series of
* <b>vertex()</b> commands must follow. To stop drawing the shape, call
* <b>endShape()</b>. The <b>vertex()</b> function with two parameters
* specifies a position in 2D and the <b>vertex()</b> function with three
* parameters specifies a position in 3D. Each shape will be outlined with
* the current stroke color and filled with the fill color.
* <br/> <br/>
* Transformations such as <b>translate()</b>, <b>rotate()</b>, and
* <b>scale()</b> do not work within <b>beginShape()</b>. It is also not
* possible to use other shapes, such as <b>ellipse()</b> or <b>rect()</b>
* within <b>beginShape()</b>.
* <br/> <br/>
* The P3D renderer settings allow <b>stroke()</b> and <b>fill()</b>
* settings to be altered per-vertex, however the default P2D renderer does
* not. Settings such as <b>strokeWeight()</b>, <b>strokeCap()</b>, and
* <b>strokeJoin()</b> cannot be changed while inside a
* <b>beginShape()</b>/<b>endShape()</b> block with any renderer.
*
* ( end auto-generated )
* @webref shape:vertex
* @param kind Either POINTS, LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, or QUAD_STRIP
* @see PGraphics#endShape()
* @see PGraphics#vertex(float, float, float, float, float)
* @see PGraphics#curveVertex(float, float, float)
* @see PGraphics#bezierVertex(float, float, float, float, float, float, float, float, float)
*/
public void beginShape(int kind) {
if (recorder != null) recorder.beginShape(kind);
g.beginShape(kind);
}
/**
* Sets whether the upcoming vertex is part of an edge.
* Equivalent to glEdgeFlag(), for people familiar with OpenGL.
*/
public void edge(boolean edge) {
if (recorder != null) recorder.edge(edge);
g.edge(edge);
}
/**
* ( begin auto-generated from normal.xml )
*
* Sets the current normal vector. This is for drawing three dimensional
* shapes and surfaces and specifies a vector perpendicular to the surface
* of the shape which determines how lighting affects it. Processing
* attempts to automatically assign normals to shapes, but since that's
* imperfect, this is a better option when you want more control. This
* function is identical to glNormal3f() in OpenGL.
*
* ( end auto-generated )
* @webref lights_camera:lights
* @param nx x direction
* @param ny y direction
* @param nz z direction
* @see PGraphics#beginShape(int)
* @see PGraphics#endShape(int)
* @see PGraphics#lights()
*/
public void normal(float nx, float ny, float nz) {
if (recorder != null) recorder.normal(nx, ny, nz);
g.normal(nx, ny, nz);
}
/**
* ( begin auto-generated from textureMode.xml )
*
* Sets the coordinate space for texture mapping. There are two options,
* IMAGE, which refers to the actual coordinates of the image, and
* NORMAL, which refers to a normalized space of values ranging from 0
* to 1. The default mode is IMAGE. In IMAGE, if an image is 100 x 200
* pixels, mapping the image onto the entire size of a quad would require
* the points (0,0) (0,100) (100,200) (0,200). The same mapping in
* NORMAL_SPACE is (0,0) (0,1) (1,1) (0,1).
*
* ( end auto-generated )
* @webref image:textures
* @param mode either IMAGE or NORMAL
* @see PGraphics#texture(PImage)
*/
public void textureMode(int mode) {
if (recorder != null) recorder.textureMode(mode);
g.textureMode(mode);
}
/**
* ( begin auto-generated from textureWrap.xml )
*
* Description to come...
*
* ( end auto-generated from textureWrap.xml )
*
* @webref image:textures
* @param wrap Either CLAMP (default) or REPEAT
*/
public void textureWrap(int wrap) {
if (recorder != null) recorder.textureWrap(wrap);
g.textureWrap(wrap);
}
/**
* ( begin auto-generated from texture.xml )
*
* Sets a texture to be applied to vertex points. The <b>texture()</b>
* function must be called between <b>beginShape()</b> and
* <b>endShape()</b> and before any calls to <b>vertex()</b>.
* <br/> <br/>
* When textures are in use, the fill color is ignored. Instead, use tint()
* to specify the color of the texture as it is applied to the shape.
*
* ( end auto-generated )
* @webref image:textures
* @param image reference to a PImage object
* @see PGraphics#textureMode(int)
* @see PGraphics#beginShape(int)
* @see PGraphics#endShape(int)
* @see PGraphics#vertex(float, float, float, float, float)
*/
public void texture(PImage image) {
if (recorder != null) recorder.texture(image);
g.texture(image);
}
/**
* Removes texture image for current shape.
* Needs to be called between beginShape and endShape
*
*/
public void noTexture() {
if (recorder != null) recorder.noTexture();
g.noTexture();
}
public void vertex(float x, float y) {
if (recorder != null) recorder.vertex(x, y);
g.vertex(x, y);
}
public void vertex(float x, float y, float z) {
if (recorder != null) recorder.vertex(x, y, z);
g.vertex(x, y, z);
}
/**
* Used by renderer subclasses or PShape to efficiently pass in already
* formatted vertex information.
* @param v vertex parameters, as a float array of length VERTEX_FIELD_COUNT
*/
public void vertex(float[] v) {
if (recorder != null) recorder.vertex(v);
g.vertex(v);
}
public void vertex(float x, float y, float u, float v) {
if (recorder != null) recorder.vertex(x, y, u, v);
g.vertex(x, y, u, v);
}
/**
* ( begin auto-generated from vertex.xml )
*
* All shapes are constructed by connecting a series of vertices.
* <b>vertex()</b> is used to specify the vertex coordinates for points,
* lines, triangles, quads, and polygons and is used exclusively within the
* <b>beginShape()</b> and <b>endShape()</b> function.<br />
* <br />
* Drawing a vertex in 3D using the <b>z</b> parameter requires the P3D
* parameter in combination with size as shown in the above example.<br />
* <br />
* This function is also used to map a texture onto the geometry. The
* <b>texture()</b> function declares the texture to apply to the geometry
* and the <b>u</b> and <b>v</b> coordinates set define the mapping of this
* texture to the form. By default, the coordinates used for <b>u</b> and
* <b>v</b> are specified in relation to the image's size in pixels, but
* this relation can be changed with <b>textureMode()</b>.
*
* ( end auto-generated )
* @webref shape:vertex
* @param x x-coordinate of the vertex
* @param y y-coordinate of the vertex
* @param z z-coordinate of the vertex
* @param u horizontal coordinate for the texture mapping
* @param v vertical coordinate for the texture mapping
* @see PGraphics#beginShape(int)
* @see PGraphics#endShape(int)
* @see PGraphics#bezierVertex(float, float, float, float, float, float, float, float, float)
* @see PGraphics#quadraticVertex(float, float, float, float, float, float)
* @see PGraphics#curveVertex(float, float, float)
* @see PGraphics#texture(PImage)
*/
public void vertex(float x, float y, float z, float u, float v) {
if (recorder != null) recorder.vertex(x, y, z, u, v);
g.vertex(x, y, z, u, v);
}
/**
* @webref shape:vertex
*/
public void beginContour() {
if (recorder != null) recorder.beginContour();
g.beginContour();
}
/**
* @webref shape:vertex
*/
public void endContour() {
if (recorder != null) recorder.endContour();
g.endContour();
}
public void endShape() {
if (recorder != null) recorder.endShape();
g.endShape();
}
/**
* ( begin auto-generated from endShape.xml )
*
* The <b>endShape()</b> function is the companion to <b>beginShape()</b>
* and may only be called after <b>beginShape()</b>. When <b>endshape()</b>
* is called, all of image data defined since the previous call to
* <b>beginShape()</b> is written into the image buffer. The constant CLOSE
* as the value for the MODE parameter to close the shape (to connect the
* beginning and the end).
*
* ( end auto-generated )
* @webref shape:vertex
* @param mode use CLOSE to close the shape
* @see PGraphics#beginShape(int)
*/
public void endShape(int mode) {
if (recorder != null) recorder.endShape(mode);
g.endShape(mode);
}
/**
* @webref shape
* @param filename name of file to load, can be .svg or .obj
* @see PShape
* @see PApplet#createShape()
*/
public PShape loadShape(String filename) {
return g.loadShape(filename);
}
public PShape loadShape(String filename, String options) {
return g.loadShape(filename, options);
}
/**
* @webref shape
* @see PShape
* @see PShape#endShape()
* @see PApplet#loadShape(String)
*/
public PShape createShape() {
return g.createShape();
}
public PShape createShape(PShape source) {
return g.createShape(source);
}
/**
* @param type either POINTS, LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, QUAD_STRIP
*/
public PShape createShape(int type) {
return g.createShape(type);
}
/**
* @param kind either LINE, TRIANGLE, RECT, ELLIPSE, ARC, SPHERE, BOX
* @param p parameters that match the kind of shape
*/
public PShape createShape(int kind, float... p) {
return g.createShape(kind, p);
}
/**
* ( begin auto-generated from loadShader.xml )
*
* This is a new reference entry for Processing 2.0. It will be updated shortly.
*
* ( end auto-generated )
*
* @webref rendering:shaders
* @param fragFilename name of fragment shader file
*/
public PShader loadShader(String fragFilename) {
return g.loadShader(fragFilename);
}
/**
* @param vertFilename name of vertex shader file
*/
public PShader loadShader(String fragFilename, String vertFilename) {
return g.loadShader(fragFilename, vertFilename);
}
/**
* ( begin auto-generated from shader.xml )
*
* This is a new reference entry for Processing 2.0. It will be updated shortly.
*
* ( end auto-generated )
*
* @webref rendering:shaders
* @param shader name of shader file
*/
public void shader(PShader shader) {
if (recorder != null) recorder.shader(shader);
g.shader(shader);
}
/**
* @param kind type of shader, either POINTS, LINES, or TRIANGLES
*/
public void shader(PShader shader, int kind) {
if (recorder != null) recorder.shader(shader, kind);
g.shader(shader, kind);
}
/**
* ( begin auto-generated from resetShader.xml )
*
* This is a new reference entry for Processing 2.0. It will be updated shortly.
*
* ( end auto-generated )
*
* @webref rendering:shaders
*/
public void resetShader() {
if (recorder != null) recorder.resetShader();
g.resetShader();
}
/**
* @param kind type of shader, either POINTS, LINES, or TRIANGLES
*/
public void resetShader(int kind) {
if (recorder != null) recorder.resetShader(kind);
g.resetShader(kind);
}
/**
* @param shader the fragment shader to apply
*/
public void filter(PShader shader) {
if (recorder != null) recorder.filter(shader);
g.filter(shader);
}
/*
* @webref rendering:shaders
* @param a x-coordinate of the rectangle by default
* @param b y-coordinate of the rectangle by default
* @param c width of the rectangle by default
* @param d height of the rectangle by default
*/
public void clip(float a, float b, float c, float d) {
if (recorder != null) recorder.clip(a, b, c, d);
g.clip(a, b, c, d);
}
/*
* @webref rendering:shaders
*/
public void noClip() {
if (recorder != null) recorder.noClip();
g.noClip();
}
/**
* ( begin auto-generated from blendMode.xml )
*
* This is a new reference entry for Processing 2.0. It will be updated shortly.
*
* ( end auto-generated )
*
* @webref Rendering
* @param mode the blending mode to use
*/
public void blendMode(int mode) {
if (recorder != null) recorder.blendMode(mode);
g.blendMode(mode);
}
public void bezierVertex(float x2, float y2,
float x3, float y3,
float x4, float y4) {
if (recorder != null) recorder.bezierVertex(x2, y2, x3, y3, x4, y4);
g.bezierVertex(x2, y2, x3, y3, x4, y4);
}
/**
* ( begin auto-generated from bezierVertex.xml )
*
* Specifies vertex coordinates for Bezier curves. Each call to
* <b>bezierVertex()</b> defines the position of two control points and one
* anchor point of a Bezier curve, adding a new segment to a line or shape.
* The first time <b>bezierVertex()</b> is used within a
* <b>beginShape()</b> call, it must be prefaced with a call to
* <b>vertex()</b> to set the first anchor point. This function must be
* used between <b>beginShape()</b> and <b>endShape()</b> and only when
* there is no MODE parameter specified to <b>beginShape()</b>. Using the
* 3D version requires rendering with P3D (see the Environment reference
* for more information).
*
* ( end auto-generated )
* @webref shape:vertex
* @param x2 the x-coordinate of the 1st control point
* @param y2 the y-coordinate of the 1st control point
* @param z2 the z-coordinate of the 1st control point
* @param x3 the x-coordinate of the 2nd control point
* @param y3 the y-coordinate of the 2nd control point
* @param z3 the z-coordinate of the 2nd control point
* @param x4 the x-coordinate of the anchor point
* @param y4 the y-coordinate of the anchor point
* @param z4 the z-coordinate of the anchor point
* @see PGraphics#curveVertex(float, float, float)
* @see PGraphics#vertex(float, float, float, float, float)
* @see PGraphics#quadraticVertex(float, float, float, float, float, float)
* @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
*/
public void bezierVertex(float x2, float y2, float z2,
float x3, float y3, float z3,
float x4, float y4, float z4) {
if (recorder != null) recorder.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4);
g.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4);
}
/**
* @webref shape:vertex
* @param cx the x-coordinate of the control point
* @param cy the y-coordinate of the control point
* @param x3 the x-coordinate of the anchor point
* @param y3 the y-coordinate of the anchor point
* @see PGraphics#curveVertex(float, float, float)
* @see PGraphics#vertex(float, float, float, float, float)
* @see PGraphics#bezierVertex(float, float, float, float, float, float)
* @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
*/
public void quadraticVertex(float cx, float cy,
float x3, float y3) {
if (recorder != null) recorder.quadraticVertex(cx, cy, x3, y3);
g.quadraticVertex(cx, cy, x3, y3);
}
/**
* @param cz the z-coordinate of the control point
* @param z3 the z-coordinate of the anchor point
*/
public void quadraticVertex(float cx, float cy, float cz,
float x3, float y3, float z3) {
if (recorder != null) recorder.quadraticVertex(cx, cy, cz, x3, y3, z3);
g.quadraticVertex(cx, cy, cz, x3, y3, z3);
}
/**
* ( begin auto-generated from curveVertex.xml )
*
* Specifies vertex coordinates for curves. This function may only be used
* between <b>beginShape()</b> and <b>endShape()</b> and only when there is
* no MODE parameter specified to <b>beginShape()</b>. The first and last
* points in a series of <b>curveVertex()</b> lines will be used to guide
* the beginning and end of a the curve. A minimum of four points is
* required to draw a tiny curve between the second and third points.
* Adding a fifth point with <b>curveVertex()</b> will draw the curve
* between the second, third, and fourth points. The <b>curveVertex()</b>
* function is an implementation of Catmull-Rom splines. Using the 3D
* version requires rendering with P3D (see the Environment reference for
* more information).
*
* ( end auto-generated )
*
* @webref shape:vertex
* @param x the x-coordinate of the vertex
* @param y the y-coordinate of the vertex
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#beginShape(int)
* @see PGraphics#endShape(int)
* @see PGraphics#vertex(float, float, float, float, float)
* @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#quadraticVertex(float, float, float, float, float, float)
*/
public void curveVertex(float x, float y) {
if (recorder != null) recorder.curveVertex(x, y);
g.curveVertex(x, y);
}
/**
* @param z the z-coordinate of the vertex
*/
public void curveVertex(float x, float y, float z) {
if (recorder != null) recorder.curveVertex(x, y, z);
g.curveVertex(x, y, z);
}
/**
* ( begin auto-generated from point.xml )
*
* Draws a point, a coordinate in space at the dimension of one pixel. The
* first parameter is the horizontal value for the point, the second value
* is the vertical value for the point, and the optional third value is the
* depth value. Drawing this shape in 3D with the <b>z</b> parameter
* requires the P3D parameter in combination with <b>size()</b> as shown in
* the above example.
*
* ( end auto-generated )
*
* @webref shape:2d_primitives
* @param x x-coordinate of the point
* @param y y-coordinate of the point
*/
public void point(float x, float y) {
if (recorder != null) recorder.point(x, y);
g.point(x, y);
}
/**
* @param z z-coordinate of the point
*/
public void point(float x, float y, float z) {
if (recorder != null) recorder.point(x, y, z);
g.point(x, y, z);
}
/**
* ( begin auto-generated from line.xml )
*
* Draws a line (a direct path between two points) to the screen. The
* version of <b>line()</b> with four parameters draws the line in 2D. To
* color a line, use the <b>stroke()</b> function. A line cannot be filled,
* therefore the <b>fill()</b> function will not affect the color of a
* line. 2D lines are drawn with a width of one pixel by default, but this
* can be changed with the <b>strokeWeight()</b> function. The version with
* six parameters allows the line to be placed anywhere within XYZ space.
* Drawing this shape in 3D with the <b>z</b> parameter requires the P3D
* parameter in combination with <b>size()</b> as shown in the above example.
*
* ( end auto-generated )
* @webref shape:2d_primitives
* @param x1 x-coordinate of the first point
* @param y1 y-coordinate of the first point
* @param x2 x-coordinate of the second point
* @param y2 y-coordinate of the second point
* @see PGraphics#strokeWeight(float)
* @see PGraphics#strokeJoin(int)
* @see PGraphics#strokeCap(int)
* @see PGraphics#beginShape()
*/
public void line(float x1, float y1, float x2, float y2) {
if (recorder != null) recorder.line(x1, y1, x2, y2);
g.line(x1, y1, x2, y2);
}
/**
* @param z1 z-coordinate of the first point
* @param z2 z-coordinate of the second point
*/
public void line(float x1, float y1, float z1,
float x2, float y2, float z2) {
if (recorder != null) recorder.line(x1, y1, z1, x2, y2, z2);
g.line(x1, y1, z1, x2, y2, z2);
}
/**
* ( begin auto-generated from triangle.xml )
*
* A triangle is a plane created by connecting three points. The first two
* arguments specify the first point, the middle two arguments specify the
* second point, and the last two arguments specify the third point.
*
* ( end auto-generated )
* @webref shape:2d_primitives
* @param x1 x-coordinate of the first point
* @param y1 y-coordinate of the first point
* @param x2 x-coordinate of the second point
* @param y2 y-coordinate of the second point
* @param x3 x-coordinate of the third point
* @param y3 y-coordinate of the third point
* @see PApplet#beginShape()
*/
public void triangle(float x1, float y1, float x2, float y2,
float x3, float y3) {
if (recorder != null) recorder.triangle(x1, y1, x2, y2, x3, y3);
g.triangle(x1, y1, x2, y2, x3, y3);
}
/**
* ( begin auto-generated from quad.xml )
*
* A quad is a quadrilateral, a four sided polygon. It is similar to a
* rectangle, but the angles between its edges are not constrained to
* ninety degrees. The first pair of parameters (x1,y1) sets the first
* vertex and the subsequent pairs should proceed clockwise or
* counter-clockwise around the defined shape.
*
* ( end auto-generated )
* @webref shape:2d_primitives
* @param x1 x-coordinate of the first corner
* @param y1 y-coordinate of the first corner
* @param x2 x-coordinate of the second corner
* @param y2 y-coordinate of the second corner
* @param x3 x-coordinate of the third corner
* @param y3 y-coordinate of the third corner
* @param x4 x-coordinate of the fourth corner
* @param y4 y-coordinate of the fourth corner
*/
public void quad(float x1, float y1, float x2, float y2,
float x3, float y3, float x4, float y4) {
if (recorder != null) recorder.quad(x1, y1, x2, y2, x3, y3, x4, y4);
g.quad(x1, y1, x2, y2, x3, y3, x4, y4);
}
/**
* ( begin auto-generated from rectMode.xml )
*
* Modifies the location from which rectangles draw. The default mode is
* <b>rectMode(CORNER)</b>, which specifies the location to be the upper
* left corner of the shape and uses the third and fourth parameters of
* <b>rect()</b> to specify the width and height. The syntax
* <b>rectMode(CORNERS)</b> uses the first and second parameters of
* <b>rect()</b> to set the location of one corner and uses the third and
* fourth parameters to set the opposite corner. The syntax
* <b>rectMode(CENTER)</b> draws the image from its center point and uses
* the third and forth parameters of <b>rect()</b> to specify the image's
* width and height. The syntax <b>rectMode(RADIUS)</b> draws the image
* from its center point and uses the third and forth parameters of
* <b>rect()</b> to specify half of the image's width and height. The
* parameter must be written in ALL CAPS because Processing is a case
* sensitive language. Note: In version 125, the mode named CENTER_RADIUS
* was shortened to RADIUS.
*
* ( end auto-generated )
* @webref shape:attributes
* @param mode either CORNER, CORNERS, CENTER, or RADIUS
* @see PGraphics#rect(float, float, float, float)
*/
public void rectMode(int mode) {
if (recorder != null) recorder.rectMode(mode);
g.rectMode(mode);
}
/**
* ( begin auto-generated from rect.xml )
*
* Draws a rectangle to the screen. A rectangle is a four-sided shape with
* every angle at ninety degrees. By default, the first two parameters set
* the location of the upper-left corner, the third sets the width, and the
* fourth sets the height. These parameters may be changed with the
* <b>rectMode()</b> function.
*
* ( end auto-generated )
*
* @webref shape:2d_primitives
* @param a x-coordinate of the rectangle by default
* @param b y-coordinate of the rectangle by default
* @param c width of the rectangle by default
* @param d height of the rectangle by default
* @see PGraphics#rectMode(int)
* @see PGraphics#quad(float, float, float, float, float, float, float, float)
*/
public void rect(float a, float b, float c, float d) {
if (recorder != null) recorder.rect(a, b, c, d);
g.rect(a, b, c, d);
}
/**
* @param r radii for all four corners
*/
public void rect(float a, float b, float c, float d, float r) {
if (recorder != null) recorder.rect(a, b, c, d, r);
g.rect(a, b, c, d, r);
}
/**
* @param tl radius for top-left corner
* @param tr radius for top-right corner
* @param br radius for bottom-right corner
* @param bl radius for bottom-left corner
*/
public void rect(float a, float b, float c, float d,
float tl, float tr, float br, float bl) {
if (recorder != null) recorder.rect(a, b, c, d, tl, tr, br, bl);
g.rect(a, b, c, d, tl, tr, br, bl);
}
/**
* ( begin auto-generated from ellipseMode.xml )
*
* The origin of the ellipse is modified by the <b>ellipseMode()</b>
* function. The default configuration is <b>ellipseMode(CENTER)</b>, which
* specifies the location of the ellipse as the center of the shape. The
* <b>RADIUS</b> mode is the same, but the width and height parameters to
* <b>ellipse()</b> specify the radius of the ellipse, rather than the
* diameter. The <b>CORNER</b> mode draws the shape from the upper-left
* corner of its bounding box. The <b>CORNERS</b> mode uses the four
* parameters to <b>ellipse()</b> to set two opposing corners of the
* ellipse's bounding box. The parameter must be written in ALL CAPS
* because Processing is a case-sensitive language.
*
* ( end auto-generated )
* @webref shape:attributes
* @param mode either CENTER, RADIUS, CORNER, or CORNERS
* @see PApplet#ellipse(float, float, float, float)
* @see PApplet#arc(float, float, float, float, float, float)
*/
public void ellipseMode(int mode) {
if (recorder != null) recorder.ellipseMode(mode);
g.ellipseMode(mode);
}
/**
* ( begin auto-generated from ellipse.xml )
*
* Draws an ellipse (oval) in the display window. An ellipse with an equal
* <b>width</b> and <b>height</b> is a circle. The first two parameters set
* the location, the third sets the width, and the fourth sets the height.
* The origin may be changed with the <b>ellipseMode()</b> function.
*
* ( end auto-generated )
* @webref shape:2d_primitives
* @param a x-coordinate of the ellipse
* @param b y-coordinate of the ellipse
* @param c width of the ellipse by default
* @param d height of the ellipse by default
* @see PApplet#ellipseMode(int)
* @see PApplet#arc(float, float, float, float, float, float)
*/
public void ellipse(float a, float b, float c, float d) {
if (recorder != null) recorder.ellipse(a, b, c, d);
g.ellipse(a, b, c, d);
}
/**
* ( begin auto-generated from arc.xml )
*
* Draws an arc in the display window. Arcs are drawn along the outer edge
* of an ellipse defined by the <b>x</b>, <b>y</b>, <b>width</b> and
* <b>height</b> parameters. The origin or the arc's ellipse may be changed
* with the <b>ellipseMode()</b> function. The <b>start</b> and <b>stop</b>
* parameters specify the angles at which to draw the arc.
*
* ( end auto-generated )
* @webref shape:2d_primitives
* @param a x-coordinate of the arc's ellipse
* @param b y-coordinate of the arc's ellipse
* @param c width of the arc's ellipse by default
* @param d height of the arc's ellipse by default
* @param start angle to start the arc, specified in radians
* @param stop angle to stop the arc, specified in radians
* @see PApplet#ellipse(float, float, float, float)
* @see PApplet#ellipseMode(int)
* @see PApplet#radians(float)
* @see PApplet#degrees(float)
*/
public void arc(float a, float b, float c, float d,
float start, float stop) {
if (recorder != null) recorder.arc(a, b, c, d, start, stop);
g.arc(a, b, c, d, start, stop);
}
/*
* @param mode either OPEN, CHORD, or PIE
*/
public void arc(float a, float b, float c, float d,
float start, float stop, int mode) {
if (recorder != null) recorder.arc(a, b, c, d, start, stop, mode);
g.arc(a, b, c, d, start, stop, mode);
}
/**
* ( begin auto-generated from box.xml )
*
* A box is an extruded rectangle. A box with equal dimension on all sides
* is a cube.
*
* ( end auto-generated )
*
* @webref shape:3d_primitives
* @param size dimension of the box in all dimensions (creates a cube)
* @see PGraphics#sphere(float)
*/
public void box(float size) {
if (recorder != null) recorder.box(size);
g.box(size);
}
/**
* @param w dimension of the box in the x-dimension
* @param h dimension of the box in the y-dimension
* @param d dimension of the box in the z-dimension
*/
public void box(float w, float h, float d) {
if (recorder != null) recorder.box(w, h, d);
g.box(w, h, d);
}
/**
* ( begin auto-generated from sphereDetail.xml )
*
* Controls the detail used to render a sphere by adjusting the number of
* vertices of the sphere mesh. The default resolution is 30, which creates
* a fairly detailed sphere definition with vertices every 360/30 = 12
* degrees. If you're going to render a great number of spheres per frame,
* it is advised to reduce the level of detail using this function. The
* setting stays active until <b>sphereDetail()</b> is called again with a
* new parameter and so should <i>not</i> be called prior to every
* <b>sphere()</b> statement, unless you wish to render spheres with
* different settings, e.g. using less detail for smaller spheres or ones
* further away from the camera. To control the detail of the horizontal
* and vertical resolution independently, use the version of the functions
* with two parameters.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Code for sphereDetail() submitted by toxi [031031].
* Code for enhanced u/v version from davbol [080801].
*
* @param res number of segments (minimum 3) used per full circle revolution
* @webref shape:3d_primitives
* @see PGraphics#sphere(float)
*/
public void sphereDetail(int res) {
if (recorder != null) recorder.sphereDetail(res);
g.sphereDetail(res);
}
/**
* @param ures number of segments used longitudinally per full circle revolutoin
* @param vres number of segments used latitudinally from top to bottom
*/
public void sphereDetail(int ures, int vres) {
if (recorder != null) recorder.sphereDetail(ures, vres);
g.sphereDetail(ures, vres);
}
/**
* ( begin auto-generated from sphere.xml )
*
* A sphere is a hollow ball made from tessellated triangles.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* <P>
* Implementation notes:
* <P>
* cache all the points of the sphere in a static array
* top and bottom are just a bunch of triangles that land
* in the center point
* <P>
* sphere is a series of concentric circles who radii vary
* along the shape, based on, er.. cos or something
* <PRE>
* [toxi 031031] new sphere code. removed all multiplies with
* radius, as scale() will take care of that anyway
*
* [toxi 031223] updated sphere code (removed modulos)
* and introduced sphereAt(x,y,z,r)
* to avoid additional translate()'s on the user/sketch side
*
* [davbol 080801] now using separate sphereDetailU/V
* </PRE>
*
* @webref shape:3d_primitives
* @param r the radius of the sphere
* @see PGraphics#sphereDetail(int)
*/
public void sphere(float r) {
if (recorder != null) recorder.sphere(r);
g.sphere(r);
}
/**
* ( begin auto-generated from bezierPoint.xml )
*
* Evaluates the Bezier at point t for points a, b, c, d. The parameter t
* varies between 0 and 1, a and d are points on the curve, and b and c are
* the control points. This can be done once with the x coordinates and a
* second time with the y coordinates to get the location of a bezier curve
* at t.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* For instance, to convert the following example:<PRE>
* stroke(255, 102, 0);
* line(85, 20, 10, 10);
* line(90, 90, 15, 80);
* stroke(0, 0, 0);
* bezier(85, 20, 10, 10, 90, 90, 15, 80);
*
* // draw it in gray, using 10 steps instead of the default 20
* // this is a slower way to do it, but useful if you need
* // to do things with the coordinates at each step
* stroke(128);
* beginShape(LINE_STRIP);
* for (int i = 0; i <= 10; i++) {
* float t = i / 10.0f;
* float x = bezierPoint(85, 10, 90, 15, t);
* float y = bezierPoint(20, 10, 90, 80, t);
* vertex(x, y);
* }
* endShape();</PRE>
*
* @webref shape:curves
* @param a coordinate of first point on the curve
* @param b coordinate of first control point
* @param c coordinate of second control point
* @param d coordinate of second point on the curve
* @param t value between 0 and 1
* @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#bezierVertex(float, float, float, float, float, float)
* @see PGraphics#curvePoint(float, float, float, float, float)
*/
public float bezierPoint(float a, float b, float c, float d, float t) {
return g.bezierPoint(a, b, c, d, t);
}
/**
* ( begin auto-generated from bezierTangent.xml )
*
* Calculates the tangent of a point on a Bezier curve. There is a good
* definition of <a href="http://en.wikipedia.org/wiki/Tangent"
* target="new"><em>tangent</em> on Wikipedia</a>.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Code submitted by Dave Bollinger (davol) for release 0136.
*
* @webref shape:curves
* @param a coordinate of first point on the curve
* @param b coordinate of first control point
* @param c coordinate of second control point
* @param d coordinate of second point on the curve
* @param t value between 0 and 1
* @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#bezierVertex(float, float, float, float, float, float)
* @see PGraphics#curvePoint(float, float, float, float, float)
*/
public float bezierTangent(float a, float b, float c, float d, float t) {
return g.bezierTangent(a, b, c, d, t);
}
/**
* ( begin auto-generated from bezierDetail.xml )
*
* Sets the resolution at which Beziers display. The default value is 20.
* This function is only useful when using the P3D renderer as the default
* P2D renderer does not use this information.
*
* ( end auto-generated )
*
* @webref shape:curves
* @param detail resolution of the curves
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#curveVertex(float, float, float)
* @see PGraphics#curveTightness(float)
*/
public void bezierDetail(int detail) {
if (recorder != null) recorder.bezierDetail(detail);
g.bezierDetail(detail);
}
public void bezier(float x1, float y1,
float x2, float y2,
float x3, float y3,
float x4, float y4) {
if (recorder != null) recorder.bezier(x1, y1, x2, y2, x3, y3, x4, y4);
g.bezier(x1, y1, x2, y2, x3, y3, x4, y4);
}
/**
* ( begin auto-generated from bezier.xml )
*
* Draws a Bezier curve on the screen. These curves are defined by a series
* of anchor and control points. The first two parameters specify the first
* anchor point and the last two parameters specify the other anchor point.
* The middle parameters specify the control points which define the shape
* of the curve. Bezier curves were developed by French engineer Pierre
* Bezier. Using the 3D version requires rendering with P3D (see the
* Environment reference for more information).
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Draw a cubic bezier curve. The first and last points are
* the on-curve points. The middle two are the 'control' points,
* or 'handles' in an application like Illustrator.
* <P>
* Identical to typing:
* <PRE>beginShape();
* vertex(x1, y1);
* bezierVertex(x2, y2, x3, y3, x4, y4);
* endShape();
* </PRE>
* In Postscript-speak, this would be:
* <PRE>moveto(x1, y1);
* curveto(x2, y2, x3, y3, x4, y4);</PRE>
* If you were to try and continue that curve like so:
* <PRE>curveto(x5, y5, x6, y6, x7, y7);</PRE>
* This would be done in processing by adding these statements:
* <PRE>bezierVertex(x5, y5, x6, y6, x7, y7)
* </PRE>
* To draw a quadratic (instead of cubic) curve,
* use the control point twice by doubling it:
* <PRE>bezier(x1, y1, cx, cy, cx, cy, x2, y2);</PRE>
*
* @webref shape:curves
* @param x1 coordinates for the first anchor point
* @param y1 coordinates for the first anchor point
* @param z1 coordinates for the first anchor point
* @param x2 coordinates for the first control point
* @param y2 coordinates for the first control point
* @param z2 coordinates for the first control point
* @param x3 coordinates for the second control point
* @param y3 coordinates for the second control point
* @param z3 coordinates for the second control point
* @param x4 coordinates for the second anchor point
* @param y4 coordinates for the second anchor point
* @param z4 coordinates for the second anchor point
*
* @see PGraphics#bezierVertex(float, float, float, float, float, float)
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
*/
public void bezier(float x1, float y1, float z1,
float x2, float y2, float z2,
float x3, float y3, float z3,
float x4, float y4, float z4) {
if (recorder != null) recorder.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
g.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
}
/**
* ( begin auto-generated from curvePoint.xml )
*
* Evalutes the curve at point t for points a, b, c, d. The parameter t
* varies between 0 and 1, a and d are points on the curve, and b and c are
* the control points. This can be done once with the x coordinates and a
* second time with the y coordinates to get the location of a curve at t.
*
* ( end auto-generated )
*
* @webref shape:curves
* @param a coordinate of first point on the curve
* @param b coordinate of second point on the curve
* @param c coordinate of third point on the curve
* @param d coordinate of fourth point on the curve
* @param t value between 0 and 1
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#curveVertex(float, float)
* @see PGraphics#bezierPoint(float, float, float, float, float)
*/
public float curvePoint(float a, float b, float c, float d, float t) {
return g.curvePoint(a, b, c, d, t);
}
/**
* ( begin auto-generated from curveTangent.xml )
*
* Calculates the tangent of a point on a curve. There's a good definition
* of <em><a href="http://en.wikipedia.org/wiki/Tangent"
* target="new">tangent</em> on Wikipedia</a>.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Code thanks to Dave Bollinger (Bug #715)
*
* @webref shape:curves
* @param a coordinate of first point on the curve
* @param b coordinate of first control point
* @param c coordinate of second control point
* @param d coordinate of second point on the curve
* @param t value between 0 and 1
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#curveVertex(float, float)
* @see PGraphics#curvePoint(float, float, float, float, float)
* @see PGraphics#bezierTangent(float, float, float, float, float)
*/
public float curveTangent(float a, float b, float c, float d, float t) {
return g.curveTangent(a, b, c, d, t);
}
/**
* ( begin auto-generated from curveDetail.xml )
*
* Sets the resolution at which curves display. The default value is 20.
* This function is only useful when using the P3D renderer as the default
* P2D renderer does not use this information.
*
* ( end auto-generated )
*
* @webref shape:curves
* @param detail resolution of the curves
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#curveVertex(float, float)
* @see PGraphics#curveTightness(float)
*/
public void curveDetail(int detail) {
if (recorder != null) recorder.curveDetail(detail);
g.curveDetail(detail);
}
/**
* ( begin auto-generated from curveTightness.xml )
*
* Modifies the quality of forms created with <b>curve()</b> and
* <b>curveVertex()</b>. The parameter <b>squishy</b> determines how the
* curve fits to the vertex points. The value 0.0 is the default value for
* <b>squishy</b> (this value defines the curves to be Catmull-Rom splines)
* and the value 1.0 connects all the points with straight lines. Values
* within the range -5.0 and 5.0 will deform the curves but will leave them
* recognizable and as values increase in magnitude, they will continue to deform.
*
* ( end auto-generated )
*
* @webref shape:curves
* @param tightness amount of deformation from the original vertices
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#curveVertex(float, float)
*/
public void curveTightness(float tightness) {
if (recorder != null) recorder.curveTightness(tightness);
g.curveTightness(tightness);
}
/**
* ( begin auto-generated from curve.xml )
*
* Draws a curved line on the screen. The first and second parameters
* specify the beginning control point and the last two parameters specify
* the ending control point. The middle parameters specify the start and
* stop of the curve. Longer curves can be created by putting a series of
* <b>curve()</b> functions together or using <b>curveVertex()</b>. An
* additional function called <b>curveTightness()</b> provides control for
* the visual quality of the curve. The <b>curve()</b> function is an
* implementation of Catmull-Rom splines. Using the 3D version requires
* rendering with P3D (see the Environment reference for more information).
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* As of revision 0070, this function no longer doubles the first
* and last points. The curves are a bit more boring, but it's more
* mathematically correct, and properly mirrored in curvePoint().
* <P>
* Identical to typing out:<PRE>
* beginShape();
* curveVertex(x1, y1);
* curveVertex(x2, y2);
* curveVertex(x3, y3);
* curveVertex(x4, y4);
* endShape();
* </PRE>
*
* @webref shape:curves
* @param x1 coordinates for the beginning control point
* @param y1 coordinates for the beginning control point
* @param x2 coordinates for the first point
* @param y2 coordinates for the first point
* @param x3 coordinates for the second point
* @param y3 coordinates for the second point
* @param x4 coordinates for the ending control point
* @param y4 coordinates for the ending control point
* @see PGraphics#curveVertex(float, float)
* @see PGraphics#curveTightness(float)
* @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
*/
public void curve(float x1, float y1,
float x2, float y2,
float x3, float y3,
float x4, float y4) {
if (recorder != null) recorder.curve(x1, y1, x2, y2, x3, y3, x4, y4);
g.curve(x1, y1, x2, y2, x3, y3, x4, y4);
}
/**
* @param z1 coordinates for the beginning control point
* @param z2 coordinates for the first point
* @param z3 coordinates for the second point
* @param z4 coordinates for the ending control point
*/
public void curve(float x1, float y1, float z1,
float x2, float y2, float z2,
float x3, float y3, float z3,
float x4, float y4, float z4) {
if (recorder != null) recorder.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
g.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
}
/**
* ( begin auto-generated from smooth.xml )
*
* Draws all geometry with smooth (anti-aliased) edges. This will sometimes
* slow down the frame rate of the application, but will enhance the visual
* refinement. Note that <b>smooth()</b> will also improve image quality of
* resized images, and <b>noSmooth()</b> will disable image (and font)
* smoothing altogether.
*
* ( end auto-generated )
*
* @webref shape:attributes
* @see PGraphics#noSmooth()
* @see PGraphics#hint(int)
* @see PApplet#size(int, int, String)
*/
public void smooth() {
if (recorder != null) recorder.smooth();
g.smooth();
}
/**
*
* @param level either 2, 4, or 8
*/
public void smooth(int level) {
if (recorder != null) recorder.smooth(level);
g.smooth(level);
}
/**
* ( begin auto-generated from noSmooth.xml )
*
* Draws all geometry with jagged (aliased) edges.
*
* ( end auto-generated )
* @webref shape:attributes
* @see PGraphics#smooth()
*/
public void noSmooth() {
if (recorder != null) recorder.noSmooth();
g.noSmooth();
}
/**
* ( begin auto-generated from imageMode.xml )
*
* Modifies the location from which images draw. The default mode is
* <b>imageMode(CORNER)</b>, which specifies the location to be the upper
* left corner and uses the fourth and fifth parameters of <b>image()</b>
* to set the image's width and height. The syntax
* <b>imageMode(CORNERS)</b> uses the second and third parameters of
* <b>image()</b> to set the location of one corner of the image and uses
* the fourth and fifth parameters to set the opposite corner. Use
* <b>imageMode(CENTER)</b> to draw images centered at the given x and y
* position.<br />
* <br />
* The parameter to <b>imageMode()</b> must be written in ALL CAPS because
* Processing is a case-sensitive language.
*
* ( end auto-generated )
*
* @webref image:loading_displaying
* @param mode either CORNER, CORNERS, or CENTER
* @see PApplet#loadImage(String, String)
* @see PImage
* @see PGraphics#image(PImage, float, float, float, float)
* @see PGraphics#background(float, float, float, float)
*/
public void imageMode(int mode) {
if (recorder != null) recorder.imageMode(mode);
g.imageMode(mode);
}
/**
* ( begin auto-generated from image.xml )
*
* Displays images to the screen. The images must be in the sketch's "data"
* directory to load correctly. Select "Add file..." from the "Sketch" menu
* to add the image. Processing currently works with GIF, JPEG, and Targa
* images. The <b>img</b> parameter specifies the image to display and the
* <b>x</b> and <b>y</b> parameters define the location of the image from
* its upper-left corner. The image is displayed at its original size
* unless the <b>width</b> and <b>height</b> parameters specify a different
* size.<br />
* <br />
* The <b>imageMode()</b> function changes the way the parameters work. For
* example, a call to <b>imageMode(CORNERS)</b> will change the
* <b>width</b> and <b>height</b> parameters to define the x and y values
* of the opposite corner of the image.<br />
* <br />
* The color of an image may be modified with the <b>tint()</b> function.
* This function will maintain transparency for GIF and PNG images.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Starting with release 0124, when using the default (JAVA2D) renderer,
* smooth() will also improve image quality of resized images.
*
* @webref image:loading_displaying
* @param img the image to display
* @param a x-coordinate of the image
* @param b y-coordinate of the image
* @see PApplet#loadImage(String, String)
* @see PImage
* @see PGraphics#imageMode(int)
* @see PGraphics#tint(float)
* @see PGraphics#background(float, float, float, float)
* @see PGraphics#alpha(int)
*/
public void image(PImage img, float a, float b) {
if (recorder != null) recorder.image(img, a, b);
g.image(img, a, b);
}
/**
* @param c width to display the image
* @param d height to display the image
*/
public void image(PImage img, float a, float b, float c, float d) {
if (recorder != null) recorder.image(img, a, b, c, d);
g.image(img, a, b, c, d);
}
/**
* Draw an image(), also specifying u/v coordinates.
* In this method, the u, v coordinates are always based on image space
* location, regardless of the current textureMode().
*
* @nowebref
*/
public void image(PImage img,
float a, float b, float c, float d,
int u1, int v1, int u2, int v2) {
if (recorder != null) recorder.image(img, a, b, c, d, u1, v1, u2, v2);
g.image(img, a, b, c, d, u1, v1, u2, v2);
}
/**
* ( begin auto-generated from shapeMode.xml )
*
* Modifies the location from which shapes draw. The default mode is
* <b>shapeMode(CORNER)</b>, which specifies the location to be the upper
* left corner of the shape and uses the third and fourth parameters of
* <b>shape()</b> to specify the width and height. The syntax
* <b>shapeMode(CORNERS)</b> uses the first and second parameters of
* <b>shape()</b> to set the location of one corner and uses the third and
* fourth parameters to set the opposite corner. The syntax
* <b>shapeMode(CENTER)</b> draws the shape from its center point and uses
* the third and forth parameters of <b>shape()</b> to specify the width
* and height. The parameter must be written in "ALL CAPS" because
* Processing is a case sensitive language.
*
* ( end auto-generated )
*
* @webref shape:loading_displaying
* @param mode either CORNER, CORNERS, CENTER
* @see PGraphics#shape(PShape)
* @see PGraphics#rectMode(int)
*/
public void shapeMode(int mode) {
if (recorder != null) recorder.shapeMode(mode);
g.shapeMode(mode);
}
public void shape(PShape shape) {
if (recorder != null) recorder.shape(shape);
g.shape(shape);
}
/**
* ( begin auto-generated from shape.xml )
*
* Displays shapes to the screen. The shapes must be in the sketch's "data"
* directory to load correctly. Select "Add file..." from the "Sketch" menu
* to add the shape. Processing currently works with SVG shapes only. The
* <b>sh</b> parameter specifies the shape to display and the <b>x</b> and
* <b>y</b> parameters define the location of the shape from its upper-left
* corner. The shape is displayed at its original size unless the
* <b>width</b> and <b>height</b> parameters specify a different size. The
* <b>shapeMode()</b> function changes the way the parameters work. A call
* to <b>shapeMode(CORNERS)</b>, for example, will change the width and
* height parameters to define the x and y values of the opposite corner of
* the shape.
* <br /><br />
* Note complex shapes may draw awkwardly with P3D. This renderer does not
* yet support shapes that have holes or complicated breaks.
*
* ( end auto-generated )
*
* @webref shape:loading_displaying
* @param shape the shape to display
* @param x x-coordinate of the shape
* @param y y-coordinate of the shape
* @see PShape
* @see PApplet#loadShape(String)
* @see PGraphics#shapeMode(int)
*
* Convenience method to draw at a particular location.
*/
public void shape(PShape shape, float x, float y) {
if (recorder != null) recorder.shape(shape, x, y);
g.shape(shape, x, y);
}
/**
* @param a x-coordinate of the shape
* @param b y-coordinate of the shape
* @param c width to display the shape
* @param d height to display the shape
*/
public void shape(PShape shape, float a, float b, float c, float d) {
if (recorder != null) recorder.shape(shape, a, b, c, d);
g.shape(shape, a, b, c, d);
}
public void textAlign(int alignX) {
if (recorder != null) recorder.textAlign(alignX);
g.textAlign(alignX);
}
/**
* ( begin auto-generated from textAlign.xml )
*
* Sets the current alignment for drawing text. The parameters LEFT,
* CENTER, and RIGHT set the display characteristics of the letters in
* relation to the values for the <b>x</b> and <b>y</b> parameters of the
* <b>text()</b> function.
* <br/> <br/>
* In Processing 0125 and later, an optional second parameter can be used
* to vertically align the text. BASELINE is the default, and the vertical
* alignment will be reset to BASELINE if the second parameter is not used.
* The TOP and CENTER parameters are straightforward. The BOTTOM parameter
* offsets the line based on the current <b>textDescent()</b>. For multiple
* lines, the final line will be aligned to the bottom, with the previous
* lines appearing above it.
* <br/> <br/>
* When using <b>text()</b> with width and height parameters, BASELINE is
* ignored, and treated as TOP. (Otherwise, text would by default draw
* outside the box, since BASELINE is the default setting. BASELINE is not
* a useful drawing mode for text drawn in a rectangle.)
* <br/> <br/>
* The vertical alignment is based on the value of <b>textAscent()</b>,
* which many fonts do not specify correctly. It may be necessary to use a
* hack and offset by a few pixels by hand so that the offset looks
* correct. To do this as less of a hack, use some percentage of
* <b>textAscent()</b> or <b>textDescent()</b> so that the hack works even
* if you change the size of the font.
*
* ( end auto-generated )
*
* @webref typography:attributes
* @param alignX horizontal alignment, either LEFT, CENTER, or RIGHT
* @param alignY vertical alignment, either TOP, BOTTOM, CENTER, or BASELINE
* @see PApplet#loadFont(String)
* @see PFont
* @see PGraphics#text(String, float, float)
*/
public void textAlign(int alignX, int alignY) {
if (recorder != null) recorder.textAlign(alignX, alignY);
g.textAlign(alignX, alignY);
}
/**
* ( begin auto-generated from textAscent.xml )
*
* Returns ascent of the current font at its current size. This information
* is useful for determining the height of the font above the baseline. For
* example, adding the <b>textAscent()</b> and <b>textDescent()</b> values
* will give you the total height of the line.
*
* ( end auto-generated )
*
* @webref typography:metrics
* @see PGraphics#textDescent()
*/
public float textAscent() {
return g.textAscent();
}
/**
* ( begin auto-generated from textDescent.xml )
*
* Returns descent of the current font at its current size. This
* information is useful for determining the height of the font below the
* baseline. For example, adding the <b>textAscent()</b> and
* <b>textDescent()</b> values will give you the total height of the line.
*
* ( end auto-generated )
*
* @webref typography:metrics
* @see PGraphics#textAscent()
*/
public float textDescent() {
return g.textDescent();
}
/**
* ( begin auto-generated from textFont.xml )
*
* Sets the current font that will be drawn with the <b>text()</b>
* function. Fonts must be loaded with <b>loadFont()</b> before it can be
* used. This font will be used in all subsequent calls to the
* <b>text()</b> function. If no <b>size</b> parameter is input, the font
* will appear at its original size (the size it was created at with the
* "Create Font..." tool) until it is changed with <b>textSize()</b>. <br
* /> <br /> Because fonts are usually bitmaped, you should create fonts at
* the sizes that will be used most commonly. Using <b>textFont()</b>
* without the size parameter will result in the cleanest-looking text. <br
* /><br /> With the default (JAVA2D) and PDF renderers, it's also possible
* to enable the use of native fonts via the command
* <b>hint(ENABLE_NATIVE_FONTS)</b>. This will produce vector text in
* JAVA2D sketches and PDF output in cases where the vector data is
* available: when the font is still installed, or the font is created via
* the <b>createFont()</b> function (rather than the Create Font tool).
*
* ( end auto-generated )
*
* @webref typography:loading_displaying
* @param which any variable of the type PFont
* @see PApplet#createFont(String, float, boolean)
* @see PApplet#loadFont(String)
* @see PFont#PFont
* @see PGraphics#text(String, float, float)
*/
public void textFont(PFont which) {
if (recorder != null) recorder.textFont(which);
g.textFont(which);
}
/**
* @param size the size of the letters in units of pixels
*/
public void textFont(PFont which, float size) {
if (recorder != null) recorder.textFont(which, size);
g.textFont(which, size);
}
/**
* ( begin auto-generated from textLeading.xml )
*
* Sets the spacing between lines of text in units of pixels. This setting
* will be used in all subsequent calls to the <b>text()</b> function.
*
* ( end auto-generated )
*
* @webref typography:attributes
* @param leading the size in pixels for spacing between lines
* @see PApplet#loadFont(String)
* @see PFont#PFont
* @see PGraphics#text(String, float, float)
* @see PGraphics#textFont(PFont)
*/
public void textLeading(float leading) {
if (recorder != null) recorder.textLeading(leading);
g.textLeading(leading);
}
/**
* ( begin auto-generated from textMode.xml )
*
* Sets the way text draws to the screen. In the default configuration, the
* <b>MODEL</b> mode, it's possible to rotate, scale, and place letters in
* two and three dimensional space.<br />
* <br />
* The <b>SHAPE</b> mode draws text using the the glyph outlines of
* individual characters rather than as textures. This mode is only
* supported with the <b>PDF</b> and <b>P3D</b> renderer settings. With the
* <b>PDF</b> renderer, you must call <b>textMode(SHAPE)</b> before any
* other drawing occurs. If the outlines are not available, then
* <b>textMode(SHAPE)</b> will be ignored and <b>textMode(MODEL)</b> will
* be used instead.<br />
* <br />
* The <b>textMode(SHAPE)</b> option in <b>P3D</b> can be combined with
* <b>beginRaw()</b> to write vector-accurate text to 2D and 3D output
* files, for instance <b>DXF</b> or <b>PDF</b>. The <b>SHAPE</b> mode is
* not currently optimized for <b>P3D</b>, so if recording shape data, use
* <b>textMode(MODEL)</b> until you're ready to capture the geometry with <b>beginRaw()</b>.
*
* ( end auto-generated )
*
* @webref typography:attributes
* @param mode either MODEL or SHAPE
* @see PApplet#loadFont(String)
* @see PFont#PFont
* @see PGraphics#text(String, float, float)
* @see PGraphics#textFont(PFont)
* @see PGraphics#beginRaw(PGraphics)
* @see PApplet#createFont(String, float, boolean)
*/
public void textMode(int mode) {
if (recorder != null) recorder.textMode(mode);
g.textMode(mode);
}
/**
* ( begin auto-generated from textSize.xml )
*
* Sets the current font size. This size will be used in all subsequent
* calls to the <b>text()</b> function. Font size is measured in units of pixels.
*
* ( end auto-generated )
*
* @webref typography:attributes
* @param size the size of the letters in units of pixels
* @see PApplet#loadFont(String)
* @see PFont#PFont
* @see PGraphics#text(String, float, float)
* @see PGraphics#textFont(PFont)
*/
public void textSize(float size) {
if (recorder != null) recorder.textSize(size);
g.textSize(size);
}
/**
* @param c the character to measure
*/
public float textWidth(char c) {
return g.textWidth(c);
}
/**
* ( begin auto-generated from textWidth.xml )
*
* Calculates and returns the width of any character or text string.
*
* ( end auto-generated )
*
* @webref typography:attributes
* @param str the String of characters to measure
* @see PApplet#loadFont(String)
* @see PFont#PFont
* @see PGraphics#text(String, float, float)
* @see PGraphics#textFont(PFont)
*/
public float textWidth(String str) {
return g.textWidth(str);
}
/**
* @nowebref
*/
public float textWidth(char[] chars, int start, int length) {
return g.textWidth(chars, start, length);
}
/**
* ( begin auto-generated from text.xml )
*
* Draws text to the screen. Displays the information specified in the
* <b>data</b> or <b>stringdata</b> parameters on the screen in the
* position specified by the <b>x</b> and <b>y</b> parameters and the
* optional <b>z</b> parameter. A default font will be used unless a font
* is set with the <b>textFont()</b> function. Change the color of the text
* with the <b>fill()</b> function. The text displays in relation to the
* <b>textAlign()</b> function, which gives the option to draw to the left,
* right, and center of the coordinates.
* <br /><br />
* The <b>x2</b> and <b>y2</b> parameters define a rectangular area to
* display within and may only be used with string data. For text drawn
* inside a rectangle, the coordinates are interpreted based on the current
* <b>rectMode()</b> setting.
*
* ( end auto-generated )
*
* @webref typography:loading_displaying
* @param c the alphanumeric character to be displayed
* @param x x-coordinate of text
* @param y y-coordinate of text
* @see PGraphics#textAlign(int, int)
* @see PGraphics#textMode(int)
* @see PApplet#loadFont(String)
* @see PGraphics#textFont(PFont)
* @see PGraphics#rectMode(int)
* @see PGraphics#fill(int, float)
* @see_external String
*/
public void text(char c, float x, float y) {
if (recorder != null) recorder.text(c, x, y);
g.text(c, x, y);
}
/**
* @param z z-coordinate of text
*/
public void text(char c, float x, float y, float z) {
if (recorder != null) recorder.text(c, x, y, z);
g.text(c, x, y, z);
}
/**
* <h3>Advanced</h3>
* Draw a chunk of text.
* Newlines that are \n (Unix newline or linefeed char, ascii 10)
* are honored, but \r (carriage return, Windows and Mac OS) are
* ignored.
*/
public void text(String str, float x, float y) {
if (recorder != null) recorder.text(str, x, y);
g.text(str, x, y);
}
/**
* <h3>Advanced</h3>
* Method to draw text from an array of chars. This method will usually be
* more efficient than drawing from a String object, because the String will
* not be converted to a char array before drawing.
* @param chars the alphanumberic symbols to be displayed
* @param start array index at which to start writing characters
* @param stop array index at which to stop writing characters
*/
public void text(char[] chars, int start, int stop, float x, float y) {
if (recorder != null) recorder.text(chars, start, stop, x, y);
g.text(chars, start, stop, x, y);
}
/**
* Same as above but with a z coordinate.
*/
public void text(String str, float x, float y, float z) {
if (recorder != null) recorder.text(str, x, y, z);
g.text(str, x, y, z);
}
public void text(char[] chars, int start, int stop,
float x, float y, float z) {
if (recorder != null) recorder.text(chars, start, stop, x, y, z);
g.text(chars, start, stop, x, y, z);
}
/**
* <h3>Advanced</h3>
* Draw text in a box that is constrained to a particular size.
* The current rectMode() determines what the coordinates mean
* (whether x1/y1/x2/y2 or x/y/w/h).
* <P/>
* Note that the x,y coords of the start of the box
* will align with the *ascent* of the text, not the baseline,
* as is the case for the other text() functions.
* <P/>
* Newlines that are \n (Unix newline or linefeed char, ascii 10)
* are honored, and \r (carriage return, Windows and Mac OS) are
* ignored.
*
* @param x1 by default, the x-coordinate of text, see rectMode() for more info
* @param y1 by default, the x-coordinate of text, see rectMode() for more info
* @param x2 by default, the width of the text box, see rectMode() for more info
* @param y2 by default, the height of the text box, see rectMode() for more info
*/
public void text(String str, float x1, float y1, float x2, float y2) {
if (recorder != null) recorder.text(str, x1, y1, x2, y2);
g.text(str, x1, y1, x2, y2);
}
public void text(int num, float x, float y) {
if (recorder != null) recorder.text(num, x, y);
g.text(num, x, y);
}
public void text(int num, float x, float y, float z) {
if (recorder != null) recorder.text(num, x, y, z);
g.text(num, x, y, z);
}
/**
* This does a basic number formatting, to avoid the
* generally ugly appearance of printing floats.
* Users who want more control should use their own nf() cmmand,
* or if they want the long, ugly version of float,
* use String.valueOf() to convert the float to a String first.
*
* @param num the numeric value to be displayed
*/
public void text(float num, float x, float y) {
if (recorder != null) recorder.text(num, x, y);
g.text(num, x, y);
}
public void text(float num, float x, float y, float z) {
if (recorder != null) recorder.text(num, x, y, z);
g.text(num, x, y, z);
}
/**
* ( begin auto-generated from pushMatrix.xml )
*
* Pushes the current transformation matrix onto the matrix stack.
* Understanding <b>pushMatrix()</b> and <b>popMatrix()</b> requires
* understanding the concept of a matrix stack. The <b>pushMatrix()</b>
* function saves the current coordinate system to the stack and
* <b>popMatrix()</b> restores the prior coordinate system.
* <b>pushMatrix()</b> and <b>popMatrix()</b> are used in conjuction with
* the other transformation functions and may be embedded to control the
* scope of the transformations.
*
* ( end auto-generated )
*
* @webref transform
* @see PGraphics#popMatrix()
* @see PGraphics#translate(float, float, float)
* @see PGraphics#rotate(float)
* @see PGraphics#rotateX(float)
* @see PGraphics#rotateY(float)
* @see PGraphics#rotateZ(float)
*/
public void pushMatrix() {
if (recorder != null) recorder.pushMatrix();
g.pushMatrix();
}
/**
* ( begin auto-generated from popMatrix.xml )
*
* Pops the current transformation matrix off the matrix stack.
* Understanding pushing and popping requires understanding the concept of
* a matrix stack. The <b>pushMatrix()</b> function saves the current
* coordinate system to the stack and <b>popMatrix()</b> restores the prior
* coordinate system. <b>pushMatrix()</b> and <b>popMatrix()</b> are used
* in conjuction with the other transformation functions and may be
* embedded to control the scope of the transformations.
*
* ( end auto-generated )
*
* @webref transform
* @see PGraphics#pushMatrix()
*/
public void popMatrix() {
if (recorder != null) recorder.popMatrix();
g.popMatrix();
}
/**
* ( begin auto-generated from translate.xml )
*
* Specifies an amount to displace objects within the display window. The
* <b>x</b> parameter specifies left/right translation, the <b>y</b>
* parameter specifies up/down translation, and the <b>z</b> parameter
* specifies translations toward/away from the screen. Using this function
* with the <b>z</b> parameter requires using P3D as a parameter in
* combination with size as shown in the above example. Transformations
* apply to everything that happens after and subsequent calls to the
* function accumulates the effect. For example, calling <b>translate(50,
* 0)</b> and then <b>translate(20, 0)</b> is the same as <b>translate(70,
* 0)</b>. If <b>translate()</b> is called within <b>draw()</b>, the
* transformation is reset when the loop begins again. This function can be
* further controlled by the <b>pushMatrix()</b> and <b>popMatrix()</b>.
*
* ( end auto-generated )
*
* @webref transform
* @param x left/right translation
* @param y up/down translation
* @see PGraphics#popMatrix()
* @see PGraphics#pushMatrix()
* @see PGraphics#rotate(float)
* @see PGraphics#rotateX(float)
* @see PGraphics#rotateY(float)
* @see PGraphics#rotateZ(float)
* @see PGraphics#scale(float, float, float)
*/
public void translate(float x, float y) {
if (recorder != null) recorder.translate(x, y);
g.translate(x, y);
}
/**
* @param z forward/backward translation
*/
public void translate(float x, float y, float z) {
if (recorder != null) recorder.translate(x, y, z);
g.translate(x, y, z);
}
/**
* ( begin auto-generated from rotate.xml )
*
* Rotates a shape the amount specified by the <b>angle</b> parameter.
* Angles should be specified in radians (values from 0 to TWO_PI) or
* converted to radians with the <b>radians()</b> function.
* <br/> <br/>
* Objects are always rotated around their relative position to the origin
* and positive numbers rotate objects in a clockwise direction.
* Transformations apply to everything that happens after and subsequent
* calls to the function accumulates the effect. For example, calling
* <b>rotate(HALF_PI)</b> and then <b>rotate(HALF_PI)</b> is the same as
* <b>rotate(PI)</b>. All tranformations are reset when <b>draw()</b>
* begins again.
* <br/> <br/>
* Technically, <b>rotate()</b> multiplies the current transformation
* matrix by a rotation matrix. This function can be further controlled by
* the <b>pushMatrix()</b> and <b>popMatrix()</b>.
*
* ( end auto-generated )
*
* @webref transform
* @param angle angle of rotation specified in radians
* @see PGraphics#popMatrix()
* @see PGraphics#pushMatrix()
* @see PGraphics#rotateX(float)
* @see PGraphics#rotateY(float)
* @see PGraphics#rotateZ(float)
* @see PGraphics#scale(float, float, float)
* @see PApplet#radians(float)
*/
public void rotate(float angle) {
if (recorder != null) recorder.rotate(angle);
g.rotate(angle);
}
/**
* ( begin auto-generated from rotateX.xml )
*
* Rotates a shape around the x-axis the amount specified by the
* <b>angle</b> parameter. Angles should be specified in radians (values
* from 0 to PI*2) or converted to radians with the <b>radians()</b>
* function. Objects are always rotated around their relative position to
* the origin and positive numbers rotate objects in a counterclockwise
* direction. Transformations apply to everything that happens after and
* subsequent calls to the function accumulates the effect. For example,
* calling <b>rotateX(PI/2)</b> and then <b>rotateX(PI/2)</b> is the same
* as <b>rotateX(PI)</b>. If <b>rotateX()</b> is called within the
* <b>draw()</b>, the transformation is reset when the loop begins again.
* This function requires using P3D as a third parameter to <b>size()</b>
* as shown in the example above.
*
* ( end auto-generated )
*
* @webref transform
* @param angle angle of rotation specified in radians
* @see PGraphics#popMatrix()
* @see PGraphics#pushMatrix()
* @see PGraphics#rotate(float)
* @see PGraphics#rotateY(float)
* @see PGraphics#rotateZ(float)
* @see PGraphics#scale(float, float, float)
* @see PGraphics#translate(float, float, float)
*/
public void rotateX(float angle) {
if (recorder != null) recorder.rotateX(angle);
g.rotateX(angle);
}
/**
* ( begin auto-generated from rotateY.xml )
*
* Rotates a shape around the y-axis the amount specified by the
* <b>angle</b> parameter. Angles should be specified in radians (values
* from 0 to PI*2) or converted to radians with the <b>radians()</b>
* function. Objects are always rotated around their relative position to
* the origin and positive numbers rotate objects in a counterclockwise
* direction. Transformations apply to everything that happens after and
* subsequent calls to the function accumulates the effect. For example,
* calling <b>rotateY(PI/2)</b> and then <b>rotateY(PI/2)</b> is the same
* as <b>rotateY(PI)</b>. If <b>rotateY()</b> is called within the
* <b>draw()</b>, the transformation is reset when the loop begins again.
* This function requires using P3D as a third parameter to <b>size()</b>
* as shown in the examples above.
*
* ( end auto-generated )
*
* @webref transform
* @param angle angle of rotation specified in radians
* @see PGraphics#popMatrix()
* @see PGraphics#pushMatrix()
* @see PGraphics#rotate(float)
* @see PGraphics#rotateX(float)
* @see PGraphics#rotateZ(float)
* @see PGraphics#scale(float, float, float)
* @see PGraphics#translate(float, float, float)
*/
public void rotateY(float angle) {
if (recorder != null) recorder.rotateY(angle);
g.rotateY(angle);
}
/**
* ( begin auto-generated from rotateZ.xml )
*
* Rotates a shape around the z-axis the amount specified by the
* <b>angle</b> parameter. Angles should be specified in radians (values
* from 0 to PI*2) or converted to radians with the <b>radians()</b>
* function. Objects are always rotated around their relative position to
* the origin and positive numbers rotate objects in a counterclockwise
* direction. Transformations apply to everything that happens after and
* subsequent calls to the function accumulates the effect. For example,
* calling <b>rotateZ(PI/2)</b> and then <b>rotateZ(PI/2)</b> is the same
* as <b>rotateZ(PI)</b>. If <b>rotateZ()</b> is called within the
* <b>draw()</b>, the transformation is reset when the loop begins again.
* This function requires using P3D as a third parameter to <b>size()</b>
* as shown in the examples above.
*
* ( end auto-generated )
*
* @webref transform
* @param angle angle of rotation specified in radians
* @see PGraphics#popMatrix()
* @see PGraphics#pushMatrix()
* @see PGraphics#rotate(float)
* @see PGraphics#rotateX(float)
* @see PGraphics#rotateY(float)
* @see PGraphics#scale(float, float, float)
* @see PGraphics#translate(float, float, float)
*/
public void rotateZ(float angle) {
if (recorder != null) recorder.rotateZ(angle);
g.rotateZ(angle);
}
/**
* <h3>Advanced</h3>
* Rotate about a vector in space. Same as the glRotatef() function.
* @param x
* @param y
* @param z
*/
public void rotate(float angle, float x, float y, float z) {
if (recorder != null) recorder.rotate(angle, x, y, z);
g.rotate(angle, x, y, z);
}
/**
* ( begin auto-generated from scale.xml )
*
* Increases or decreases the size of a shape by expanding and contracting
* vertices. Objects always scale from their relative origin to the
* coordinate system. Scale values are specified as decimal percentages.
* For example, the function call <b>scale(2.0)</b> increases the dimension
* of a shape by 200%. Transformations apply to everything that happens
* after and subsequent calls to the function multiply the effect. For
* example, calling <b>scale(2.0)</b> and then <b>scale(1.5)</b> is the
* same as <b>scale(3.0)</b>. If <b>scale()</b> is called within
* <b>draw()</b>, the transformation is reset when the loop begins again.
* Using this fuction with the <b>z</b> parameter requires using P3D as a
* parameter for <b>size()</b> as shown in the example above. This function
* can be further controlled by <b>pushMatrix()</b> and <b>popMatrix()</b>.
*
* ( end auto-generated )
*
* @webref transform
* @param s percentage to scale the object
* @see PGraphics#pushMatrix()
* @see PGraphics#popMatrix()
* @see PGraphics#translate(float, float, float)
* @see PGraphics#rotate(float)
* @see PGraphics#rotateX(float)
* @see PGraphics#rotateY(float)
* @see PGraphics#rotateZ(float)
*/
public void scale(float s) {
if (recorder != null) recorder.scale(s);
g.scale(s);
}
/**
* <h3>Advanced</h3>
* Scale in X and Y. Equivalent to scale(sx, sy, 1).
*
* Not recommended for use in 3D, because the z-dimension is just
* scaled by 1, since there's no way to know what else to scale it by.
*
* @param x percentage to scale the object in the x-axis
* @param y percentage to scale the object in the y-axis
*/
public void scale(float x, float y) {
if (recorder != null) recorder.scale(x, y);
g.scale(x, y);
}
/**
* @param z percentage to scale the object in the z-axis
*/
public void scale(float x, float y, float z) {
if (recorder != null) recorder.scale(x, y, z);
g.scale(x, y, z);
}
/**
* ( begin auto-generated from shearX.xml )
*
* Shears a shape around the x-axis the amount specified by the
* <b>angle</b> parameter. Angles should be specified in radians (values
* from 0 to PI*2) or converted to radians with the <b>radians()</b>
* function. Objects are always sheared around their relative position to
* the origin and positive numbers shear objects in a clockwise direction.
* Transformations apply to everything that happens after and subsequent
* calls to the function accumulates the effect. For example, calling
* <b>shearX(PI/2)</b> and then <b>shearX(PI/2)</b> is the same as
* <b>shearX(PI)</b>. If <b>shearX()</b> is called within the
* <b>draw()</b>, the transformation is reset when the loop begins again.
* <br/> <br/>
* Technically, <b>shearX()</b> multiplies the current transformation
* matrix by a rotation matrix. This function can be further controlled by
* the <b>pushMatrix()</b> and <b>popMatrix()</b> functions.
*
* ( end auto-generated )
*
* @webref transform
* @param angle angle of shear specified in radians
* @see PGraphics#popMatrix()
* @see PGraphics#pushMatrix()
* @see PGraphics#shearY(float)
* @see PGraphics#scale(float, float, float)
* @see PGraphics#translate(float, float, float)
* @see PApplet#radians(float)
*/
public void shearX(float angle) {
if (recorder != null) recorder.shearX(angle);
g.shearX(angle);
}
/**
* ( begin auto-generated from shearY.xml )
*
* Shears a shape around the y-axis the amount specified by the
* <b>angle</b> parameter. Angles should be specified in radians (values
* from 0 to PI*2) or converted to radians with the <b>radians()</b>
* function. Objects are always sheared around their relative position to
* the origin and positive numbers shear objects in a clockwise direction.
* Transformations apply to everything that happens after and subsequent
* calls to the function accumulates the effect. For example, calling
* <b>shearY(PI/2)</b> and then <b>shearY(PI/2)</b> is the same as
* <b>shearY(PI)</b>. If <b>shearY()</b> is called within the
* <b>draw()</b>, the transformation is reset when the loop begins again.
* <br/> <br/>
* Technically, <b>shearY()</b> multiplies the current transformation
* matrix by a rotation matrix. This function can be further controlled by
* the <b>pushMatrix()</b> and <b>popMatrix()</b> functions.
*
* ( end auto-generated )
*
* @webref transform
* @param angle angle of shear specified in radians
* @see PGraphics#popMatrix()
* @see PGraphics#pushMatrix()
* @see PGraphics#shearX(float)
* @see PGraphics#scale(float, float, float)
* @see PGraphics#translate(float, float, float)
* @see PApplet#radians(float)
*/
public void shearY(float angle) {
if (recorder != null) recorder.shearY(angle);
g.shearY(angle);
}
/**
* ( begin auto-generated from resetMatrix.xml )
*
* Replaces the current matrix with the identity matrix. The equivalent
* function in OpenGL is glLoadIdentity().
*
* ( end auto-generated )
*
* @webref transform
* @see PGraphics#pushMatrix()
* @see PGraphics#popMatrix()
* @see PGraphics#applyMatrix(PMatrix)
* @see PGraphics#printMatrix()
*/
public void resetMatrix() {
if (recorder != null) recorder.resetMatrix();
g.resetMatrix();
}
/**
* ( begin auto-generated from applyMatrix.xml )
*
* Multiplies the current matrix by the one specified through the
* parameters. This is very slow because it will try to calculate the
* inverse of the transform, so avoid it whenever possible. The equivalent
* function in OpenGL is glMultMatrix().
*
* ( end auto-generated )
*
* @webref transform
* @source
* @see PGraphics#pushMatrix()
* @see PGraphics#popMatrix()
* @see PGraphics#resetMatrix()
* @see PGraphics#printMatrix()
*/
public void applyMatrix(PMatrix source) {
if (recorder != null) recorder.applyMatrix(source);
g.applyMatrix(source);
}
public void applyMatrix(PMatrix2D source) {
if (recorder != null) recorder.applyMatrix(source);
g.applyMatrix(source);
}
/**
* @param n00 numbers which define the 4x4 matrix to be multiplied
* @param n01 numbers which define the 4x4 matrix to be multiplied
* @param n02 numbers which define the 4x4 matrix to be multiplied
* @param n10 numbers which define the 4x4 matrix to be multiplied
* @param n11 numbers which define the 4x4 matrix to be multiplied
* @param n12 numbers which define the 4x4 matrix to be multiplied
*/
public void applyMatrix(float n00, float n01, float n02,
float n10, float n11, float n12) {
if (recorder != null) recorder.applyMatrix(n00, n01, n02, n10, n11, n12);
g.applyMatrix(n00, n01, n02, n10, n11, n12);
}
public void applyMatrix(PMatrix3D source) {
if (recorder != null) recorder.applyMatrix(source);
g.applyMatrix(source);
}
/**
* @param n03 numbers which define the 4x4 matrix to be multiplied
* @param n13 numbers which define the 4x4 matrix to be multiplied
* @param n20 numbers which define the 4x4 matrix to be multiplied
* @param n21 numbers which define the 4x4 matrix to be multiplied
* @param n22 numbers which define the 4x4 matrix to be multiplied
* @param n23 numbers which define the 4x4 matrix to be multiplied
* @param n30 numbers which define the 4x4 matrix to be multiplied
* @param n31 numbers which define the 4x4 matrix to be multiplied
* @param n32 numbers which define the 4x4 matrix to be multiplied
* @param n33 numbers which define the 4x4 matrix to be multiplied
*/
public void applyMatrix(float n00, float n01, float n02, float n03,
float n10, float n11, float n12, float n13,
float n20, float n21, float n22, float n23,
float n30, float n31, float n32, float n33) {
if (recorder != null) recorder.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33);
g.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33);
}
public PMatrix getMatrix() {
return g.getMatrix();
}
/**
* Copy the current transformation matrix into the specified target.
* Pass in null to create a new matrix.
*/
public PMatrix2D getMatrix(PMatrix2D target) {
return g.getMatrix(target);
}
/**
* Copy the current transformation matrix into the specified target.
* Pass in null to create a new matrix.
*/
public PMatrix3D getMatrix(PMatrix3D target) {
return g.getMatrix(target);
}
/**
* Set the current transformation matrix to the contents of another.
*/
public void setMatrix(PMatrix source) {
if (recorder != null) recorder.setMatrix(source);
g.setMatrix(source);
}
/**
* Set the current transformation to the contents of the specified source.
*/
public void setMatrix(PMatrix2D source) {
if (recorder != null) recorder.setMatrix(source);
g.setMatrix(source);
}
/**
* Set the current transformation to the contents of the specified source.
*/
public void setMatrix(PMatrix3D source) {
if (recorder != null) recorder.setMatrix(source);
g.setMatrix(source);
}
/**
* ( begin auto-generated from printMatrix.xml )
*
* Prints the current matrix to the Console (the text window at the bottom
* of Processing).
*
* ( end auto-generated )
*
* @webref transform
* @see PGraphics#pushMatrix()
* @see PGraphics#popMatrix()
* @see PGraphics#resetMatrix()
* @see PGraphics#applyMatrix(PMatrix)
*/
public void printMatrix() {
if (recorder != null) recorder.printMatrix();
g.printMatrix();
}
/**
* ( begin auto-generated from beginCamera.xml )
*
* The <b>beginCamera()</b> and <b>endCamera()</b> functions enable
* advanced customization of the camera space. The functions are useful if
* you want to more control over camera movement, however for most users,
* the <b>camera()</b> function will be sufficient.<br /><br />The camera
* functions will replace any transformations (such as <b>rotate()</b> or
* <b>translate()</b>) that occur before them in <b>draw()</b>, but they
* will not automatically replace the camera transform itself. For this
* reason, camera functions should be placed at the beginning of
* <b>draw()</b> (so that transformations happen afterwards), and the
* <b>camera()</b> function can be used after <b>beginCamera()</b> if you
* want to reset the camera before applying transformations.<br /><br
* />This function sets the matrix mode to the camera matrix so calls such
* as <b>translate()</b>, <b>rotate()</b>, applyMatrix() and resetMatrix()
* affect the camera. <b>beginCamera()</b> should always be used with a
* following <b>endCamera()</b> and pairs of <b>beginCamera()</b> and
* <b>endCamera()</b> cannot be nested.
*
* ( end auto-generated )
*
* @webref lights_camera:camera
* @see PGraphics#camera()
* @see PGraphics#endCamera()
* @see PGraphics#applyMatrix(PMatrix)
* @see PGraphics#resetMatrix()
* @see PGraphics#translate(float, float, float)
* @see PGraphics#scale(float, float, float)
*/
public void beginCamera() {
if (recorder != null) recorder.beginCamera();
g.beginCamera();
}
/**
* ( begin auto-generated from endCamera.xml )
*
* The <b>beginCamera()</b> and <b>endCamera()</b> functions enable
* advanced customization of the camera space. Please see the reference for
* <b>beginCamera()</b> for a description of how the functions are used.
*
* ( end auto-generated )
*
* @webref lights_camera:camera
* @see PGraphics#camera(float, float, float, float, float, float, float, float, float)
*/
public void endCamera() {
if (recorder != null) recorder.endCamera();
g.endCamera();
}
/**
* ( begin auto-generated from camera.xml )
*
* Sets the position of the camera through setting the eye position, the
* center of the scene, and which axis is facing upward. Moving the eye
* position and the direction it is pointing (the center of the scene)
* allows the images to be seen from different angles. The version without
* any parameters sets the camera to the default position, pointing to the
* center of the display window with the Y axis as up. The default values
* are <b>camera(width/2.0, height/2.0, (height/2.0) / tan(PI*30.0 /
* 180.0), width/2.0, height/2.0, 0, 0, 1, 0)</b>. This function is similar
* to <b>gluLookAt()</b> in OpenGL, but it first clears the current camera settings.
*
* ( end auto-generated )
*
* @webref lights_camera:camera
* @see PGraphics#endCamera()
* @see PGraphics#frustum(float, float, float, float, float, float)
*/
public void camera() {
if (recorder != null) recorder.camera();
g.camera();
}
/**
* @param eyeX x-coordinate for the eye
* @param eyeY y-coordinate for the eye
* @param eyeZ z-coordinate for the eye
* @param centerX x-coordinate for the center of the scene
* @param centerY y-coordinate for the center of the scene
* @param centerZ z-coordinate for the center of the scene
* @param upX usually 0.0, 1.0, or -1.0
* @param upY usually 0.0, 1.0, or -1.0
* @param upZ usually 0.0, 1.0, or -1.0
*/
public void camera(float eyeX, float eyeY, float eyeZ,
float centerX, float centerY, float centerZ,
float upX, float upY, float upZ) {
if (recorder != null) recorder.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ);
g.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ);
}
/**
* ( begin auto-generated from printCamera.xml )
*
* Prints the current camera matrix to the Console (the text window at the
* bottom of Processing).
*
* ( end auto-generated )
* @webref lights_camera:camera
* @see PGraphics#camera(float, float, float, float, float, float, float, float, float)
*/
public void printCamera() {
if (recorder != null) recorder.printCamera();
g.printCamera();
}
/**
* ( begin auto-generated from ortho.xml )
*
* Sets an orthographic projection and defines a parallel clipping volume.
* All objects with the same dimension appear the same size, regardless of
* whether they are near or far from the camera. The parameters to this
* function specify the clipping volume where left and right are the
* minimum and maximum x values, top and bottom are the minimum and maximum
* y values, and near and far are the minimum and maximum z values. If no
* parameters are given, the default is used: ortho(0, width, 0, height,
* -10, 10).
*
* ( end auto-generated )
*
* @webref lights_camera:camera
*/
public void ortho() {
if (recorder != null) recorder.ortho();
g.ortho();
}
/**
* @param left left plane of the clipping volume
* @param right right plane of the clipping volume
* @param bottom bottom plane of the clipping volume
* @param top top plane of the clipping volume
*/
public void ortho(float left, float right,
float bottom, float top) {
if (recorder != null) recorder.ortho(left, right, bottom, top);
g.ortho(left, right, bottom, top);
}
/**
* @param near maximum distance from the origin to the viewer
* @param far maximum distance from the origin away from the viewer
*/
public void ortho(float left, float right,
float bottom, float top,
float near, float far) {
if (recorder != null) recorder.ortho(left, right, bottom, top, near, far);
g.ortho(left, right, bottom, top, near, far);
}
/**
* ( begin auto-generated from perspective.xml )
*
* Sets a perspective projection applying foreshortening, making distant
* objects appear smaller than closer ones. The parameters define a viewing
* volume with the shape of truncated pyramid. Objects near to the front of
* the volume appear their actual size, while farther objects appear
* smaller. This projection simulates the perspective of the world more
* accurately than orthographic projection. The version of perspective
* without parameters sets the default perspective and the version with
* four parameters allows the programmer to set the area precisely. The
* default values are: perspective(PI/3.0, width/height, cameraZ/10.0,
* cameraZ*10.0) where cameraZ is ((height/2.0) / tan(PI*60.0/360.0));
*
* ( end auto-generated )
*
* @webref lights_camera:camera
*/
public void perspective() {
if (recorder != null) recorder.perspective();
g.perspective();
}
/**
* @param fovy field-of-view angle (in radians) for vertical direction
* @param aspect ratio of width to height
* @param zNear z-position of nearest clipping plane
* @param zFar z-position of farthest clipping plane
*/
public void perspective(float fovy, float aspect, float zNear, float zFar) {
if (recorder != null) recorder.perspective(fovy, aspect, zNear, zFar);
g.perspective(fovy, aspect, zNear, zFar);
}
/**
* ( begin auto-generated from frustum.xml )
*
* Sets a perspective matrix defined through the parameters. Works like
* glFrustum, except it wipes out the current perspective matrix rather
* than muliplying itself with it.
*
* ( end auto-generated )
*
* @webref lights_camera:camera
* @param left left coordinate of the clipping plane
* @param right right coordinate of the clipping plane
* @param bottom bottom coordinate of the clipping plane
* @param top top coordinate of the clipping plane
* @param near near component of the clipping plane; must be greater than zero
* @param far far component of the clipping plane; must be greater than the near value
* @see PGraphics#camera(float, float, float, float, float, float, float, float, float)
* @see PGraphics#endCamera()
* @see PGraphics#perspective(float, float, float, float)
*/
public void frustum(float left, float right,
float bottom, float top,
float near, float far) {
if (recorder != null) recorder.frustum(left, right, bottom, top, near, far);
g.frustum(left, right, bottom, top, near, far);
}
/**
* ( begin auto-generated from printProjection.xml )
*
* Prints the current projection matrix to the Console (the text window at
* the bottom of Processing).
*
* ( end auto-generated )
*
* @webref lights_camera:camera
* @see PGraphics#camera(float, float, float, float, float, float, float, float, float)
*/
public void printProjection() {
if (recorder != null) recorder.printProjection();
g.printProjection();
}
/**
* ( begin auto-generated from screenX.xml )
*
* Takes a three-dimensional X, Y, Z position and returns the X value for
* where it will appear on a (two-dimensional) screen.
*
* ( end auto-generated )
*
* @webref lights_camera:coordinates
* @param x 3D x-coordinate to be mapped
* @param y 3D y-coordinate to be mapped
* @see PGraphics#screenY(float, float, float)
* @see PGraphics#screenZ(float, float, float)
*/
public float screenX(float x, float y) {
return g.screenX(x, y);
}
/**
* ( begin auto-generated from screenY.xml )
*
* Takes a three-dimensional X, Y, Z position and returns the Y value for
* where it will appear on a (two-dimensional) screen.
*
* ( end auto-generated )
*
* @webref lights_camera:coordinates
* @param x 3D x-coordinate to be mapped
* @param y 3D y-coordinate to be mapped
* @see PGraphics#screenX(float, float, float)
* @see PGraphics#screenZ(float, float, float)
*/
public float screenY(float x, float y) {
return g.screenY(x, y);
}
/**
* @param z 3D z-coordinate to be mapped
*/
public float screenX(float x, float y, float z) {
return g.screenX(x, y, z);
}
/**
* @param z 3D z-coordinate to be mapped
*/
public float screenY(float x, float y, float z) {
return g.screenY(x, y, z);
}
/**
* ( begin auto-generated from screenZ.xml )
*
* Takes a three-dimensional X, Y, Z position and returns the Z value for
* where it will appear on a (two-dimensional) screen.
*
* ( end auto-generated )
*
* @webref lights_camera:coordinates
* @param x 3D x-coordinate to be mapped
* @param y 3D y-coordinate to be mapped
* @param z 3D z-coordinate to be mapped
* @see PGraphics#screenX(float, float, float)
* @see PGraphics#screenY(float, float, float)
*/
public float screenZ(float x, float y, float z) {
return g.screenZ(x, y, z);
}
/**
* ( begin auto-generated from modelX.xml )
*
* Returns the three-dimensional X, Y, Z position in model space. This
* returns the X value for a given coordinate based on the current set of
* transformations (scale, rotate, translate, etc.) The X value can be used
* to place an object in space relative to the location of the original
* point once the transformations are no longer in use.
* <br/> <br/>
* In the example, the <b>modelX()</b>, <b>modelY()</b>, and
* <b>modelZ()</b> functions record the location of a box in space after
* being placed using a series of translate and rotate commands. After
* popMatrix() is called, those transformations no longer apply, but the
* (x, y, z) coordinate returned by the model functions is used to place
* another box in the same location.
*
* ( end auto-generated )
*
* @webref lights_camera:coordinates
* @param x 3D x-coordinate to be mapped
* @param y 3D y-coordinate to be mapped
* @param z 3D z-coordinate to be mapped
* @see PGraphics#modelY(float, float, float)
* @see PGraphics#modelZ(float, float, float)
*/
public float modelX(float x, float y, float z) {
return g.modelX(x, y, z);
}
/**
* ( begin auto-generated from modelY.xml )
*
* Returns the three-dimensional X, Y, Z position in model space. This
* returns the Y value for a given coordinate based on the current set of
* transformations (scale, rotate, translate, etc.) The Y value can be used
* to place an object in space relative to the location of the original
* point once the transformations are no longer in use.<br />
* <br />
* In the example, the <b>modelX()</b>, <b>modelY()</b>, and
* <b>modelZ()</b> functions record the location of a box in space after
* being placed using a series of translate and rotate commands. After
* popMatrix() is called, those transformations no longer apply, but the
* (x, y, z) coordinate returned by the model functions is used to place
* another box in the same location.
*
* ( end auto-generated )
*
* @webref lights_camera:coordinates
* @param x 3D x-coordinate to be mapped
* @param y 3D y-coordinate to be mapped
* @param z 3D z-coordinate to be mapped
* @see PGraphics#modelX(float, float, float)
* @see PGraphics#modelZ(float, float, float)
*/
public float modelY(float x, float y, float z) {
return g.modelY(x, y, z);
}
/**
* ( begin auto-generated from modelZ.xml )
*
* Returns the three-dimensional X, Y, Z position in model space. This
* returns the Z value for a given coordinate based on the current set of
* transformations (scale, rotate, translate, etc.) The Z value can be used
* to place an object in space relative to the location of the original
* point once the transformations are no longer in use.<br />
* <br />
* In the example, the <b>modelX()</b>, <b>modelY()</b>, and
* <b>modelZ()</b> functions record the location of a box in space after
* being placed using a series of translate and rotate commands. After
* popMatrix() is called, those transformations no longer apply, but the
* (x, y, z) coordinate returned by the model functions is used to place
* another box in the same location.
*
* ( end auto-generated )
*
* @webref lights_camera:coordinates
* @param x 3D x-coordinate to be mapped
* @param y 3D y-coordinate to be mapped
* @param z 3D z-coordinate to be mapped
* @see PGraphics#modelX(float, float, float)
* @see PGraphics#modelY(float, float, float)
*/
public float modelZ(float x, float y, float z) {
return g.modelZ(x, y, z);
}
/**
* ( begin auto-generated from pushStyle.xml )
*
* The <b>pushStyle()</b> function saves the current style settings and
* <b>popStyle()</b> restores the prior settings. Note that these functions
* are always used together. They allow you to change the style settings
* and later return to what you had. When a new style is started with
* <b>pushStyle()</b>, it builds on the current style information. The
* <b>pushStyle()</b> and <b>popStyle()</b> functions can be embedded to
* provide more control (see the second example above for a demonstration.)
* <br /><br />
* The style information controlled by the following functions are included
* in the style:
* fill(), stroke(), tint(), strokeWeight(), strokeCap(), strokeJoin(),
* imageMode(), rectMode(), ellipseMode(), shapeMode(), colorMode(),
* textAlign(), textFont(), textMode(), textSize(), textLeading(),
* emissive(), specular(), shininess(), ambient()
*
* ( end auto-generated )
*
* @webref structure
* @see PGraphics#popStyle()
*/
public void pushStyle() {
if (recorder != null) recorder.pushStyle();
g.pushStyle();
}
/**
* ( begin auto-generated from popStyle.xml )
*
* The <b>pushStyle()</b> function saves the current style settings and
* <b>popStyle()</b> restores the prior settings; these functions are
* always used together. They allow you to change the style settings and
* later return to what you had. When a new style is started with
* <b>pushStyle()</b>, it builds on the current style information. The
* <b>pushStyle()</b> and <b>popStyle()</b> functions can be embedded to
* provide more control (see the second example above for a demonstration.)
*
* ( end auto-generated )
*
* @webref structure
* @see PGraphics#pushStyle()
*/
public void popStyle() {
if (recorder != null) recorder.popStyle();
g.popStyle();
}
public void style(PStyle s) {
if (recorder != null) recorder.style(s);
g.style(s);
}
/**
* ( begin auto-generated from strokeWeight.xml )
*
* Sets the width of the stroke used for lines, points, and the border
* around shapes. All widths are set in units of pixels.
* <br/> <br/>
* When drawing with P3D, series of connected lines (such as the stroke
* around a polygon, triangle, or ellipse) produce unattractive results
* when a thick stroke weight is set (<a
* href="http://code.google.com/p/processing/issues/detail?id=123">see
* Issue 123</a>). With P3D, the minimum and maximum values for
* <b>strokeWeight()</b> are controlled by the graphics card and the
* operating system's OpenGL implementation. For instance, the thickness
* may not go higher than 10 pixels.
*
* ( end auto-generated )
*
* @webref shape:attributes
* @param weight the weight (in pixels) of the stroke
* @see PGraphics#stroke(int, float)
* @see PGraphics#strokeJoin(int)
* @see PGraphics#strokeCap(int)
*/
public void strokeWeight(float weight) {
if (recorder != null) recorder.strokeWeight(weight);
g.strokeWeight(weight);
}
/**
* ( begin auto-generated from strokeJoin.xml )
*
* Sets the style of the joints which connect line segments. These joints
* are either mitered, beveled, or rounded and specified with the
* corresponding parameters MITER, BEVEL, and ROUND. The default joint is
* MITER.
* <br/> <br/>
* This function is not available with the P3D renderer, (<a
* href="http://code.google.com/p/processing/issues/detail?id=123">see
* Issue 123</a>). More information about the renderers can be found in the
* <b>size()</b> reference.
*
* ( end auto-generated )
*
* @webref shape:attributes
* @param join either MITER, BEVEL, ROUND
* @see PGraphics#stroke(int, float)
* @see PGraphics#strokeWeight(float)
* @see PGraphics#strokeCap(int)
*/
public void strokeJoin(int join) {
if (recorder != null) recorder.strokeJoin(join);
g.strokeJoin(join);
}
/**
* ( begin auto-generated from strokeCap.xml )
*
* Sets the style for rendering line endings. These ends are either
* squared, extended, or rounded and specified with the corresponding
* parameters SQUARE, PROJECT, and ROUND. The default cap is ROUND.
* <br/> <br/>
* This function is not available with the P3D renderer (<a
* href="http://code.google.com/p/processing/issues/detail?id=123">see
* Issue 123</a>). More information about the renderers can be found in the
* <b>size()</b> reference.
*
* ( end auto-generated )
*
* @webref shape:attributes
* @param cap either SQUARE, PROJECT, or ROUND
* @see PGraphics#stroke(int, float)
* @see PGraphics#strokeWeight(float)
* @see PGraphics#strokeJoin(int)
* @see PApplet#size(int, int, String, String)
*/
public void strokeCap(int cap) {
if (recorder != null) recorder.strokeCap(cap);
g.strokeCap(cap);
}
/**
* ( begin auto-generated from noStroke.xml )
*
* Disables drawing the stroke (outline). If both <b>noStroke()</b> and
* <b>noFill()</b> are called, nothing will be drawn to the screen.
*
* ( end auto-generated )
*
* @webref color:setting
* @see PGraphics#stroke(float, float, float, float)
*/
public void noStroke() {
if (recorder != null) recorder.noStroke();
g.noStroke();
}
/**
* ( begin auto-generated from stroke.xml )
*
* Sets the color used to draw lines and borders around shapes. This color
* is either specified in terms of the RGB or HSB color depending on the
* current <b>colorMode()</b> (the default color space is RGB, with each
* value in the range from 0 to 255).
* <br/> <br/>
* When using hexadecimal notation to specify a color, use "#" or "0x"
* before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six
* digits to specify a color (the way colors are specified in HTML and
* CSS). When using the hexadecimal notation starting with "0x", the
* hexadecimal value must be specified with eight characters; the first two
* characters define the alpha component and the remainder the red, green,
* and blue components.
* <br/> <br/>
* The value for the parameter "gray" must be less than or equal to the
* current maximum value as specified by <b>colorMode()</b>. The default
* maximum value is 255.
*
* ( end auto-generated )
*
* @param rgb color value in hexadecimal notation
* @see PGraphics#noStroke()
* @see PGraphics#fill(int, float)
* @see PGraphics#tint(int, float)
* @see PGraphics#background(float, float, float, float)
* @see PGraphics#colorMode(int, float, float, float, float)
*/
public void stroke(int rgb) {
if (recorder != null) recorder.stroke(rgb);
g.stroke(rgb);
}
/**
* @param alpha opacity of the stroke
*/
public void stroke(int rgb, float alpha) {
if (recorder != null) recorder.stroke(rgb, alpha);
g.stroke(rgb, alpha);
}
/**
* @param gray specifies a value between white and black
*/
public void stroke(float gray) {
if (recorder != null) recorder.stroke(gray);
g.stroke(gray);
}
public void stroke(float gray, float alpha) {
if (recorder != null) recorder.stroke(gray, alpha);
g.stroke(gray, alpha);
}
/**
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
* @webref color:setting
*/
public void stroke(float v1, float v2, float v3) {
if (recorder != null) recorder.stroke(v1, v2, v3);
g.stroke(v1, v2, v3);
}
public void stroke(float v1, float v2, float v3, float alpha) {
if (recorder != null) recorder.stroke(v1, v2, v3, alpha);
g.stroke(v1, v2, v3, alpha);
}
/**
* ( begin auto-generated from noTint.xml )
*
* Removes the current fill value for displaying images and reverts to
* displaying images with their original hues.
*
* ( end auto-generated )
*
* @webref image:loading_displaying
* @usage web_application
* @see PGraphics#tint(float, float, float, float)
* @see PGraphics#image(PImage, float, float, float, float)
*/
public void noTint() {
if (recorder != null) recorder.noTint();
g.noTint();
}
/**
* ( begin auto-generated from tint.xml )
*
* Sets the fill value for displaying images. Images can be tinted to
* specified colors or made transparent by setting the alpha.<br />
* <br />
* To make an image transparent, but not change it's color, use white as
* the tint color and specify an alpha value. For instance, tint(255, 128)
* will make an image 50% transparent (unless <b>colorMode()</b> has been
* used).<br />
* <br />
* When using hexadecimal notation to specify a color, use "#" or "0x"
* before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six
* digits to specify a color (the way colors are specified in HTML and
* CSS). When using the hexadecimal notation starting with "0x", the
* hexadecimal value must be specified with eight characters; the first two
* characters define the alpha component and the remainder the red, green,
* and blue components.<br />
* <br />
* The value for the parameter "gray" must be less than or equal to the
* current maximum value as specified by <b>colorMode()</b>. The default
* maximum value is 255.<br />
* <br />
* The <b>tint()</b> function is also used to control the coloring of
* textures in 3D.
*
* ( end auto-generated )
*
* @webref image:loading_displaying
* @usage web_application
* @param rgb color value in hexadecimal notation
* @see PGraphics#noTint()
* @see PGraphics#image(PImage, float, float, float, float)
*/
public void tint(int rgb) {
if (recorder != null) recorder.tint(rgb);
g.tint(rgb);
}
/**
* @param alpha opacity of the image
*/
public void tint(int rgb, float alpha) {
if (recorder != null) recorder.tint(rgb, alpha);
g.tint(rgb, alpha);
}
/**
* @param gray specifies a value between white and black
*/
public void tint(float gray) {
if (recorder != null) recorder.tint(gray);
g.tint(gray);
}
public void tint(float gray, float alpha) {
if (recorder != null) recorder.tint(gray, alpha);
g.tint(gray, alpha);
}
/**
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
*/
public void tint(float v1, float v2, float v3) {
if (recorder != null) recorder.tint(v1, v2, v3);
g.tint(v1, v2, v3);
}
public void tint(float v1, float v2, float v3, float alpha) {
if (recorder != null) recorder.tint(v1, v2, v3, alpha);
g.tint(v1, v2, v3, alpha);
}
/**
* ( begin auto-generated from noFill.xml )
*
* Disables filling geometry. If both <b>noStroke()</b> and <b>noFill()</b>
* are called, nothing will be drawn to the screen.
*
* ( end auto-generated )
*
* @webref color:setting
* @usage web_application
* @see PGraphics#fill(float, float, float, float)
*/
public void noFill() {
if (recorder != null) recorder.noFill();
g.noFill();
}
/**
* ( begin auto-generated from fill.xml )
*
* Sets the color used to fill shapes. For example, if you run <b>fill(204,
* 102, 0)</b>, all subsequent shapes will be filled with orange. This
* color is either specified in terms of the RGB or HSB color depending on
* the current <b>colorMode()</b> (the default color space is RGB, with
* each value in the range from 0 to 255).
* <br/> <br/>
* When using hexadecimal notation to specify a color, use "#" or "0x"
* before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six
* digits to specify a color (the way colors are specified in HTML and
* CSS). When using the hexadecimal notation starting with "0x", the
* hexadecimal value must be specified with eight characters; the first two
* characters define the alpha component and the remainder the red, green,
* and blue components.
* <br/> <br/>
* The value for the parameter "gray" must be less than or equal to the
* current maximum value as specified by <b>colorMode()</b>. The default
* maximum value is 255.
* <br/> <br/>
* To change the color of an image (or a texture), use tint().
*
* ( end auto-generated )
*
* @webref color:setting
* @usage web_application
* @param rgb color variable or hex value
* @see PGraphics#noFill()
* @see PGraphics#stroke(int, float)
* @see PGraphics#tint(int, float)
* @see PGraphics#background(float, float, float, float)
* @see PGraphics#colorMode(int, float, float, float, float)
*/
public void fill(int rgb) {
if (recorder != null) recorder.fill(rgb);
g.fill(rgb);
}
/**
* @param alpha opacity of the fill
*/
public void fill(int rgb, float alpha) {
if (recorder != null) recorder.fill(rgb, alpha);
g.fill(rgb, alpha);
}
/**
* @param gray number specifying value between white and black
*/
public void fill(float gray) {
if (recorder != null) recorder.fill(gray);
g.fill(gray);
}
public void fill(float gray, float alpha) {
if (recorder != null) recorder.fill(gray, alpha);
g.fill(gray, alpha);
}
/**
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
*/
public void fill(float v1, float v2, float v3) {
if (recorder != null) recorder.fill(v1, v2, v3);
g.fill(v1, v2, v3);
}
public void fill(float v1, float v2, float v3, float alpha) {
if (recorder != null) recorder.fill(v1, v2, v3, alpha);
g.fill(v1, v2, v3, alpha);
}
/**
* ( begin auto-generated from ambient.xml )
*
* Sets the ambient reflectance for shapes drawn to the screen. This is
* combined with the ambient light component of environment. The color
* components set through the parameters define the reflectance. For
* example in the default color mode, setting v1=255, v2=126, v3=0, would
* cause all the red light to reflect and half of the green light to
* reflect. Used in combination with <b>emissive()</b>, <b>specular()</b>,
* and <b>shininess()</b> in setting the material properties of shapes.
*
* ( end auto-generated )
*
* @webref lights_camera:material_properties
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#emissive(float, float, float)
* @see PGraphics#specular(float, float, float)
* @see PGraphics#shininess(float)
*/
public void ambient(int rgb) {
if (recorder != null) recorder.ambient(rgb);
g.ambient(rgb);
}
/**
* @param gray number specifying value between white and black
*/
public void ambient(float gray) {
if (recorder != null) recorder.ambient(gray);
g.ambient(gray);
}
/**
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
*/
public void ambient(float v1, float v2, float v3) {
if (recorder != null) recorder.ambient(v1, v2, v3);
g.ambient(v1, v2, v3);
}
/**
* ( begin auto-generated from specular.xml )
*
* Sets the specular color of the materials used for shapes drawn to the
* screen, which sets the color of hightlights. Specular refers to light
* which bounces off a surface in a perferred direction (rather than
* bouncing in all directions like a diffuse light). Used in combination
* with <b>emissive()</b>, <b>ambient()</b>, and <b>shininess()</b> in
* setting the material properties of shapes.
*
* ( end auto-generated )
*
* @webref lights_camera:material_properties
* @usage web_application
* @param rgb color to set
* @see PGraphics#lightSpecular(float, float, float)
* @see PGraphics#ambient(float, float, float)
* @see PGraphics#emissive(float, float, float)
* @see PGraphics#shininess(float)
*/
public void specular(int rgb) {
if (recorder != null) recorder.specular(rgb);
g.specular(rgb);
}
/**
* gray number specifying value between white and black
*/
public void specular(float gray) {
if (recorder != null) recorder.specular(gray);
g.specular(gray);
}
/**
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
*/
public void specular(float v1, float v2, float v3) {
if (recorder != null) recorder.specular(v1, v2, v3);
g.specular(v1, v2, v3);
}
/**
* ( begin auto-generated from shininess.xml )
*
* Sets the amount of gloss in the surface of shapes. Used in combination
* with <b>ambient()</b>, <b>specular()</b>, and <b>emissive()</b> in
* setting the material properties of shapes.
*
* ( end auto-generated )
*
* @webref lights_camera:material_properties
* @usage web_application
* @param shine degree of shininess
* @see PGraphics#emissive(float, float, float)
* @see PGraphics#ambient(float, float, float)
* @see PGraphics#specular(float, float, float)
*/
public void shininess(float shine) {
if (recorder != null) recorder.shininess(shine);
g.shininess(shine);
}
/**
* ( begin auto-generated from emissive.xml )
*
* Sets the emissive color of the material used for drawing shapes drawn to
* the screen. Used in combination with <b>ambient()</b>,
* <b>specular()</b>, and <b>shininess()</b> in setting the material
* properties of shapes.
*
* ( end auto-generated )
*
* @webref lights_camera:material_properties
* @usage web_application
* @param rgb color to set
* @see PGraphics#ambient(float, float, float)
* @see PGraphics#specular(float, float, float)
* @see PGraphics#shininess(float)
*/
public void emissive(int rgb) {
if (recorder != null) recorder.emissive(rgb);
g.emissive(rgb);
}
/**
* gray number specifying value between white and black
*/
public void emissive(float gray) {
if (recorder != null) recorder.emissive(gray);
g.emissive(gray);
}
/**
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
*/
public void emissive(float v1, float v2, float v3) {
if (recorder != null) recorder.emissive(v1, v2, v3);
g.emissive(v1, v2, v3);
}
/**
* ( begin auto-generated from lights.xml )
*
* Sets the default ambient light, directional light, falloff, and specular
* values. The defaults are ambientLight(128, 128, 128) and
* directionalLight(128, 128, 128, 0, 0, -1), lightFalloff(1, 0, 0), and
* lightSpecular(0, 0, 0). Lights need to be included in the draw() to
* remain persistent in a looping program. Placing them in the setup() of a
* looping program will cause them to only have an effect the first time
* through the loop.
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @see PGraphics#ambientLight(float, float, float, float, float, float)
* @see PGraphics#directionalLight(float, float, float, float, float, float)
* @see PGraphics#pointLight(float, float, float, float, float, float)
* @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#noLights()
*/
public void lights() {
if (recorder != null) recorder.lights();
g.lights();
}
/**
* ( begin auto-generated from noLights.xml )
*
* Disable all lighting. Lighting is turned off by default and enabled with
* the <b>lights()</b> function. This function can be used to disable
* lighting so that 2D geometry (which does not require lighting) can be
* drawn after a set of lighted 3D geometry.
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @see PGraphics#lights()
*/
public void noLights() {
if (recorder != null) recorder.noLights();
g.noLights();
}
/**
* ( begin auto-generated from ambientLight.xml )
*
* Adds an ambient light. Ambient light doesn't come from a specific
* direction, the rays have light have bounced around so much that objects
* are evenly lit from all sides. Ambient lights are almost always used in
* combination with other types of lights. Lights need to be included in
* the <b>draw()</b> to remain persistent in a looping program. Placing
* them in the <b>setup()</b> of a looping program will cause them to only
* have an effect the first time through the loop. The effect of the
* parameters is determined by the current color mode.
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
* @see PGraphics#lights()
* @see PGraphics#directionalLight(float, float, float, float, float, float)
* @see PGraphics#pointLight(float, float, float, float, float, float)
* @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float)
*/
public void ambientLight(float v1, float v2, float v3) {
if (recorder != null) recorder.ambientLight(v1, v2, v3);
g.ambientLight(v1, v2, v3);
}
/**
* @param x x-coordinate of the light
* @param y y-coordinate of the light
* @param z z-coordinate of the light
*/
public void ambientLight(float v1, float v2, float v3,
float x, float y, float z) {
if (recorder != null) recorder.ambientLight(v1, v2, v3, x, y, z);
g.ambientLight(v1, v2, v3, x, y, z);
}
/**
* ( begin auto-generated from directionalLight.xml )
*
* Adds a directional light. Directional light comes from one direction and
* is stronger when hitting a surface squarely and weaker if it hits at a a
* gentle angle. After hitting a surface, a directional lights scatters in
* all directions. Lights need to be included in the <b>draw()</b> to
* remain persistent in a looping program. Placing them in the
* <b>setup()</b> of a looping program will cause them to only have an
* effect the first time through the loop. The affect of the <b>v1</b>,
* <b>v2</b>, and <b>v3</b> parameters is determined by the current color
* mode. The <b>nx</b>, <b>ny</b>, and <b>nz</b> parameters specify the
* direction the light is facing. For example, setting <b>ny</b> to -1 will
* cause the geometry to be lit from below (the light is facing directly upward).
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
* @param nx direction along the x-axis
* @param ny direction along the y-axis
* @param nz direction along the z-axis
* @see PGraphics#lights()
* @see PGraphics#ambientLight(float, float, float, float, float, float)
* @see PGraphics#pointLight(float, float, float, float, float, float)
* @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float)
*/
public void directionalLight(float v1, float v2, float v3,
float nx, float ny, float nz) {
if (recorder != null) recorder.directionalLight(v1, v2, v3, nx, ny, nz);
g.directionalLight(v1, v2, v3, nx, ny, nz);
}
/**
* ( begin auto-generated from pointLight.xml )
*
* Adds a point light. Lights need to be included in the <b>draw()</b> to
* remain persistent in a looping program. Placing them in the
* <b>setup()</b> of a looping program will cause them to only have an
* effect the first time through the loop. The affect of the <b>v1</b>,
* <b>v2</b>, and <b>v3</b> parameters is determined by the current color
* mode. The <b>x</b>, <b>y</b>, and <b>z</b> parameters set the position
* of the light.
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
* @param x x-coordinate of the light
* @param y y-coordinate of the light
* @param z z-coordinate of the light
* @see PGraphics#lights()
* @see PGraphics#directionalLight(float, float, float, float, float, float)
* @see PGraphics#ambientLight(float, float, float, float, float, float)
* @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float)
*/
public void pointLight(float v1, float v2, float v3,
float x, float y, float z) {
if (recorder != null) recorder.pointLight(v1, v2, v3, x, y, z);
g.pointLight(v1, v2, v3, x, y, z);
}
/**
* ( begin auto-generated from spotLight.xml )
*
* Adds a spot light. Lights need to be included in the <b>draw()</b> to
* remain persistent in a looping program. Placing them in the
* <b>setup()</b> of a looping program will cause them to only have an
* effect the first time through the loop. The affect of the <b>v1</b>,
* <b>v2</b>, and <b>v3</b> parameters is determined by the current color
* mode. The <b>x</b>, <b>y</b>, and <b>z</b> parameters specify the
* position of the light and <b>nx</b>, <b>ny</b>, <b>nz</b> specify the
* direction or light. The <b>angle</b> parameter affects angle of the
* spotlight cone.
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
* @param x x-coordinate of the light
* @param y y-coordinate of the light
* @param z z-coordinate of the light
* @param nx direction along the x axis
* @param ny direction along the y axis
* @param nz direction along the z axis
* @param angle angle of the spotlight cone
* @param concentration exponent determining the center bias of the cone
* @see PGraphics#lights()
* @see PGraphics#directionalLight(float, float, float, float, float, float)
* @see PGraphics#pointLight(float, float, float, float, float, float)
* @see PGraphics#ambientLight(float, float, float, float, float, float)
*/
public void spotLight(float v1, float v2, float v3,
float x, float y, float z,
float nx, float ny, float nz,
float angle, float concentration) {
if (recorder != null) recorder.spotLight(v1, v2, v3, x, y, z, nx, ny, nz, angle, concentration);
g.spotLight(v1, v2, v3, x, y, z, nx, ny, nz, angle, concentration);
}
/**
* ( begin auto-generated from lightFalloff.xml )
*
* Sets the falloff rates for point lights, spot lights, and ambient
* lights. The parameters are used to determine the falloff with the
* following equation:<br /><br />d = distance from light position to
* vertex position<br />falloff = 1 / (CONSTANT + d * LINEAR + (d*d) *
* QUADRATIC)<br /><br />Like <b>fill()</b>, it affects only the elements
* which are created after it in the code. The default value if
* <b>LightFalloff(1.0, 0.0, 0.0)</b>. Thinking about an ambient light with
* a falloff can be tricky. It is used, for example, if you wanted a region
* of your scene to be lit ambiently one color and another region to be lit
* ambiently by another color, you would use an ambient light with location
* and falloff. You can think of it as a point light that doesn't care
* which direction a surface is facing.
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @param constant constant value or determining falloff
* @param linear linear value for determining falloff
* @param quadratic quadratic value for determining falloff
* @see PGraphics#lights()
* @see PGraphics#ambientLight(float, float, float, float, float, float)
* @see PGraphics#pointLight(float, float, float, float, float, float)
* @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#lightSpecular(float, float, float)
*/
public void lightFalloff(float constant, float linear, float quadratic) {
if (recorder != null) recorder.lightFalloff(constant, linear, quadratic);
g.lightFalloff(constant, linear, quadratic);
}
/**
* ( begin auto-generated from lightSpecular.xml )
*
* Sets the specular color for lights. Like <b>fill()</b>, it affects only
* the elements which are created after it in the code. Specular refers to
* light which bounces off a surface in a perferred direction (rather than
* bouncing in all directions like a diffuse light) and is used for
* creating highlights. The specular quality of a light interacts with the
* specular material qualities set through the <b>specular()</b> and
* <b>shininess()</b> functions.
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
* @see PGraphics#specular(float, float, float)
* @see PGraphics#lights()
* @see PGraphics#ambientLight(float, float, float, float, float, float)
* @see PGraphics#pointLight(float, float, float, float, float, float)
* @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float)
*/
public void lightSpecular(float v1, float v2, float v3) {
if (recorder != null) recorder.lightSpecular(v1, v2, v3);
g.lightSpecular(v1, v2, v3);
}
/**
* ( begin auto-generated from background.xml )
*
* The <b>background()</b> function sets the color used for the background
* of the Processing window. The default background is light gray. In the
* <b>draw()</b> function, the background color is used to clear the
* display window at the beginning of each frame.
* <br/> <br/>
* An image can also be used as the background for a sketch, however its
* width and height must be the same size as the sketch window. To resize
* an image 'b' to the size of the sketch window, use b.resize(width, height).
* <br/> <br/>
* Images used as background will ignore the current <b>tint()</b> setting.
* <br/> <br/>
* It is not possible to use transparency (alpha) in background colors with
* the main drawing surface, however they will work properly with <b>createGraphics()</b>.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* <p>Clear the background with a color that includes an alpha value. This can
* only be used with objects created by createGraphics(), because the main
* drawing surface cannot be set transparent.</p>
* <p>It might be tempting to use this function to partially clear the screen
* on each frame, however that's not how this function works. When calling
* background(), the pixels will be replaced with pixels that have that level
* of transparency. To do a semi-transparent overlay, use fill() with alpha
* and draw a rectangle.</p>
*
* @webref color:setting
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#stroke(float)
* @see PGraphics#fill(float)
* @see PGraphics#tint(float)
* @see PGraphics#colorMode(int)
*/
public void background(int rgb) {
if (recorder != null) recorder.background(rgb);
g.background(rgb);
}
/**
* @param alpha opacity of the background
*/
public void background(int rgb, float alpha) {
if (recorder != null) recorder.background(rgb, alpha);
g.background(rgb, alpha);
}
/**
* @param gray specifies a value between white and black
*/
public void background(float gray) {
if (recorder != null) recorder.background(gray);
g.background(gray);
}
public void background(float gray, float alpha) {
if (recorder != null) recorder.background(gray, alpha);
g.background(gray, alpha);
}
/**
* @param v1 red or hue value (depending on the current color mode)
* @param v2 green or saturation value (depending on the current color mode)
* @param v3 blue or brightness value (depending on the current color mode)
*/
public void background(float v1, float v2, float v3) {
if (recorder != null) recorder.background(v1, v2, v3);
g.background(v1, v2, v3);
}
public void background(float v1, float v2, float v3, float alpha) {
if (recorder != null) recorder.background(v1, v2, v3, alpha);
g.background(v1, v2, v3, alpha);
}
/**
* @webref color:setting
*/
public void clear() {
if (recorder != null) recorder.clear();
g.clear();
}
/**
* Takes an RGB or ARGB image and sets it as the background.
* The width and height of the image must be the same size as the sketch.
* Use image.resize(width, height) to make short work of such a task.<br/>
* <br/>
* Note that even if the image is set as RGB, the high 8 bits of each pixel
* should be set opaque (0xFF000000) because the image data will be copied
* directly to the screen, and non-opaque background images may have strange
* behavior. Use image.filter(OPAQUE) to handle this easily.<br/>
* <br/>
* When using 3D, this will also clear the zbuffer (if it exists).
*
* @param image PImage to set as background (must be same size as the sketch window)
*/
public void background(PImage image) {
if (recorder != null) recorder.background(image);
g.background(image);
}
/**
* ( begin auto-generated from colorMode.xml )
*
* Changes the way Processing interprets color data. By default, the
* parameters for <b>fill()</b>, <b>stroke()</b>, <b>background()</b>, and
* <b>color()</b> are defined by values between 0 and 255 using the RGB
* color model. The <b>colorMode()</b> function is used to change the
* numerical range used for specifying colors and to switch color systems.
* For example, calling <b>colorMode(RGB, 1.0)</b> will specify that values
* are specified between 0 and 1. The limits for defining colors are
* altered by setting the parameters range1, range2, range3, and range 4.
*
* ( end auto-generated )
*
* @webref color:setting
* @usage web_application
* @param mode Either RGB or HSB, corresponding to Red/Green/Blue and Hue/Saturation/Brightness
* @see PGraphics#background(float)
* @see PGraphics#fill(float)
* @see PGraphics#stroke(float)
*/
public void colorMode(int mode) {
if (recorder != null) recorder.colorMode(mode);
g.colorMode(mode);
}
/**
* @param max range for all color elements
*/
public void colorMode(int mode, float max) {
if (recorder != null) recorder.colorMode(mode, max);
g.colorMode(mode, max);
}
/**
* @param max1 range for the red or hue depending on the current color mode
* @param max2 range for the green or saturation depending on the current color mode
* @param max3 range for the blue or brightness depending on the current color mode
*/
public void colorMode(int mode, float max1, float max2, float max3) {
if (recorder != null) recorder.colorMode(mode, max1, max2, max3);
g.colorMode(mode, max1, max2, max3);
}
/**
* @param maxA range for the alpha
*/
public void colorMode(int mode,
float max1, float max2, float max3, float maxA) {
if (recorder != null) recorder.colorMode(mode, max1, max2, max3, maxA);
g.colorMode(mode, max1, max2, max3, maxA);
}
/**
* ( begin auto-generated from alpha.xml )
*
* Extracts the alpha value from a color.
*
* ( end auto-generated )
* @webref color:creating_reading
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#red(int)
* @see PGraphics#green(int)
* @see PGraphics#blue(int)
* @see PGraphics#hue(int)
* @see PGraphics#saturation(int)
* @see PGraphics#brightness(int)
*/
public final float alpha(int rgb) {
return g.alpha(rgb);
}
/**
* ( begin auto-generated from red.xml )
*
* Extracts the red value from a color, scaled to match current
* <b>colorMode()</b>. This value is always returned as a float so be
* careful not to assign it to an int value.<br /><br />The red() function
* is easy to use and undestand, but is slower than another technique. To
* achieve the same results when working in <b>colorMode(RGB, 255)</b>, but
* with greater speed, use the >> (right shift) operator with a bit
* mask. For example, the following two lines of code are equivalent:<br
* /><pre>float r1 = red(myColor);<br />float r2 = myColor >> 16
* & 0xFF;</pre>
*
* ( end auto-generated )
*
* @webref color:creating_reading
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#green(int)
* @see PGraphics#blue(int)
* @see PGraphics#alpha(int)
* @see PGraphics#hue(int)
* @see PGraphics#saturation(int)
* @see PGraphics#brightness(int)
* @see_external rightshift
*/
public final float red(int rgb) {
return g.red(rgb);
}
/**
* ( begin auto-generated from green.xml )
*
* Extracts the green value from a color, scaled to match current
* <b>colorMode()</b>. This value is always returned as a float so be
* careful not to assign it to an int value.<br /><br />The <b>green()</b>
* function is easy to use and undestand, but is slower than another
* technique. To achieve the same results when working in <b>colorMode(RGB,
* 255)</b>, but with greater speed, use the >> (right shift)
* operator with a bit mask. For example, the following two lines of code
* are equivalent:<br /><pre>float r1 = green(myColor);<br />float r2 =
* myColor >> 8 & 0xFF;</pre>
*
* ( end auto-generated )
*
* @webref color:creating_reading
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#red(int)
* @see PGraphics#blue(int)
* @see PGraphics#alpha(int)
* @see PGraphics#hue(int)
* @see PGraphics#saturation(int)
* @see PGraphics#brightness(int)
* @see_external rightshift
*/
public final float green(int rgb) {
return g.green(rgb);
}
/**
* ( begin auto-generated from blue.xml )
*
* Extracts the blue value from a color, scaled to match current
* <b>colorMode()</b>. This value is always returned as a float so be
* careful not to assign it to an int value.<br /><br />The <b>blue()</b>
* function is easy to use and undestand, but is slower than another
* technique. To achieve the same results when working in <b>colorMode(RGB,
* 255)</b>, but with greater speed, use a bit mask to remove the other
* color components. For example, the following two lines of code are
* equivalent:<br /><pre>float r1 = blue(myColor);<br />float r2 = myColor
* & 0xFF;</pre>
*
* ( end auto-generated )
*
* @webref color:creating_reading
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#red(int)
* @see PGraphics#green(int)
* @see PGraphics#alpha(int)
* @see PGraphics#hue(int)
* @see PGraphics#saturation(int)
* @see PGraphics#brightness(int)
* @see_external rightshift
*/
public final float blue(int rgb) {
return g.blue(rgb);
}
/**
* ( begin auto-generated from hue.xml )
*
* Extracts the hue value from a color.
*
* ( end auto-generated )
* @webref color:creating_reading
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#red(int)
* @see PGraphics#green(int)
* @see PGraphics#blue(int)
* @see PGraphics#alpha(int)
* @see PGraphics#saturation(int)
* @see PGraphics#brightness(int)
*/
public final float hue(int rgb) {
return g.hue(rgb);
}
/**
* ( begin auto-generated from saturation.xml )
*
* Extracts the saturation value from a color.
*
* ( end auto-generated )
* @webref color:creating_reading
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#red(int)
* @see PGraphics#green(int)
* @see PGraphics#blue(int)
* @see PGraphics#alpha(int)
* @see PGraphics#hue(int)
* @see PGraphics#brightness(int)
*/
public final float saturation(int rgb) {
return g.saturation(rgb);
}
/**
* ( begin auto-generated from brightness.xml )
*
* Extracts the brightness value from a color.
*
* ( end auto-generated )
*
* @webref color:creating_reading
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#red(int)
* @see PGraphics#green(int)
* @see PGraphics#blue(int)
* @see PGraphics#alpha(int)
* @see PGraphics#hue(int)
* @see PGraphics#saturation(int)
*/
public final float brightness(int rgb) {
return g.brightness(rgb);
}
/**
* ( begin auto-generated from lerpColor.xml )
*
* Calculates a color or colors between two color at a specific increment.
* The <b>amt</b> parameter is the amount to interpolate between the two
* values where 0.0 equal to the first point, 0.1 is very near the first
* point, 0.5 is half-way in between, etc.
*
* ( end auto-generated )
*
* @webref color:creating_reading
* @usage web_application
* @param c1 interpolate from this color
* @param c2 interpolate to this color
* @param amt between 0.0 and 1.0
* @see PImage#blendColor(int, int, int)
* @see PGraphics#color(float, float, float, float)
*/
public int lerpColor(int c1, int c2, float amt) {
return g.lerpColor(c1, c2, amt);
}
/**
* @nowebref
* Interpolate between two colors. Like lerp(), but for the
* individual color components of a color supplied as an int value.
*/
static public int lerpColor(int c1, int c2, float amt, int mode) {
return PGraphics.lerpColor(c1, c2, amt, mode);
}
/**
* Display a warning that the specified method is only available with 3D.
* @param method The method name (no parentheses)
*/
static public void showDepthWarning(String method) {
PGraphics.showDepthWarning(method);
}
/**
* Display a warning that the specified method that takes x, y, z parameters
* can only be used with x and y parameters in this renderer.
* @param method The method name (no parentheses)
*/
static public void showDepthWarningXYZ(String method) {
PGraphics.showDepthWarningXYZ(method);
}
/**
* Display a warning that the specified method is simply unavailable.
*/
static public void showMethodWarning(String method) {
PGraphics.showMethodWarning(method);
}
/**
* Error that a particular variation of a method is unavailable (even though
* other variations are). For instance, if vertex(x, y, u, v) is not
* available, but vertex(x, y) is just fine.
*/
static public void showVariationWarning(String str) {
PGraphics.showVariationWarning(str);
}
/**
* Display a warning that the specified method is not implemented, meaning
* that it could be either a completely missing function, although other
* variations of it may still work properly.
*/
static public void showMissingWarning(String method) {
PGraphics.showMissingWarning(method);
}
/**
* Return true if this renderer should be drawn to the screen. Defaults to
* returning true, since nearly all renderers are on-screen beasts. But can
* be overridden for subclasses like PDF so that a window doesn't open up.
* <br/> <br/>
* A better name? showFrame, displayable, isVisible, visible, shouldDisplay,
* what to call this?
*/
public boolean displayable() {
return g.displayable();
}
/**
* Return true if this renderer does rendering through OpenGL. Defaults to false.
*/
public boolean isGL() {
return g.isGL();
}
/**
* ( begin auto-generated from PImage_get.xml )
*
* Reads the color of any pixel or grabs a section of an image. If no
* parameters are specified, the entire image is returned. Use the <b>x</b>
* and <b>y</b> parameters to get the value of one pixel. Get a section of
* the display window by specifying an additional <b>width</b> and
* <b>height</b> parameter. When getting an image, the <b>x</b> and
* <b>y</b> parameters define the coordinates for the upper-left corner of
* the image, regardless of the current <b>imageMode()</b>.<br />
* <br />
* If the pixel requested is outside of the image window, black is
* returned. The numbers returned are scaled according to the current color
* ranges, but only RGB values are returned by this function. For example,
* even though you may have drawn a shape with <b>colorMode(HSB)</b>, the
* numbers returned will be in RGB format.<br />
* <br />
* Getting the color of a single pixel with <b>get(x, y)</b> is easy, but
* not as fast as grabbing the data directly from <b>pixels[]</b>. The
* equivalent statement to <b>get(x, y)</b> using <b>pixels[]</b> is
* <b>pixels[y*width+x]</b>. See the reference for <b>pixels[]</b> for more information.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Returns an ARGB "color" type (a packed 32 bit int with the color.
* If the coordinate is outside the image, zero is returned
* (black, but completely transparent).
* <P>
* If the image is in RGB format (i.e. on a PVideo object),
* the value will get its high bits set, just to avoid cases where
* they haven't been set already.
* <P>
* If the image is in ALPHA format, this returns a white with its
* alpha value set.
* <P>
* This function is included primarily for beginners. It is quite
* slow because it has to check to see if the x, y that was provided
* is inside the bounds, and then has to check to see what image
* type it is. If you want things to be more efficient, access the
* pixels[] array directly.
*
* @webref image:pixels
* @brief Reads the color of any pixel or grabs a rectangle of pixels
* @usage web_application
* @param x x-coordinate of the pixel
* @param y y-coordinate of the pixel
* @see PApplet#set(int, int, int)
* @see PApplet#pixels
* @see PApplet#copy(PImage, int, int, int, int, int, int, int, int)
*/
public int get(int x, int y) {
return g.get(x, y);
}
/**
* @param w width of pixel rectangle to get
* @param h height of pixel rectangle to get
*/
public PImage get(int x, int y, int w, int h) {
return g.get(x, y, w, h);
}
/**
* Returns a copy of this PImage. Equivalent to get(0, 0, width, height).
*/
public PImage get() {
return g.get();
}
/**
* ( begin auto-generated from PImage_set.xml )
*
* Changes the color of any pixel or writes an image directly into the
* display window.<br />
* <br />
* The <b>x</b> and <b>y</b> parameters specify the pixel to change and the
* <b>color</b> parameter specifies the color value. The color parameter is
* affected by the current color mode (the default is RGB values from 0 to
* 255). When setting an image, the <b>x</b> and <b>y</b> parameters define
* the coordinates for the upper-left corner of the image, regardless of
* the current <b>imageMode()</b>.
* <br /><br />
* Setting the color of a single pixel with <b>set(x, y)</b> is easy, but
* not as fast as putting the data directly into <b>pixels[]</b>. The
* equivalent statement to <b>set(x, y, #000000)</b> using <b>pixels[]</b>
* is <b>pixels[y*width+x] = #000000</b>. See the reference for
* <b>pixels[]</b> for more information.
*
* ( end auto-generated )
*
* @webref image:pixels
* @brief writes a color to any pixel or writes an image into another
* @usage web_application
* @param x x-coordinate of the pixel
* @param y y-coordinate of the pixel
* @param c any value of the color datatype
* @see PImage#get(int, int, int, int)
* @see PImage#pixels
* @see PImage#copy(PImage, int, int, int, int, int, int, int, int)
*/
public void set(int x, int y, int c) {
if (recorder != null) recorder.set(x, y, c);
g.set(x, y, c);
}
/**
* <h3>Advanced</h3>
* Efficient method of drawing an image's pixels directly to this surface.
* No variations are employed, meaning that any scale, tint, or imageMode
* settings will be ignored.
*
* @param img image to draw on screen
*/
public void set(int x, int y, PImage img) {
if (recorder != null) recorder.set(x, y, img);
g.set(x, y, img);
}
/**
* ( begin auto-generated from PImage_mask.xml )
*
* Masks part of an image from displaying by loading another image and
* using it as an alpha channel. This mask image should only contain
* grayscale data, but only the blue color channel is used. The mask image
* needs to be the same size as the image to which it is applied.<br />
* <br />
* In addition to using a mask image, an integer array containing the alpha
* channel data can be specified directly. This method is useful for
* creating dynamically generated alpha masks. This array must be of the
* same length as the target image's pixels array and should contain only
* grayscale data of values between 0-255.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
*
* Set alpha channel for an image. Black colors in the source
* image will make the destination image completely transparent,
* and white will make things fully opaque. Gray values will
* be in-between steps.
* <P>
* Strictly speaking the "blue" value from the source image is
* used as the alpha color. For a fully grayscale image, this
* is correct, but for a color image it's not 100% accurate.
* For a more accurate conversion, first use filter(GRAY)
* which will make the image into a "correct" grayscale by
* performing a proper luminance-based conversion.
*
* @webref pimage:method
* @usage web_application
* @brief Masks part of an image with another image as an alpha channel
* @param maskArray array of integers used as the alpha channel, needs to be the same length as the image's pixel array
*/
public void mask(PImage img) {
if (recorder != null) recorder.mask(img);
g.mask(img);
}
public void filter(int kind) {
if (recorder != null) recorder.filter(kind);
g.filter(kind);
}
/**
* ( begin auto-generated from PImage_filter.xml )
*
* Filters an image as defined by one of the following modes:<br /><br
* />THRESHOLD - converts the image to black and white pixels depending if
* they are above or below the threshold defined by the level parameter.
* The level must be between 0.0 (black) and 1.0(white). If no level is
* specified, 0.5 is used.<br />
* <br />
* GRAY - converts any colors in the image to grayscale equivalents<br />
* <br />
* INVERT - sets each pixel to its inverse value<br />
* <br />
* POSTERIZE - limits each channel of the image to the number of colors
* specified as the level parameter<br />
* <br />
* BLUR - executes a Guassian blur with the level parameter specifying the
* extent of the blurring. If no level parameter is used, the blur is
* equivalent to Guassian blur of radius 1<br />
* <br />
* OPAQUE - sets the alpha channel to entirely opaque<br />
* <br />
* ERODE - reduces the light areas with the amount defined by the level
* parameter<br />
* <br />
* DILATE - increases the light areas with the amount defined by the level parameter
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Method to apply a variety of basic filters to this image.
* <P>
* <UL>
* <LI>filter(BLUR) provides a basic blur.
* <LI>filter(GRAY) converts the image to grayscale based on luminance.
* <LI>filter(INVERT) will invert the color components in the image.
* <LI>filter(OPAQUE) set all the high bits in the image to opaque
* <LI>filter(THRESHOLD) converts the image to black and white.
* <LI>filter(DILATE) grow white/light areas
* <LI>filter(ERODE) shrink white/light areas
* </UL>
* Luminance conversion code contributed by
* <A HREF="http://www.toxi.co.uk">toxi</A>
* <P/>
* Gaussian blur code contributed by
* <A HREF="http://incubator.quasimondo.com">Mario Klingemann</A>
*
* @webref image:pixels
* @brief Converts the image to grayscale or black and white
* @usage web_application
* @param kind Either THRESHOLD, GRAY, OPAQUE, INVERT, POSTERIZE, BLUR, ERODE, or DILATE
* @param param unique for each, see above
*/
public void filter(int kind, float param) {
if (recorder != null) recorder.filter(kind, param);
g.filter(kind, param);
}
/**
* ( begin auto-generated from PImage_copy.xml )
*
* Copies a region of pixels from one image into another. If the source and
* destination regions aren't the same size, it will automatically resize
* source pixels to fit the specified target region. No alpha information
* is used in the process, however if the source image has an alpha channel
* set, it will be copied as well.
* <br /><br />
* As of release 0149, this function ignores <b>imageMode()</b>.
*
* ( end auto-generated )
*
* @webref image:pixels
* @brief Copies the entire image
* @usage web_application
* @param sx X coordinate of the source's upper left corner
* @param sy Y coordinate of the source's upper left corner
* @param sw source image width
* @param sh source image height
* @param dx X coordinate of the destination's upper left corner
* @param dy Y coordinate of the destination's upper left corner
* @param dw destination image width
* @param dh destination image height
* @see PGraphics#alpha(int)
* @see PImage#blend(PImage, int, int, int, int, int, int, int, int, int)
*/
public void copy(int sx, int sy, int sw, int sh,
int dx, int dy, int dw, int dh) {
if (recorder != null) recorder.copy(sx, sy, sw, sh, dx, dy, dw, dh);
g.copy(sx, sy, sw, sh, dx, dy, dw, dh);
}
/**
* @param src an image variable referring to the source image.
*/
public void copy(PImage src,
int sx, int sy, int sw, int sh,
int dx, int dy, int dw, int dh) {
if (recorder != null) recorder.copy(src, sx, sy, sw, sh, dx, dy, dw, dh);
g.copy(src, sx, sy, sw, sh, dx, dy, dw, dh);
}
public void blend(int sx, int sy, int sw, int sh,
int dx, int dy, int dw, int dh, int mode) {
if (recorder != null) recorder.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode);
g.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode);
}
/**
* ( begin auto-generated from PImage_blend.xml )
*
* Blends a region of pixels into the image specified by the <b>img</b>
* parameter. These copies utilize full alpha channel support and a choice
* of the following modes to blend the colors of source pixels (A) with the
* ones of pixels in the destination image (B):<br />
* <br />
* BLEND - linear interpolation of colours: C = A*factor + B<br />
* <br />
* ADD - additive blending with white clip: C = min(A*factor + B, 255)<br />
* <br />
* SUBTRACT - subtractive blending with black clip: C = max(B - A*factor,
* 0)<br />
* <br />
* DARKEST - only the darkest colour succeeds: C = min(A*factor, B)<br />
* <br />
* LIGHTEST - only the lightest colour succeeds: C = max(A*factor, B)<br />
* <br />
* DIFFERENCE - subtract colors from underlying image.<br />
* <br />
* EXCLUSION - similar to DIFFERENCE, but less extreme.<br />
* <br />
* MULTIPLY - Multiply the colors, result will always be darker.<br />
* <br />
* SCREEN - Opposite multiply, uses inverse values of the colors.<br />
* <br />
* OVERLAY - A mix of MULTIPLY and SCREEN. Multiplies dark values,
* and screens light values.<br />
* <br />
* HARD_LIGHT - SCREEN when greater than 50% gray, MULTIPLY when lower.<br />
* <br />
* SOFT_LIGHT - Mix of DARKEST and LIGHTEST.
* Works like OVERLAY, but not as harsh.<br />
* <br />
* DODGE - Lightens light tones and increases contrast, ignores darks.
* Called "Color Dodge" in Illustrator and Photoshop.<br />
* <br />
* BURN - Darker areas are applied, increasing contrast, ignores lights.
* Called "Color Burn" in Illustrator and Photoshop.<br />
* <br />
* All modes use the alpha information (highest byte) of source image
* pixels as the blending factor. If the source and destination regions are
* different sizes, the image will be automatically resized to match the
* destination size. If the <b>srcImg</b> parameter is not used, the
* display window is used as the source image.<br />
* <br />
* As of release 0149, this function ignores <b>imageMode()</b>.
*
* ( end auto-generated )
*
* @webref image:pixels
* @brief Copies a pixel or rectangle of pixels using different blending modes
* @param src an image variable referring to the source image
* @param sx X coordinate of the source's upper left corner
* @param sy Y coordinate of the source's upper left corner
* @param sw source image width
* @param sh source image height
* @param dx X coordinate of the destinations's upper left corner
* @param dy Y coordinate of the destinations's upper left corner
* @param dw destination image width
* @param dh destination image height
* @param mode Either BLEND, ADD, SUBTRACT, LIGHTEST, DARKEST, DIFFERENCE, EXCLUSION, MULTIPLY, SCREEN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, BURN
*
* @see PApplet#alpha(int)
* @see PImage#copy(PImage, int, int, int, int, int, int, int, int)
* @see PImage#blendColor(int,int,int)
*/
public void blend(PImage src,
int sx, int sy, int sw, int sh,
int dx, int dy, int dw, int dh, int mode) {
if (recorder != null) recorder.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode);
g.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode);
}
}
| false | true | public PImage loadImage(String filename, String extension) { //, Object params) {
if (extension == null) {
String lower = filename.toLowerCase();
int dot = filename.lastIndexOf('.');
if (dot == -1) {
extension = "unknown"; // no extension found
}
extension = lower.substring(dot + 1);
// check for, and strip any parameters on the url, i.e.
// filename.jpg?blah=blah&something=that
int question = extension.indexOf('?');
if (question != -1) {
extension = extension.substring(0, question);
}
}
// just in case. them users will try anything!
extension = extension.toLowerCase();
if (extension.equals("tga")) {
try {
PImage image = loadImageTGA(filename);
// if (params != null) {
// image.setParams(g, params);
// }
return image;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
if (extension.equals("tif") || extension.equals("tiff")) {
byte bytes[] = loadBytes(filename);
PImage image = (bytes == null) ? null : PImage.loadTIFF(bytes);
// if (params != null) {
// image.setParams(g, params);
// }
return image;
}
// For jpeg, gif, and png, load them using createImage(),
// because the javax.imageio code was found to be much slower.
// http://dev.processing.org/bugs/show_bug.cgi?id=392
try {
if (extension.equals("jpg") || extension.equals("jpeg") ||
extension.equals("gif") || extension.equals("png") ||
extension.equals("unknown")) {
byte bytes[] = loadBytes(filename);
if (bytes == null) {
return null;
} else {
Image awtImage = Toolkit.getDefaultToolkit().createImage(bytes);
PImage image = loadImageMT(awtImage);
if (image.width == -1) {
System.err.println("The file " + filename +
" contains bad image data, or may not be an image.");
}
// if it's a .gif image, test to see if it has transparency
if (extension.equals("gif") || extension.equals("png")) {
image.checkAlpha();
}
// if (params != null) {
// image.setParams(g, params);
// }
return image;
}
}
} catch (Exception e) {
// show error, but move on to the stuff below, see if it'll work
e.printStackTrace();
}
if (loadImageFormats == null) {
loadImageFormats = ImageIO.getReaderFormatNames();
}
if (loadImageFormats != null) {
for (int i = 0; i < loadImageFormats.length; i++) {
if (extension.equals(loadImageFormats[i])) {
return loadImageIO(filename);
// PImage image = loadImageIO(filename);
// if (params != null) {
// image.setParams(g, params);
// }
// return image;
}
}
}
// failed, could not load image after all those attempts
System.err.println("Could not find a method to load " + filename);
return null;
}
public PImage requestImage(String filename) {
// return requestImage(filename, null, null);
return requestImage(filename, null);
}
/**
* ( begin auto-generated from requestImage.xml )
*
* This function load images on a separate thread so that your sketch does
* not freeze while images load during <b>setup()</b>. While the image is
* loading, its width and height will be 0. If an error occurs while
* loading the image, its width and height will be set to -1. You'll know
* when the image has loaded properly because its width and height will be
* greater than 0. Asynchronous image loading (particularly when
* downloading from a server) can dramatically improve performance.<br />
* <br/> <b>extension</b> parameter is used to determine the image type in
* cases where the image filename does not end with a proper extension.
* Specify the extension as the second parameter to <b>requestImage()</b>.
*
* ( end auto-generated )
*
* @webref image:loading_displaying
* @param filename name of the file to load, can be .gif, .jpg, .tga, or a handful of other image types depending on your platform
* @param extension the type of image to load, for example "png", "gif", "jpg"
* @see PApplet#loadImage(String, String)
* @see PImage#PImage
*/
public PImage requestImage(String filename, String extension) {
PImage vessel = createImage(0, 0, ARGB);
AsyncImageLoader ail =
new AsyncImageLoader(filename, extension, vessel);
ail.start();
return vessel;
}
// /**
// * @nowebref
// */
// public PImage requestImage(String filename, String extension, Object params) {
// PImage vessel = createImage(0, 0, ARGB, params);
// AsyncImageLoader ail =
// new AsyncImageLoader(filename, extension, vessel);
// ail.start();
// return vessel;
// }
/**
* By trial and error, four image loading threads seem to work best when
* loading images from online. This is consistent with the number of open
* connections that web browsers will maintain. The variable is made public
* (however no accessor has been added since it's esoteric) if you really
* want to have control over the value used. For instance, when loading local
* files, it might be better to only have a single thread (or two) loading
* images so that you're disk isn't simply jumping around.
*/
public int requestImageMax = 4;
volatile int requestImageCount;
class AsyncImageLoader extends Thread {
String filename;
String extension;
PImage vessel;
public AsyncImageLoader(String filename, String extension, PImage vessel) {
this.filename = filename;
this.extension = extension;
this.vessel = vessel;
}
@Override
public void run() {
while (requestImageCount == requestImageMax) {
try {
Thread.sleep(10);
} catch (InterruptedException e) { }
}
requestImageCount++;
PImage actual = loadImage(filename, extension);
// An error message should have already printed
if (actual == null) {
vessel.width = -1;
vessel.height = -1;
} else {
vessel.width = actual.width;
vessel.height = actual.height;
vessel.format = actual.format;
vessel.pixels = actual.pixels;
}
requestImageCount--;
}
}
/**
* Load an AWT image synchronously by setting up a MediaTracker for
* a single image, and blocking until it has loaded.
*/
protected PImage loadImageMT(Image awtImage) {
MediaTracker tracker = new MediaTracker(this);
tracker.addImage(awtImage, 0);
try {
tracker.waitForAll();
} catch (InterruptedException e) {
//e.printStackTrace(); // non-fatal, right?
}
PImage image = new PImage(awtImage);
image.parent = this;
return image;
}
/**
* Use Java 1.4 ImageIO methods to load an image.
*/
protected PImage loadImageIO(String filename) {
InputStream stream = createInput(filename);
if (stream == null) {
System.err.println("The image " + filename + " could not be found.");
return null;
}
try {
BufferedImage bi = ImageIO.read(stream);
PImage outgoing = new PImage(bi.getWidth(), bi.getHeight());
outgoing.parent = this;
bi.getRGB(0, 0, outgoing.width, outgoing.height,
outgoing.pixels, 0, outgoing.width);
// check the alpha for this image
// was gonna call getType() on the image to see if RGB or ARGB,
// but it's not actually useful, since gif images will come through
// as TYPE_BYTE_INDEXED, which means it'll still have to check for
// the transparency. also, would have to iterate through all the other
// types and guess whether alpha was in there, so.. just gonna stick
// with the old method.
outgoing.checkAlpha();
// return the image
return outgoing;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Targa image loader for RLE-compressed TGA files.
* <p>
* Rewritten for 0115 to read/write RLE-encoded targa images.
* For 0125, non-RLE encoded images are now supported, along with
* images whose y-order is reversed (which is standard for TGA files).
*/
protected PImage loadImageTGA(String filename) throws IOException {
InputStream is = createInput(filename);
if (is == null) return null;
byte header[] = new byte[18];
int offset = 0;
do {
int count = is.read(header, offset, header.length - offset);
if (count == -1) return null;
offset += count;
} while (offset < 18);
/*
header[2] image type code
2 (0x02) - Uncompressed, RGB images.
3 (0x03) - Uncompressed, black and white images.
10 (0x0A) - Runlength encoded RGB images.
11 (0x0B) - Compressed, black and white images. (grayscale?)
header[16] is the bit depth (8, 24, 32)
header[17] image descriptor (packed bits)
0x20 is 32 = origin upper-left
0x28 is 32 + 8 = origin upper-left + 32 bits
7 6 5 4 3 2 1 0
128 64 32 16 8 4 2 1
*/
int format = 0;
if (((header[2] == 3) || (header[2] == 11)) && // B&W, plus RLE or not
(header[16] == 8) && // 8 bits
((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32 bit
format = ALPHA;
} else if (((header[2] == 2) || (header[2] == 10)) && // RGB, RLE or not
(header[16] == 24) && // 24 bits
((header[17] == 0x20) || (header[17] == 0))) { // origin
format = RGB;
} else if (((header[2] == 2) || (header[2] == 10)) &&
(header[16] == 32) &&
((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32
format = ARGB;
}
if (format == 0) {
System.err.println("Unknown .tga file format for " + filename);
//" (" + header[2] + " " +
//(header[16] & 0xff) + " " +
//hex(header[17], 2) + ")");
return null;
}
int w = ((header[13] & 0xff) << 8) + (header[12] & 0xff);
int h = ((header[15] & 0xff) << 8) + (header[14] & 0xff);
PImage outgoing = createImage(w, h, format);
// where "reversed" means upper-left corner (normal for most of
// the modernized world, but "reversed" for the tga spec)
boolean reversed = (header[17] & 0x20) != 0;
if ((header[2] == 2) || (header[2] == 3)) { // not RLE encoded
if (reversed) {
int index = (h-1) * w;
switch (format) {
case ALPHA:
for (int y = h-1; y >= 0; y--) {
for (int x = 0; x < w; x++) {
outgoing.pixels[index + x] = is.read();
}
index -= w;
}
break;
case RGB:
for (int y = h-1; y >= 0; y--) {
for (int x = 0; x < w; x++) {
outgoing.pixels[index + x] =
is.read() | (is.read() << 8) | (is.read() << 16) |
0xff000000;
}
index -= w;
}
break;
case ARGB:
for (int y = h-1; y >= 0; y--) {
for (int x = 0; x < w; x++) {
outgoing.pixels[index + x] =
is.read() | (is.read() << 8) | (is.read() << 16) |
(is.read() << 24);
}
index -= w;
}
}
} else { // not reversed
int count = w * h;
switch (format) {
case ALPHA:
for (int i = 0; i < count; i++) {
outgoing.pixels[i] = is.read();
}
break;
case RGB:
for (int i = 0; i < count; i++) {
outgoing.pixels[i] =
is.read() | (is.read() << 8) | (is.read() << 16) |
0xff000000;
}
break;
case ARGB:
for (int i = 0; i < count; i++) {
outgoing.pixels[i] =
is.read() | (is.read() << 8) | (is.read() << 16) |
(is.read() << 24);
}
break;
}
}
} else { // header[2] is 10 or 11
int index = 0;
int px[] = outgoing.pixels;
while (index < px.length) {
int num = is.read();
boolean isRLE = (num & 0x80) != 0;
if (isRLE) {
num -= 127; // (num & 0x7F) + 1
int pixel = 0;
switch (format) {
case ALPHA:
pixel = is.read();
break;
case RGB:
pixel = 0xFF000000 |
is.read() | (is.read() << 8) | (is.read() << 16);
//(is.read() << 16) | (is.read() << 8) | is.read();
break;
case ARGB:
pixel = is.read() |
(is.read() << 8) | (is.read() << 16) | (is.read() << 24);
break;
}
for (int i = 0; i < num; i++) {
px[index++] = pixel;
if (index == px.length) break;
}
} else { // write up to 127 bytes as uncompressed
num += 1;
switch (format) {
case ALPHA:
for (int i = 0; i < num; i++) {
px[index++] = is.read();
}
break;
case RGB:
for (int i = 0; i < num; i++) {
px[index++] = 0xFF000000 |
is.read() | (is.read() << 8) | (is.read() << 16);
//(is.read() << 16) | (is.read() << 8) | is.read();
}
break;
case ARGB:
for (int i = 0; i < num; i++) {
px[index++] = is.read() | //(is.read() << 24) |
(is.read() << 8) | (is.read() << 16) | (is.read() << 24);
//(is.read() << 16) | (is.read() << 8) | is.read();
}
break;
}
}
}
if (!reversed) {
int[] temp = new int[w];
for (int y = 0; y < h/2; y++) {
int z = (h-1) - y;
System.arraycopy(px, y*w, temp, 0, w);
System.arraycopy(px, z*w, px, y*w, w);
System.arraycopy(temp, 0, px, z*w, w);
}
}
}
return outgoing;
}
//////////////////////////////////////////////////////////////
// DATA I/O
/**
* @webref input:files
* @brief Creates a new XML object
* @param name the name to be given to the root element of the new XML object
* @return an XML object, or null
* @see PApplet#loadXML(String)
* @see PApplet#parseXML(String)
*/
public XML createXML(String name) {
try {
return new XML(name);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* @webref input:files
* @param filename name of a file in the data folder or a URL.
* @see PApplet#createXML(String)
* @see PApplet#parseXML(String)
* @see PApplet#saveXML(String)
* @see PApplet#loadBytes(String)
* @see PApplet#loadStrings(String)
* @see PApplet#loadTable(String)
*/
public XML loadXML(String filename) {
return loadXML(filename, null);
}
// version that uses 'options' though there are currently no supported options
public XML loadXML(String filename, String options) {
try {
return new XML(createInput(filename), options);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* @webref input:files
* @brief Converts String content to an XML object
* @param data the content to be parsed as XML
* @return an XML object, or null
* @see PApplet#createXML(String)
* @see PApplet#loadXML(String)
* @see PApplet#saveXML(String)
*/
public XML parseXML(String xmlString) {
return parseXML(xmlString, null);
}
public XML parseXML(String xmlString, String options) {
try {
return XML.parse(xmlString, options);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* @webref output:files
* @param xml the XML object to save to disk
* @param filename name of the file to write to
* @see PApplet#createXML(String)
* @see PApplet#loadXML(String)
* @see PApplet#parseXML(String)
*/
public boolean saveXML(XML xml, String filename) {
return saveXML(xml, filename, null);
}
public boolean saveXML(XML xml, String filename, String options) {
return xml.save(saveFile(filename), options);
}
/**
* @webref input:files
* @see PApplet#loadTable(String)
* @see PApplet#saveTable(Table, String)
*/
public Table createTable() {
return new Table();
}
/**
* @webref input:files
* @param filename name of a file in the data folder or a URL.
* @see PApplet#createTable()
* @see PApplet#saveTable(Table, String)
* @see PApplet#loadBytes(String)
* @see PApplet#loadStrings(String)
* @see PApplet#loadXML(String)
*/
public Table loadTable(String filename) {
return loadTable(filename, null);
}
/**
* @param options may contain "header", "tsv", or "csv" separated by commas
*/
public Table loadTable(String filename, String options) {
try {
String ext = checkExtension(filename);
if (ext != null) {
if (ext.equals("csv") || ext.equals("tsv") || ext.equals("bin")) {
if (options == null) {
options = ext;
} else {
options = ext + "," + options;
}
}
}
return new Table(createInput(filename), options);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* @webref input:files
* @param table the Table object to save to a file
* @param filename the filename to which the Table should be saved
* @see PApplet#createTable()
* @see PApplet#loadTable(String)
*/
public boolean saveTable(Table table, String filename) {
return saveTable(table, filename, null);
}
/**
* @param options may contain "header", "tsv", or "csv" separated by commas
*/
public boolean saveTable(Table table, String filename, String options) {
try {
table.save(saveFile(filename), options);
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
protected String checkExtension(String filename) {
int index = filename.lastIndexOf('.');
if (index == -1) {
return null;
}
return filename.substring(index + 1).toLowerCase();
}
//////////////////////////////////////////////////////////////
// FONT I/O
/**
* ( begin auto-generated from loadFont.xml )
*
* Loads a font into a variable of type <b>PFont</b>. To load correctly,
* fonts must be located in the data directory of the current sketch. To
* create a font to use with Processing, select "Create Font..." from the
* Tools menu. This will create a font in the format Processing requires
* and also adds it to the current sketch's data directory.<br />
* <br />
* Like <b>loadImage()</b> and other functions that load data, the
* <b>loadFont()</b> function should not be used inside <b>draw()</b>,
* because it will slow down the sketch considerably, as the font will be
* re-loaded from the disk (or network) on each frame.<br />
* <br />
* For most renderers, Processing displays fonts using the .vlw font
* format, which uses images for each letter, rather than defining them
* through vector data. When <b>hint(ENABLE_NATIVE_FONTS)</b> is used with
* the JAVA2D renderer, the native version of a font will be used if it is
* installed on the user's machine.<br />
* <br />
* Using <b>createFont()</b> (instead of loadFont) enables vector data to
* be used with the JAVA2D (default) renderer setting. This can be helpful
* when many font sizes are needed, or when using any renderer based on
* JAVA2D, such as the PDF library.
*
* ( end auto-generated )
* @webref typography:loading_displaying
* @param filename name of the font to load
* @see PFont#PFont(Font, boolean)
* @see PGraphics#textFont(PFont, float)
* @see PApplet#createFont(String, float, boolean, char[])
*/
public PFont loadFont(String filename) {
try {
InputStream input = createInput(filename);
return new PFont(input);
} catch (Exception e) {
die("Could not load font " + filename + ". " +
"Make sure that the font has been copied " +
"to the data folder of your sketch.", e);
}
return null;
}
/**
* Used by PGraphics to remove the requirement for loading a font!
*/
protected PFont createDefaultFont(float size) {
// Font f = new Font("SansSerif", Font.PLAIN, 12);
// println("n: " + f.getName());
// println("fn: " + f.getFontName());
// println("ps: " + f.getPSName());
return createFont("Lucida Sans", size, true, null);
}
public PFont createFont(String name, float size) {
return createFont(name, size, true, null);
}
public PFont createFont(String name, float size, boolean smooth) {
return createFont(name, size, smooth, null);
}
/**
* ( begin auto-generated from createFont.xml )
*
* Dynamically converts a font to the format used by Processing from either
* a font name that's installed on the computer, or from a .ttf or .otf
* file inside the sketches "data" folder. This function is an advanced
* feature for precise control. On most occasions you should create fonts
* through selecting "Create Font..." from the Tools menu.
* <br /><br />
* Use the <b>PFont.list()</b> method to first determine the names for the
* fonts recognized by the computer and are compatible with this function.
* Because of limitations in Java, not all fonts can be used and some might
* work with one operating system and not others. When sharing a sketch
* with other people or posting it on the web, you may need to include a
* .ttf or .otf version of your font in the data directory of the sketch
* because other people might not have the font installed on their
* computer. Only fonts that can legally be distributed should be included
* with a sketch.
* <br /><br />
* The <b>size</b> parameter states the font size you want to generate. The
* <b>smooth</b> parameter specifies if the font should be antialiased or
* not, and the <b>charset</b> parameter is an array of chars that
* specifies the characters to generate.
* <br /><br />
* This function creates a bitmapped version of a font in the same manner
* as the Create Font tool. It loads a font by name, and converts it to a
* series of images based on the size of the font. When possible, the
* <b>text()</b> function will use a native font rather than the bitmapped
* version created behind the scenes with <b>createFont()</b>. For
* instance, when using P2D, the actual native version of the font will be
* employed by the sketch, improving drawing quality and performance. With
* the P3D renderer, the bitmapped version will be used. While this can
* drastically improve speed and appearance, results are poor when
* exporting if the sketch does not include the .otf or .ttf file, and the
* requested font is not available on the machine running the sketch.
*
* ( end auto-generated )
* @webref typography:loading_displaying
* @param name name of the font to load
* @param size point size of the font
* @param smooth true for an antialiased font, false for aliased
* @param charset array containing characters to be generated
* @see PFont#PFont
* @see PGraphics#textFont(PFont, float)
* @see PGraphics#text(String, float, float, float, float, float)
* @see PApplet#loadFont(String)
*/
public PFont createFont(String name, float size,
boolean smooth, char charset[]) {
String lowerName = name.toLowerCase();
Font baseFont = null;
try {
InputStream stream = null;
if (lowerName.endsWith(".otf") || lowerName.endsWith(".ttf")) {
stream = createInput(name);
if (stream == null) {
System.err.println("The font \"" + name + "\" " +
"is missing or inaccessible, make sure " +
"the URL is valid or that the file has been " +
"added to your sketch and is readable.");
return null;
}
baseFont = Font.createFont(Font.TRUETYPE_FONT, createInput(name));
} else {
baseFont = PFont.findFont(name);
}
return new PFont(baseFont.deriveFont(size), smooth, charset,
stream != null);
} catch (Exception e) {
System.err.println("Problem createFont(" + name + ")");
e.printStackTrace();
return null;
}
}
//////////////////////////////////////////////////////////////
// FILE/FOLDER SELECTION
private Frame selectFrame;
private Frame selectFrame() {
if (frame != null) {
selectFrame = frame;
} else if (selectFrame == null) {
Component comp = getParent();
while (comp != null) {
if (comp instanceof Frame) {
selectFrame = (Frame) comp;
break;
}
comp = comp.getParent();
}
// Who you callin' a hack?
if (selectFrame == null) {
selectFrame = new Frame();
}
}
return selectFrame;
}
/**
* Open a platform-specific file chooser dialog to select a file for input.
* After the selection is made, the selected File will be passed to the
* 'callback' function. If the dialog is closed or canceled, null will be
* sent to the function, so that the program is not waiting for additional
* input. The callback is necessary because of how threading works.
*
* <pre>
* void setup() {
* selectInput("Select a file to process:", "fileSelected");
* }
*
* void fileSelected(File selection) {
* if (selection == null) {
* println("Window was closed or the user hit cancel.");
* } else {
* println("User selected " + fileSeleted.getAbsolutePath());
* }
* }
* </pre>
*
* For advanced users, the method must be 'public', which is true for all
* methods inside a sketch when run from the PDE, but must explicitly be
* set when using Eclipse or other development environments.
*
* @webref input:files
* @param prompt message to the user
* @param callback name of the method to be called when the selection is made
*/
public void selectInput(String prompt, String callback) {
selectInput(prompt, callback, null);
}
public void selectInput(String prompt, String callback, File file) {
selectInput(prompt, callback, file, this);
}
public void selectInput(String prompt, String callback,
File file, Object callbackObject) {
selectInput(prompt, callback, file, callbackObject, selectFrame());
}
static public void selectInput(String prompt, String callbackMethod,
File file, Object callbackObject, Frame parent) {
selectImpl(prompt, callbackMethod, file, callbackObject, parent, FileDialog.LOAD);
}
/**
* See selectInput() for details.
*
* @webref output:files
* @param prompt message to the user
* @param callback name of the method to be called when the selection is made
*/
public void selectOutput(String prompt, String callback) {
selectOutput(prompt, callback, null);
}
public void selectOutput(String prompt, String callback, File file) {
selectOutput(prompt, callback, file, this);
}
public void selectOutput(String prompt, String callback,
File file, Object callbackObject) {
selectOutput(prompt, callback, file, callbackObject, selectFrame());
}
static public void selectOutput(String prompt, String callbackMethod,
File file, Object callbackObject, Frame parent) {
selectImpl(prompt, callbackMethod, file, callbackObject, parent, FileDialog.SAVE);
}
static protected void selectImpl(final String prompt,
final String callbackMethod,
final File defaultSelection,
final Object callbackObject,
final Frame parentFrame,
final int mode) {
EventQueue.invokeLater(new Runnable() {
public void run() {
File selectedFile = null;
if (useNativeSelect) {
FileDialog dialog = new FileDialog(parentFrame, prompt, mode);
if (defaultSelection != null) {
dialog.setDirectory(defaultSelection.getParent());
dialog.setFile(defaultSelection.getName());
}
dialog.setVisible(true);
String directory = dialog.getDirectory();
String filename = dialog.getFile();
if (filename != null) {
selectedFile = new File(directory, filename);
}
} else {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle(prompt);
if (defaultSelection != null) {
chooser.setSelectedFile(defaultSelection);
}
int result = -1;
if (mode == FileDialog.SAVE) {
result = chooser.showSaveDialog(parentFrame);
} else if (mode == FileDialog.LOAD) {
result = chooser.showOpenDialog(parentFrame);
}
if (result == JFileChooser.APPROVE_OPTION) {
selectedFile = chooser.getSelectedFile();
}
}
selectCallback(selectedFile, callbackMethod, callbackObject);
}
});
}
/**
* See selectInput() for details.
*
* @webref input:files
* @param prompt message to the user
* @param callback name of the method to be called when the selection is made
*/
public void selectFolder(String prompt, String callback) {
selectFolder(prompt, callback, null);
}
public void selectFolder(String prompt, String callback, File file) {
selectFolder(prompt, callback, file, this);
}
public void selectFolder(String prompt, String callback,
File file, Object callbackObject) {
selectFolder(prompt, callback, file, callbackObject, selectFrame());
}
static public void selectFolder(final String prompt,
final String callbackMethod,
final File defaultSelection,
final Object callbackObject,
final Frame parentFrame) {
EventQueue.invokeLater(new Runnable() {
public void run() {
File selectedFile = null;
if (platform == MACOSX && useNativeSelect != false) {
FileDialog fileDialog =
new FileDialog(parentFrame, prompt, FileDialog.LOAD);
System.setProperty("apple.awt.fileDialogForDirectories", "true");
fileDialog.setVisible(true);
System.setProperty("apple.awt.fileDialogForDirectories", "false");
String filename = fileDialog.getFile();
if (filename != null) {
selectedFile = new File(fileDialog.getDirectory(), fileDialog.getFile());
}
} else {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle(prompt);
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (defaultSelection != null) {
fileChooser.setSelectedFile(defaultSelection);
}
int result = fileChooser.showOpenDialog(parentFrame);
if (result == JFileChooser.APPROVE_OPTION) {
selectedFile = fileChooser.getSelectedFile();
}
}
selectCallback(selectedFile, callbackMethod, callbackObject);
}
});
}
static private void selectCallback(File selectedFile,
String callbackMethod,
Object callbackObject) {
try {
Class<?> callbackClass = callbackObject.getClass();
Method selectMethod =
callbackClass.getMethod(callbackMethod, new Class[] { File.class });
selectMethod.invoke(callbackObject, new Object[] { selectedFile });
} catch (IllegalAccessException iae) {
System.err.println(callbackMethod + "() must be public");
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (NoSuchMethodException nsme) {
System.err.println(callbackMethod + "() could not be found");
}
}
//////////////////////////////////////////////////////////////
// READERS AND WRITERS
/**
* ( begin auto-generated from createReader.xml )
*
* Creates a <b>BufferedReader</b> object that can be used to read files
* line-by-line as individual <b>String</b> objects. This is the complement
* to the <b>createWriter()</b> function.
* <br/> <br/>
* Starting with Processing release 0134, all files loaded and saved by the
* Processing API use UTF-8 encoding. In previous releases, the default
* encoding for your platform was used, which causes problems when files
* are moved to other platforms.
*
* ( end auto-generated )
* @webref input:files
* @param filename name of the file to be opened
* @see BufferedReader
* @see PApplet#createWriter(String)
* @see PrintWriter
*/
public BufferedReader createReader(String filename) {
try {
InputStream is = createInput(filename);
if (is == null) {
System.err.println(filename + " does not exist or could not be read");
return null;
}
return createReader(is);
} catch (Exception e) {
if (filename == null) {
System.err.println("Filename passed to reader() was null");
} else {
System.err.println("Couldn't create a reader for " + filename);
}
}
return null;
}
/**
* @nowebref
*/
static public BufferedReader createReader(File file) {
try {
InputStream is = new FileInputStream(file);
if (file.getName().toLowerCase().endsWith(".gz")) {
is = new GZIPInputStream(is);
}
return createReader(is);
} catch (Exception e) {
if (file == null) {
throw new RuntimeException("File passed to createReader() was null");
} else {
e.printStackTrace();
throw new RuntimeException("Couldn't create a reader for " +
file.getAbsolutePath());
}
}
//return null;
}
/**
* @nowebref
* I want to read lines from a stream. If I have to type the
* following lines any more I'm gonna send Sun my medical bills.
*/
static public BufferedReader createReader(InputStream input) {
InputStreamReader isr = null;
try {
isr = new InputStreamReader(input, "UTF-8");
} catch (UnsupportedEncodingException e) { } // not gonna happen
return new BufferedReader(isr);
}
/**
* ( begin auto-generated from createWriter.xml )
*
* Creates a new file in the sketch folder, and a <b>PrintWriter</b> object
* to write to it. For the file to be made correctly, it should be flushed
* and must be closed with its <b>flush()</b> and <b>close()</b> methods
* (see above example).
* <br/> <br/>
* Starting with Processing release 0134, all files loaded and saved by the
* Processing API use UTF-8 encoding. In previous releases, the default
* encoding for your platform was used, which causes problems when files
* are moved to other platforms.
*
* ( end auto-generated )
*
* @webref output:files
* @param filename name of the file to be created
* @see PrintWriter
* @see PApplet#createReader
* @see BufferedReader
*/
public PrintWriter createWriter(String filename) {
return createWriter(saveFile(filename));
}
/**
* @nowebref
* I want to print lines to a file. I have RSI from typing these
* eight lines of code so many times.
*/
static public PrintWriter createWriter(File file) {
try {
createPath(file); // make sure in-between folders exist
OutputStream output = new FileOutputStream(file);
if (file.getName().toLowerCase().endsWith(".gz")) {
output = new GZIPOutputStream(output);
}
return createWriter(output);
} catch (Exception e) {
if (file == null) {
throw new RuntimeException("File passed to createWriter() was null");
} else {
e.printStackTrace();
throw new RuntimeException("Couldn't create a writer for " +
file.getAbsolutePath());
}
}
//return null;
}
/**
* @nowebref
* I want to print lines to a file. Why am I always explaining myself?
* It's the JavaSoft API engineers who need to explain themselves.
*/
static public PrintWriter createWriter(OutputStream output) {
try {
BufferedOutputStream bos = new BufferedOutputStream(output, 8192);
OutputStreamWriter osw = new OutputStreamWriter(bos, "UTF-8");
return new PrintWriter(osw);
} catch (UnsupportedEncodingException e) { } // not gonna happen
return null;
}
//////////////////////////////////////////////////////////////
// FILE INPUT
/**
* @deprecated As of release 0136, use createInput() instead.
*/
public InputStream openStream(String filename) {
return createInput(filename);
}
/**
* ( begin auto-generated from createInput.xml )
*
* This is a function for advanced programmers to open a Java InputStream.
* It's useful if you want to use the facilities provided by PApplet to
* easily open files from the data folder or from a URL, but want an
* InputStream object so that you can use other parts of Java to take more
* control of how the stream is read.<br />
* <br />
* The filename passed in can be:<br />
* - A URL, for instance <b>openStream("http://processing.org/")</b><br />
* - A file in the sketch's <b>data</b> folder<br />
* - The full path to a file to be opened locally (when running as an
* application)<br />
* <br />
* If the requested item doesn't exist, null is returned. If not online,
* this will also check to see if the user is asking for a file whose name
* isn't properly capitalized. If capitalization is different, an error
* will be printed to the console. This helps prevent issues that appear
* when a sketch is exported to the web, where case sensitivity matters, as
* opposed to running from inside the Processing Development Environment on
* Windows or Mac OS, where case sensitivity is preserved but ignored.<br />
* <br />
* If the file ends with <b>.gz</b>, the stream will automatically be gzip
* decompressed. If you don't want the automatic decompression, use the
* related function <b>createInputRaw()</b>.
* <br />
* In earlier releases, this function was called <b>openStream()</b>.<br />
* <br />
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Simplified method to open a Java InputStream.
* <p>
* This method is useful if you want to use the facilities provided
* by PApplet to easily open things from the data folder or from a URL,
* but want an InputStream object so that you can use other Java
* methods to take more control of how the stream is read.
* <p>
* If the requested item doesn't exist, null is returned.
* (Prior to 0096, die() would be called, killing the applet)
* <p>
* For 0096+, the "data" folder is exported intact with subfolders,
* and openStream() properly handles subdirectories from the data folder
* <p>
* If not online, this will also check to see if the user is asking
* for a file whose name isn't properly capitalized. This helps prevent
* issues when a sketch is exported to the web, where case sensitivity
* matters, as opposed to Windows and the Mac OS default where
* case sensitivity is preserved but ignored.
* <p>
* It is strongly recommended that libraries use this method to open
* data files, so that the loading sequence is handled in the same way
* as functions like loadBytes(), loadImage(), etc.
* <p>
* The filename passed in can be:
* <UL>
* <LI>A URL, for instance openStream("http://processing.org/");
* <LI>A file in the sketch's data folder
* <LI>Another file to be opened locally (when running as an application)
* </UL>
*
* @webref input:files
* @param filename the name of the file to use as input
* @see PApplet#createOutput(String)
* @see PApplet#selectOutput(String)
* @see PApplet#selectInput(String)
*
*/
public InputStream createInput(String filename) {
InputStream input = createInputRaw(filename);
if ((input != null) && filename.toLowerCase().endsWith(".gz")) {
try {
return new GZIPInputStream(input);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
return input;
}
/**
* Call openStream() without automatic gzip decompression.
*/
public InputStream createInputRaw(String filename) {
InputStream stream = null;
if (filename == null) return null;
if (filename.length() == 0) {
// an error will be called by the parent function
//System.err.println("The filename passed to openStream() was empty.");
return null;
}
// safe to check for this as a url first. this will prevent online
// access logs from being spammed with GET /sketchfolder/http://blahblah
if (filename.contains(":")) { // at least smells like URL
try {
URL url = new URL(filename);
stream = url.openStream();
return stream;
} catch (MalformedURLException mfue) {
// not a url, that's fine
} catch (FileNotFoundException fnfe) {
// Java 1.5 likes to throw this when URL not available. (fix for 0119)
// http://dev.processing.org/bugs/show_bug.cgi?id=403
} catch (IOException e) {
// changed for 0117, shouldn't be throwing exception
e.printStackTrace();
//System.err.println("Error downloading from URL " + filename);
return null;
//throw new RuntimeException("Error downloading from URL " + filename);
}
}
// Moved this earlier than the getResourceAsStream() checks, because
// calling getResourceAsStream() on a directory lists its contents.
// http://dev.processing.org/bugs/show_bug.cgi?id=716
try {
// First see if it's in a data folder. This may fail by throwing
// a SecurityException. If so, this whole block will be skipped.
File file = new File(dataPath(filename));
if (!file.exists()) {
// next see if it's just in the sketch folder
file = new File(sketchPath, filename);
}
if (file.isDirectory()) {
return null;
}
if (file.exists()) {
try {
// handle case sensitivity check
String filePath = file.getCanonicalPath();
String filenameActual = new File(filePath).getName();
// make sure there isn't a subfolder prepended to the name
String filenameShort = new File(filename).getName();
// if the actual filename is the same, but capitalized
// differently, warn the user.
//if (filenameActual.equalsIgnoreCase(filenameShort) &&
//!filenameActual.equals(filenameShort)) {
if (!filenameActual.equals(filenameShort)) {
throw new RuntimeException("This file is named " +
filenameActual + " not " +
filename + ". Rename the file " +
"or change your code.");
}
} catch (IOException e) { }
}
// if this file is ok, may as well just load it
stream = new FileInputStream(file);
if (stream != null) return stream;
// have to break these out because a general Exception might
// catch the RuntimeException being thrown above
} catch (IOException ioe) {
} catch (SecurityException se) { }
// Using getClassLoader() prevents java from converting dots
// to slashes or requiring a slash at the beginning.
// (a slash as a prefix means that it'll load from the root of
// the jar, rather than trying to dig into the package location)
ClassLoader cl = getClass().getClassLoader();
// by default, data files are exported to the root path of the jar.
// (not the data folder) so check there first.
stream = cl.getResourceAsStream("data/" + filename);
if (stream != null) {
String cn = stream.getClass().getName();
// this is an irritation of sun's java plug-in, which will return
// a non-null stream for an object that doesn't exist. like all good
// things, this is probably introduced in java 1.5. awesome!
// http://dev.processing.org/bugs/show_bug.cgi?id=359
if (!cn.equals("sun.plugin.cache.EmptyInputStream")) {
return stream;
}
}
// When used with an online script, also need to check without the
// data folder, in case it's not in a subfolder called 'data'.
// http://dev.processing.org/bugs/show_bug.cgi?id=389
stream = cl.getResourceAsStream(filename);
if (stream != null) {
String cn = stream.getClass().getName();
if (!cn.equals("sun.plugin.cache.EmptyInputStream")) {
return stream;
}
}
// Finally, something special for the Internet Explorer users. Turns out
// that we can't get files that are part of the same folder using the
// methods above when using IE, so we have to resort to the old skool
// getDocumentBase() from teh applet dayz. 1996, my brotha.
try {
URL base = getDocumentBase();
if (base != null) {
URL url = new URL(base, filename);
URLConnection conn = url.openConnection();
return conn.getInputStream();
// if (conn instanceof HttpURLConnection) {
// HttpURLConnection httpConnection = (HttpURLConnection) conn;
// // test for 401 result (HTTP only)
// int responseCode = httpConnection.getResponseCode();
// }
}
} catch (Exception e) { } // IO or NPE or...
// Now try it with a 'data' subfolder. getting kinda desperate for data...
try {
URL base = getDocumentBase();
if (base != null) {
URL url = new URL(base, "data/" + filename);
URLConnection conn = url.openConnection();
return conn.getInputStream();
}
} catch (Exception e) { }
try {
// attempt to load from a local file, used when running as
// an application, or as a signed applet
try { // first try to catch any security exceptions
try {
stream = new FileInputStream(dataPath(filename));
if (stream != null) return stream;
} catch (IOException e2) { }
try {
stream = new FileInputStream(sketchPath(filename));
if (stream != null) return stream;
} catch (Exception e) { } // ignored
try {
stream = new FileInputStream(filename);
if (stream != null) return stream;
} catch (IOException e1) { }
} catch (SecurityException se) { } // online, whups
} catch (Exception e) {
//die(e.getMessage(), e);
e.printStackTrace();
}
return null;
}
/**
* @nowebref
*/
static public InputStream createInput(File file) {
if (file == null) {
throw new IllegalArgumentException("File passed to createInput() was null");
}
try {
InputStream input = new FileInputStream(file);
if (file.getName().toLowerCase().endsWith(".gz")) {
return new GZIPInputStream(input);
}
return input;
} catch (IOException e) {
System.err.println("Could not createInput() for " + file);
e.printStackTrace();
return null;
}
}
/**
* ( begin auto-generated from loadBytes.xml )
*
* Reads the contents of a file or url and places it in a byte array. If a
* file is specified, it must be located in the sketch's "data"
* directory/folder.<br />
* <br />
* The filename parameter can also be a URL to a file found online. For
* security reasons, a Processing sketch found online can only download
* files from the same server from which it came. Getting around this
* restriction requires a <a
* href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</a>.
*
* ( end auto-generated )
* @webref input:files
* @param filename name of a file in the data folder or a URL.
* @see PApplet#loadStrings(String)
* @see PApplet#saveStrings(String, String[])
* @see PApplet#saveBytes(String, byte[])
*
*/
public byte[] loadBytes(String filename) {
InputStream is = createInput(filename);
if (is != null) return loadBytes(is);
System.err.println("The file \"" + filename + "\" " +
"is missing or inaccessible, make sure " +
"the URL is valid or that the file has been " +
"added to your sketch and is readable.");
return null;
}
/**
* @nowebref
*/
static public byte[] loadBytes(InputStream input) {
try {
BufferedInputStream bis = new BufferedInputStream(input);
ByteArrayOutputStream out = new ByteArrayOutputStream();
int c = bis.read();
while (c != -1) {
out.write(c);
c = bis.read();
}
return out.toByteArray();
} catch (IOException e) {
e.printStackTrace();
//throw new RuntimeException("Couldn't load bytes from stream");
}
return null;
}
/**
* @nowebref
*/
static public byte[] loadBytes(File file) {
InputStream is = createInput(file);
return loadBytes(is);
}
/**
* @nowebref
*/
static public String[] loadStrings(File file) {
InputStream is = createInput(file);
if (is != null) return loadStrings(is);
return null;
}
/**
* ( begin auto-generated from loadStrings.xml )
*
* Reads the contents of a file or url and creates a String array of its
* individual lines. If a file is specified, it must be located in the
* sketch's "data" directory/folder.<br />
* <br />
* The filename parameter can also be a URL to a file found online. For
* security reasons, a Processing sketch found online can only download
* files from the same server from which it came. Getting around this
* restriction requires a <a
* href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</a>.
* <br />
* If the file is not available or an error occurs, <b>null</b> will be
* returned and an error message will be printed to the console. The error
* message does not halt the program, however the null value may cause a
* NullPointerException if your code does not check whether the value
* returned is null.
* <br/> <br/>
* Starting with Processing release 0134, all files loaded and saved by the
* Processing API use UTF-8 encoding. In previous releases, the default
* encoding for your platform was used, which causes problems when files
* are moved to other platforms.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Load data from a file and shove it into a String array.
* <p>
* Exceptions are handled internally, when an error, occurs, an
* exception is printed to the console and 'null' is returned,
* but the program continues running. This is a tradeoff between
* 1) showing the user that there was a problem but 2) not requiring
* that all i/o code is contained in try/catch blocks, for the sake
* of new users (or people who are just trying to get things done
* in a "scripting" fashion. If you want to handle exceptions,
* use Java methods for I/O.
*
* @webref input:files
* @param filename name of the file or url to load
* @see PApplet#loadBytes(String)
* @see PApplet#saveStrings(String, String[])
* @see PApplet#saveBytes(String, byte[])
*/
public String[] loadStrings(String filename) {
InputStream is = createInput(filename);
if (is != null) return loadStrings(is);
System.err.println("The file \"" + filename + "\" " +
"is missing or inaccessible, make sure " +
"the URL is valid or that the file has been " +
"added to your sketch and is readable.");
return null;
}
/**
* @nowebref
*/
static public String[] loadStrings(InputStream input) {
try {
BufferedReader reader =
new BufferedReader(new InputStreamReader(input, "UTF-8"));
return loadStrings(reader);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
static public String[] loadStrings(BufferedReader reader) {
try {
String lines[] = new String[100];
int lineCount = 0;
String line = null;
while ((line = reader.readLine()) != null) {
if (lineCount == lines.length) {
String temp[] = new String[lineCount << 1];
System.arraycopy(lines, 0, temp, 0, lineCount);
lines = temp;
}
lines[lineCount++] = line;
}
reader.close();
if (lineCount == lines.length) {
return lines;
}
// resize array to appropriate amount for these lines
String output[] = new String[lineCount];
System.arraycopy(lines, 0, output, 0, lineCount);
return output;
} catch (IOException e) {
e.printStackTrace();
//throw new RuntimeException("Error inside loadStrings()");
}
return null;
}
//////////////////////////////////////////////////////////////
// FILE OUTPUT
/**
* ( begin auto-generated from createOutput.xml )
*
* Similar to <b>createInput()</b>, this creates a Java <b>OutputStream</b>
* for a given filename or path. The file will be created in the sketch
* folder, or in the same folder as an exported application.
* <br /><br />
* If the path does not exist, intermediate folders will be created. If an
* exception occurs, it will be printed to the console, and <b>null</b>
* will be returned.
* <br /><br />
* This function is a convenience over the Java approach that requires you
* to 1) create a FileOutputStream object, 2) determine the exact file
* location, and 3) handle exceptions. Exceptions are handled internally by
* the function, which is more appropriate for "sketch" projects.
* <br /><br />
* If the output filename ends with <b>.gz</b>, the output will be
* automatically GZIP compressed as it is written.
*
* ( end auto-generated )
* @webref output:files
* @param filename name of the file to open
* @see PApplet#createInput(String)
* @see PApplet#selectOutput()
*/
public OutputStream createOutput(String filename) {
return createOutput(saveFile(filename));
}
/**
* @nowebref
*/
static public OutputStream createOutput(File file) {
try {
createPath(file); // make sure the path exists
FileOutputStream fos = new FileOutputStream(file);
if (file.getName().toLowerCase().endsWith(".gz")) {
return new GZIPOutputStream(fos);
}
return fos;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* ( begin auto-generated from saveStream.xml )
*
* Save the contents of a stream to a file in the sketch folder. This is
* basically <b>saveBytes(blah, loadBytes())</b>, but done more efficiently
* (and with less confusing syntax).<br />
* <br />
* When using the <b>targetFile</b> parameter, it writes to a <b>File</b>
* object for greater control over the file location. (Note that unlike
* some other functions, this will not automatically compress or uncompress
* gzip files.)
*
* ( end auto-generated )
*
* @webref output:files
* @param target name of the file to write to
* @param source location to read from (a filename, path, or URL)
* @see PApplet#createOutput(String)
*/
public boolean saveStream(String target, String source) {
return saveStream(saveFile(target), source);
}
/**
* Identical to the other saveStream(), but writes to a File
* object, for greater control over the file location.
* <p/>
* Note that unlike other api methods, this will not automatically
* compress or uncompress gzip files.
*/
public boolean saveStream(File target, String source) {
return saveStream(target, createInputRaw(source));
}
/**
* @nowebref
*/
public boolean saveStream(String target, InputStream source) {
return saveStream(saveFile(target), source);
}
/**
* @nowebref
*/
static public boolean saveStream(File target, InputStream source) {
File tempFile = null;
try {
File parentDir = target.getParentFile();
// make sure that this path actually exists before writing
createPath(target);
tempFile = File.createTempFile(target.getName(), null, parentDir);
FileOutputStream targetStream = new FileOutputStream(tempFile);
saveStream(targetStream, source);
targetStream.close();
targetStream = null;
if (target.exists()) {
if (!target.delete()) {
System.err.println("Could not replace " +
target.getAbsolutePath() + ".");
}
}
if (!tempFile.renameTo(target)) {
System.err.println("Could not rename temporary file " +
tempFile.getAbsolutePath());
return false;
}
return true;
} catch (IOException e) {
if (tempFile != null) {
tempFile.delete();
}
e.printStackTrace();
return false;
}
}
/**
* @nowebref
*/
static public void saveStream(OutputStream target,
InputStream source) throws IOException {
BufferedInputStream bis = new BufferedInputStream(source, 16384);
BufferedOutputStream bos = new BufferedOutputStream(target);
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = bis.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.flush();
}
/**
* ( begin auto-generated from saveBytes.xml )
*
* Opposite of <b>loadBytes()</b>, will write an entire array of bytes to a
* file. The data is saved in binary format. This file is saved to the
* sketch's folder, which is opened by selecting "Show sketch folder" from
* the "Sketch" menu.<br />
* <br />
* It is not possible to use saveXxxxx() functions inside a web browser
* unless the sketch is <a
* href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</A>. To
* save a file back to a server, see the <a
* href="http://wiki.processing.org/w/Saving_files_to_a_web-server">save to
* web</A> code snippet on the Processing Wiki.
*
* ( end auto-generated )
*
* @webref output:files
* @param filename name of the file to write to
* @param data array of bytes to be written
* @see PApplet#loadStrings(String)
* @see PApplet#loadBytes(String)
* @see PApplet#saveStrings(String, String[])
*/
public void saveBytes(String filename, byte[] data) {
saveBytes(saveFile(filename), data);
}
/**
* @nowebref
* Saves bytes to a specific File location specified by the user.
*/
static public void saveBytes(File file, byte[] data) {
File tempFile = null;
try {
File parentDir = file.getParentFile();
tempFile = File.createTempFile(file.getName(), null, parentDir);
OutputStream output = createOutput(tempFile);
saveBytes(output, data);
output.close();
output = null;
if (file.exists()) {
if (!file.delete()) {
System.err.println("Could not replace " + file.getAbsolutePath());
}
}
if (!tempFile.renameTo(file)) {
System.err.println("Could not rename temporary file " +
tempFile.getAbsolutePath());
}
} catch (IOException e) {
System.err.println("error saving bytes to " + file);
if (tempFile != null) {
tempFile.delete();
}
e.printStackTrace();
}
}
/**
* @nowebref
* Spews a buffer of bytes to an OutputStream.
*/
static public void saveBytes(OutputStream output, byte[] data) {
try {
output.write(data);
output.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
//
/**
* ( begin auto-generated from saveStrings.xml )
*
* Writes an array of strings to a file, one line per string. This file is
* saved to the sketch's folder, which is opened by selecting "Show sketch
* folder" from the "Sketch" menu.<br />
* <br />
* It is not possible to use saveXxxxx() functions inside a web browser
* unless the sketch is <a
* href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</A>. To
* save a file back to a server, see the <a
* href="http://wiki.processing.org/w/Saving_files_to_a_web-server">save to
* web</A> code snippet on the Processing Wiki.<br/>
* <br/ >
* Starting with Processing 1.0, all files loaded and saved by the
* Processing API use UTF-8 encoding. In previous releases, the default
* encoding for your platform was used, which causes problems when files
* are moved to other platforms.
*
* ( end auto-generated )
* @webref output:files
* @param filename filename for output
* @param data string array to be written
* @see PApplet#loadStrings(String)
* @see PApplet#loadBytes(String)
* @see PApplet#saveBytes(String, byte[])
*/
public void saveStrings(String filename, String data[]) {
saveStrings(saveFile(filename), data);
}
/**
* @nowebref
*/
static public void saveStrings(File file, String data[]) {
saveStrings(createOutput(file), data);
}
/**
* @nowebref
*/
static public void saveStrings(OutputStream output, String[] data) {
PrintWriter writer = createWriter(output);
for (int i = 0; i < data.length; i++) {
writer.println(data[i]);
}
writer.flush();
writer.close();
}
//////////////////////////////////////////////////////////////
/**
* Prepend the sketch folder path to the filename (or path) that is
* passed in. External libraries should use this function to save to
* the sketch folder.
* <p/>
* Note that when running as an applet inside a web browser,
* the sketchPath will be set to null, because security restrictions
* prevent applets from accessing that information.
* <p/>
* This will also cause an error if the sketch is not inited properly,
* meaning that init() was never called on the PApplet when hosted
* my some other main() or by other code. For proper use of init(),
* see the examples in the main description text for PApplet.
*/
public String sketchPath(String where) {
if (sketchPath == null) {
return where;
// throw new RuntimeException("The applet was not inited properly, " +
// "or security restrictions prevented " +
// "it from determining its path.");
}
// isAbsolute() could throw an access exception, but so will writing
// to the local disk using the sketch path, so this is safe here.
// for 0120, added a try/catch anyways.
try {
if (new File(where).isAbsolute()) return where;
} catch (Exception e) { }
return sketchPath + File.separator + where;
}
public File sketchFile(String where) {
return new File(sketchPath(where));
}
/**
* Returns a path inside the applet folder to save to. Like sketchPath(),
* but creates any in-between folders so that things save properly.
* <p/>
* All saveXxxx() functions use the path to the sketch folder, rather than
* its data folder. Once exported, the data folder will be found inside the
* jar file of the exported application or applet. In this case, it's not
* possible to save data into the jar file, because it will often be running
* from a server, or marked in-use if running from a local file system.
* With this in mind, saving to the data path doesn't make sense anyway.
* If you know you're running locally, and want to save to the data folder,
* use <TT>saveXxxx("data/blah.dat")</TT>.
*/
public String savePath(String where) {
if (where == null) return null;
String filename = sketchPath(where);
createPath(filename);
return filename;
}
/**
* Identical to savePath(), but returns a File object.
*/
public File saveFile(String where) {
return new File(savePath(where));
}
/**
* Return a full path to an item in the data folder.
* <p>
* This is only available with applications, not applets or Android.
* On Windows and Linux, this is simply the data folder, which is located
* in the same directory as the EXE file and lib folders. On Mac OS X, this
* is a path to the data folder buried inside Contents/Resources/Java.
* For the latter point, that also means that the data folder should not be
* considered writable. Use sketchPath() for now, or inputPath() and
* outputPath() once they're available in the 2.0 release.
* <p>
* dataPath() is not supported with applets because applets have their data
* folder wrapped into the JAR file. To read data from the data folder that
* works with an applet, you should use other methods such as createInput(),
* createReader(), or loadStrings().
*/
public String dataPath(String where) {
return dataFile(where).getAbsolutePath();
}
/**
* Return a full path to an item in the data folder as a File object.
* See the dataPath() method for more information.
*/
public File dataFile(String where) {
// isAbsolute() could throw an access exception, but so will writing
// to the local disk using the sketch path, so this is safe here.
File why = new File(where);
if (why.isAbsolute()) return why;
String jarPath =
getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
if (jarPath.contains("Contents/Resources/Java/")) {
// The path will be URL encoded (%20 for spaces) coming from above
// http://code.google.com/p/processing/issues/detail?id=1073
File containingFolder = new File(urlDecode(jarPath)).getParentFile();
File dataFolder = new File(containingFolder, "data");
return new File(dataFolder, where);
}
// Windows, Linux, or when not using a Mac OS X .app file
return new File(sketchPath + File.separator + "data" + File.separator + where);
}
/**
* On Windows and Linux, this is simply the data folder. On Mac OS X, this is
* the path to the data folder buried inside Contents/Resources/Java
*/
// public File inputFile(String where) {
// }
// public String inputPath(String where) {
// }
/**
* Takes a path and creates any in-between folders if they don't
* already exist. Useful when trying to save to a subfolder that
* may not actually exist.
*/
static public void createPath(String path) {
createPath(new File(path));
}
static public void createPath(File file) {
try {
String parent = file.getParent();
if (parent != null) {
File unit = new File(parent);
if (!unit.exists()) unit.mkdirs();
}
} catch (SecurityException se) {
System.err.println("You don't have permissions to create " +
file.getAbsolutePath());
}
}
static public String getExtension(String filename) {
String extension;
String lower = filename.toLowerCase();
int dot = filename.lastIndexOf('.');
if (dot == -1) {
extension = "unknown"; // no extension found
}
extension = lower.substring(dot + 1);
// check for, and strip any parameters on the url, i.e.
// filename.jpg?blah=blah&something=that
int question = extension.indexOf('?');
if (question != -1) {
extension = extension.substring(0, question);
}
return extension;
}
//////////////////////////////////////////////////////////////
// URL ENCODING
static public String urlEncode(String str) {
try {
return URLEncoder.encode(str, "UTF-8");
} catch (UnsupportedEncodingException e) { // oh c'mon
return null;
}
}
static public String urlDecode(String str) {
try {
return URLDecoder.decode(str, "UTF-8");
} catch (UnsupportedEncodingException e) { // safe per the JDK source
return null;
}
}
//////////////////////////////////////////////////////////////
// SORT
/**
* ( begin auto-generated from sort.xml )
*
* Sorts an array of numbers from smallest to largest and puts an array of
* words in alphabetical order. The original array is not modified, a
* re-ordered array is returned. The <b>count</b> parameter states the
* number of elements to sort. For example if there are 12 elements in an
* array and if count is the value 5, only the first five elements on the
* array will be sorted. <!--As of release 0126, the alphabetical ordering
* is case insensitive.-->
*
* ( end auto-generated )
* @webref data:array_functions
* @param list array to sort
* @see PApplet#reverse(boolean[])
*/
static public byte[] sort(byte list[]) {
return sort(list, list.length);
}
/**
* @param count number of elements to sort, starting from 0
*/
static public byte[] sort(byte[] list, int count) {
byte[] outgoing = new byte[list.length];
System.arraycopy(list, 0, outgoing, 0, list.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public char[] sort(char list[]) {
return sort(list, list.length);
}
static public char[] sort(char[] list, int count) {
char[] outgoing = new char[list.length];
System.arraycopy(list, 0, outgoing, 0, list.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public int[] sort(int list[]) {
return sort(list, list.length);
}
static public int[] sort(int[] list, int count) {
int[] outgoing = new int[list.length];
System.arraycopy(list, 0, outgoing, 0, list.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public float[] sort(float list[]) {
return sort(list, list.length);
}
static public float[] sort(float[] list, int count) {
float[] outgoing = new float[list.length];
System.arraycopy(list, 0, outgoing, 0, list.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public String[] sort(String list[]) {
return sort(list, list.length);
}
static public String[] sort(String[] list, int count) {
String[] outgoing = new String[list.length];
System.arraycopy(list, 0, outgoing, 0, list.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
//////////////////////////////////////////////////////////////
// ARRAY UTILITIES
/**
* ( begin auto-generated from arrayCopy.xml )
*
* Copies an array (or part of an array) to another array. The <b>src</b>
* array is copied to the <b>dst</b> array, beginning at the position
* specified by <b>srcPos</b> and into the position specified by
* <b>dstPos</b>. The number of elements to copy is determined by
* <b>length</b>. The simplified version with two arguments copies an
* entire array to another of the same size. It is equivalent to
* "arrayCopy(src, 0, dst, 0, src.length)". This function is far more
* efficient for copying array data than iterating through a <b>for</b> and
* copying each element.
*
* ( end auto-generated )
* @webref data:array_functions
* @param src the source array
* @param srcPosition starting position in the source array
* @param dst the destination array of the same data type as the source array
* @param dstPosition starting position in the destination array
* @param length number of array elements to be copied
* @see PApplet#concat(boolean[], boolean[])
*/
static public void arrayCopy(Object src, int srcPosition,
Object dst, int dstPosition,
int length) {
System.arraycopy(src, srcPosition, dst, dstPosition, length);
}
/**
* Convenience method for arraycopy().
* Identical to <CODE>arraycopy(src, 0, dst, 0, length);</CODE>
*/
static public void arrayCopy(Object src, Object dst, int length) {
System.arraycopy(src, 0, dst, 0, length);
}
/**
* Shortcut to copy the entire contents of
* the source into the destination array.
* Identical to <CODE>arraycopy(src, 0, dst, 0, src.length);</CODE>
*/
static public void arrayCopy(Object src, Object dst) {
System.arraycopy(src, 0, dst, 0, Array.getLength(src));
}
//
/**
* @deprecated Use arrayCopy() instead.
*/
static public void arraycopy(Object src, int srcPosition,
Object dst, int dstPosition,
int length) {
System.arraycopy(src, srcPosition, dst, dstPosition, length);
}
/**
* @deprecated Use arrayCopy() instead.
*/
static public void arraycopy(Object src, Object dst, int length) {
System.arraycopy(src, 0, dst, 0, length);
}
/**
* @deprecated Use arrayCopy() instead.
*/
static public void arraycopy(Object src, Object dst) {
System.arraycopy(src, 0, dst, 0, Array.getLength(src));
}
/**
* ( begin auto-generated from expand.xml )
*
* Increases the size of an array. By default, this function doubles the
* size of the array, but the optional <b>newSize</b> parameter provides
* precise control over the increase in size.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) expand(originalArray)</em>.
*
* ( end auto-generated )
*
* @webref data:array_functions
* @param list the array to expand
* @see PApplet#shorten(boolean[])
*/
static public boolean[] expand(boolean list[]) {
return expand(list, list.length << 1);
}
/**
* @param newSize new size for the array
*/
static public boolean[] expand(boolean list[], int newSize) {
boolean temp[] = new boolean[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public byte[] expand(byte list[]) {
return expand(list, list.length << 1);
}
static public byte[] expand(byte list[], int newSize) {
byte temp[] = new byte[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public char[] expand(char list[]) {
return expand(list, list.length << 1);
}
static public char[] expand(char list[], int newSize) {
char temp[] = new char[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public int[] expand(int list[]) {
return expand(list, list.length << 1);
}
static public int[] expand(int list[], int newSize) {
int temp[] = new int[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public long[] expand(long list[]) {
return expand(list, list.length << 1);
}
static public long[] expand(long list[], int newSize) {
long temp[] = new long[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public float[] expand(float list[]) {
return expand(list, list.length << 1);
}
static public float[] expand(float list[], int newSize) {
float temp[] = new float[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public double[] expand(double list[]) {
return expand(list, list.length << 1);
}
static public double[] expand(double list[], int newSize) {
double temp[] = new double[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public String[] expand(String list[]) {
return expand(list, list.length << 1);
}
static public String[] expand(String list[], int newSize) {
String temp[] = new String[newSize];
// in case the new size is smaller than list.length
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
/**
* @nowebref
*/
static public Object expand(Object array) {
return expand(array, Array.getLength(array) << 1);
}
static public Object expand(Object list, int newSize) {
Class<?> type = list.getClass().getComponentType();
Object temp = Array.newInstance(type, newSize);
System.arraycopy(list, 0, temp, 0,
Math.min(Array.getLength(list), newSize));
return temp;
}
// contract() has been removed in revision 0124, use subset() instead.
// (expand() is also functionally equivalent)
/**
* ( begin auto-generated from append.xml )
*
* Expands an array by one element and adds data to the new position. The
* datatype of the <b>element</b> parameter must be the same as the
* datatype of the array.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) append(originalArray, element)</em>.
*
* ( end auto-generated )
*
* @webref data:array_functions
* @param array array to append
* @param value new data for the array
* @see PApplet#shorten(boolean[])
* @see PApplet#expand(boolean[])
*/
static public byte[] append(byte array[], byte value) {
array = expand(array, array.length + 1);
array[array.length-1] = value;
return array;
}
static public char[] append(char array[], char value) {
array = expand(array, array.length + 1);
array[array.length-1] = value;
return array;
}
static public int[] append(int array[], int value) {
array = expand(array, array.length + 1);
array[array.length-1] = value;
return array;
}
static public float[] append(float array[], float value) {
array = expand(array, array.length + 1);
array[array.length-1] = value;
return array;
}
static public String[] append(String array[], String value) {
array = expand(array, array.length + 1);
array[array.length-1] = value;
return array;
}
static public Object append(Object array, Object value) {
int length = Array.getLength(array);
array = expand(array, length + 1);
Array.set(array, length, value);
return array;
}
/**
* ( begin auto-generated from shorten.xml )
*
* Decreases an array by one element and returns the shortened array.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) shorten(originalArray)</em>.
*
* ( end auto-generated )
*
* @webref data:array_functions
* @param list array to shorten
* @see PApplet#append(byte[], byte)
* @see PApplet#expand(boolean[])
*/
static public boolean[] shorten(boolean list[]) {
return subset(list, 0, list.length-1);
}
static public byte[] shorten(byte list[]) {
return subset(list, 0, list.length-1);
}
static public char[] shorten(char list[]) {
return subset(list, 0, list.length-1);
}
static public int[] shorten(int list[]) {
return subset(list, 0, list.length-1);
}
static public float[] shorten(float list[]) {
return subset(list, 0, list.length-1);
}
static public String[] shorten(String list[]) {
return subset(list, 0, list.length-1);
}
static public Object shorten(Object list) {
int length = Array.getLength(list);
return subset(list, 0, length - 1);
}
/**
* ( begin auto-generated from splice.xml )
*
* Inserts a value or array of values into an existing array. The first two
* parameters must be of the same datatype. The <b>array</b> parameter
* defines the array which will be modified and the second parameter
* defines the data which will be inserted.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) splice(array1, array2, index)</em>.
*
* ( end auto-generated )
* @webref data:array_functions
* @param list array to splice into
* @param value value to be spliced in
* @param index position in the array from which to insert data
* @see PApplet#concat(boolean[], boolean[])
* @see PApplet#subset(boolean[], int, int)
*/
static final public boolean[] splice(boolean list[],
boolean value, int index) {
boolean outgoing[] = new boolean[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public boolean[] splice(boolean list[],
boolean value[], int index) {
boolean outgoing[] = new boolean[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public byte[] splice(byte list[],
byte value, int index) {
byte outgoing[] = new byte[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public byte[] splice(byte list[],
byte value[], int index) {
byte outgoing[] = new byte[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public char[] splice(char list[],
char value, int index) {
char outgoing[] = new char[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public char[] splice(char list[],
char value[], int index) {
char outgoing[] = new char[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public int[] splice(int list[],
int value, int index) {
int outgoing[] = new int[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public int[] splice(int list[],
int value[], int index) {
int outgoing[] = new int[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public float[] splice(float list[],
float value, int index) {
float outgoing[] = new float[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public float[] splice(float list[],
float value[], int index) {
float outgoing[] = new float[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public String[] splice(String list[],
String value, int index) {
String outgoing[] = new String[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public String[] splice(String list[],
String value[], int index) {
String outgoing[] = new String[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public Object splice(Object list, Object value, int index) {
Object[] outgoing = null;
int length = Array.getLength(list);
// check whether item being spliced in is an array
if (value.getClass().getName().charAt(0) == '[') {
int vlength = Array.getLength(value);
outgoing = new Object[length + vlength];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, vlength);
System.arraycopy(list, index, outgoing, index + vlength, length - index);
} else {
outgoing = new Object[length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
Array.set(outgoing, index, value);
System.arraycopy(list, index, outgoing, index + 1, length - index);
}
return outgoing;
}
static public boolean[] subset(boolean list[], int start) {
return subset(list, start, list.length - start);
}
/**
* ( begin auto-generated from subset.xml )
*
* Extracts an array of elements from an existing array. The <b>array</b>
* parameter defines the array from which the elements will be copied and
* the <b>offset</b> and <b>length</b> parameters determine which elements
* to extract. If no <b>length</b> is given, elements will be extracted
* from the <b>offset</b> to the end of the array. When specifying the
* <b>offset</b> remember the first array element is 0. This function does
* not change the source array.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) subset(originalArray, 0, 4)</em>.
*
* ( end auto-generated )
* @webref data:array_functions
* @param list array to extract from
* @param start position to begin
* @param count number of values to extract
* @see PApplet#splice(boolean[], boolean, int)
*/
static public boolean[] subset(boolean list[], int start, int count) {
boolean output[] = new boolean[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public byte[] subset(byte list[], int start) {
return subset(list, start, list.length - start);
}
static public byte[] subset(byte list[], int start, int count) {
byte output[] = new byte[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public char[] subset(char list[], int start) {
return subset(list, start, list.length - start);
}
static public char[] subset(char list[], int start, int count) {
char output[] = new char[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public int[] subset(int list[], int start) {
return subset(list, start, list.length - start);
}
static public int[] subset(int list[], int start, int count) {
int output[] = new int[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public float[] subset(float list[], int start) {
return subset(list, start, list.length - start);
}
static public float[] subset(float list[], int start, int count) {
float output[] = new float[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public String[] subset(String list[], int start) {
return subset(list, start, list.length - start);
}
static public String[] subset(String list[], int start, int count) {
String output[] = new String[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public Object subset(Object list, int start) {
int length = Array.getLength(list);
return subset(list, start, length - start);
}
static public Object subset(Object list, int start, int count) {
Class<?> type = list.getClass().getComponentType();
Object outgoing = Array.newInstance(type, count);
System.arraycopy(list, start, outgoing, 0, count);
return outgoing;
}
/**
* ( begin auto-generated from concat.xml )
*
* Concatenates two arrays. For example, concatenating the array { 1, 2, 3
* } and the array { 4, 5, 6 } yields { 1, 2, 3, 4, 5, 6 }. Both parameters
* must be arrays of the same datatype.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) concat(array1, array2)</em>.
*
* ( end auto-generated )
* @webref data:array_functions
* @param a first array to concatenate
* @param b second array to concatenate
* @see PApplet#splice(boolean[], boolean, int)
* @see PApplet#arrayCopy(Object, int, Object, int, int)
*/
static public boolean[] concat(boolean a[], boolean b[]) {
boolean c[] = new boolean[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public byte[] concat(byte a[], byte b[]) {
byte c[] = new byte[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public char[] concat(char a[], char b[]) {
char c[] = new char[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public int[] concat(int a[], int b[]) {
int c[] = new int[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public float[] concat(float a[], float b[]) {
float c[] = new float[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public String[] concat(String a[], String b[]) {
String c[] = new String[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public Object concat(Object a, Object b) {
Class<?> type = a.getClass().getComponentType();
int alength = Array.getLength(a);
int blength = Array.getLength(b);
Object outgoing = Array.newInstance(type, alength + blength);
System.arraycopy(a, 0, outgoing, 0, alength);
System.arraycopy(b, 0, outgoing, alength, blength);
return outgoing;
}
//
/**
* ( begin auto-generated from reverse.xml )
*
* Reverses the order of an array.
*
* ( end auto-generated )
* @webref data:array_functions
* @param list booleans[], bytes[], chars[], ints[], floats[], or Strings[]
* @see PApplet#sort(String[], int)
*/
static public boolean[] reverse(boolean list[]) {
boolean outgoing[] = new boolean[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public byte[] reverse(byte list[]) {
byte outgoing[] = new byte[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public char[] reverse(char list[]) {
char outgoing[] = new char[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public int[] reverse(int list[]) {
int outgoing[] = new int[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public float[] reverse(float list[]) {
float outgoing[] = new float[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public String[] reverse(String list[]) {
String outgoing[] = new String[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public Object reverse(Object list) {
Class<?> type = list.getClass().getComponentType();
int length = Array.getLength(list);
Object outgoing = Array.newInstance(type, length);
for (int i = 0; i < length; i++) {
Array.set(outgoing, i, Array.get(list, (length - 1) - i));
}
return outgoing;
}
//////////////////////////////////////////////////////////////
// STRINGS
/**
* ( begin auto-generated from trim.xml )
*
* Removes whitespace characters from the beginning and end of a String. In
* addition to standard whitespace characters such as space, carriage
* return, and tab, this function also removes the Unicode "nbsp" character.
*
* ( end auto-generated )
* @webref data:string_functions
* @param str any string
* @see PApplet#split(String, String)
* @see PApplet#join(String[], char)
*/
static public String trim(String str) {
return str.replace('\u00A0', ' ').trim();
}
/**
* @param array a String array
*/
static public String[] trim(String[] array) {
String[] outgoing = new String[array.length];
for (int i = 0; i < array.length; i++) {
if (array[i] != null) {
outgoing[i] = array[i].replace('\u00A0', ' ').trim();
}
}
return outgoing;
}
/**
* ( begin auto-generated from join.xml )
*
* Combines an array of Strings into one String, each separated by the
* character(s) used for the <b>separator</b> parameter. To join arrays of
* ints or floats, it's necessary to first convert them to strings using
* <b>nf()</b> or <b>nfs()</b>.
*
* ( end auto-generated )
* @webref data:string_functions
* @param list array of Strings
* @param separator char or String to be placed between each item
* @see PApplet#split(String, String)
* @see PApplet#trim(String)
* @see PApplet#nf(float, int, int)
* @see PApplet#nfs(float, int, int)
*/
static public String join(String[] list, char separator) {
return join(list, String.valueOf(separator));
}
static public String join(String[] list, String separator) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < list.length; i++) {
if (i != 0) buffer.append(separator);
buffer.append(list[i]);
}
return buffer.toString();
}
static public String[] splitTokens(String value) {
return splitTokens(value, WHITESPACE);
}
/**
* ( begin auto-generated from splitTokens.xml )
*
* The splitTokens() function splits a String at one or many character
* "tokens." The <b>tokens</b> parameter specifies the character or
* characters to be used as a boundary.
* <br/> <br/>
* If no <b>tokens</b> character is specified, any whitespace character is
* used to split. Whitespace characters include tab (\\t), line feed (\\n),
* carriage return (\\r), form feed (\\f), and space. To convert a String
* to an array of integers or floats, use the datatype conversion functions
* <b>int()</b> and <b>float()</b> to convert the array of Strings.
*
* ( end auto-generated )
* @webref data:string_functions
* @param value the String to be split
* @param delim list of individual characters that will be used as separators
* @see PApplet#split(String, String)
* @see PApplet#join(String[], String)
* @see PApplet#trim(String)
*/
static public String[] splitTokens(String value, String delim) {
StringTokenizer toker = new StringTokenizer(value, delim);
String pieces[] = new String[toker.countTokens()];
int index = 0;
while (toker.hasMoreTokens()) {
pieces[index++] = toker.nextToken();
}
return pieces;
}
/**
* ( begin auto-generated from split.xml )
*
* The split() function breaks a string into pieces using a character or
* string as the divider. The <b>delim</b> parameter specifies the
* character or characters that mark the boundaries between each piece. A
* String[] array is returned that contains each of the pieces.
* <br/> <br/>
* If the result is a set of numbers, you can convert the String[] array to
* to a float[] or int[] array using the datatype conversion functions
* <b>int()</b> and <b>float()</b> (see example above).
* <br/> <br/>
* The <b>splitTokens()</b> function works in a similar fashion, except
* that it splits using a range of characters instead of a specific
* character or sequence.
* <!-- /><br />
* This function uses regular expressions to determine how the <b>delim</b>
* parameter divides the <b>str</b> parameter. Therefore, if you use
* characters such parentheses and brackets that are used with regular
* expressions as a part of the <b>delim</b> parameter, you'll need to put
* two blackslashes (\\\\) in front of the character (see example above).
* You can read more about <a
* href="http://en.wikipedia.org/wiki/Regular_expression">regular
* expressions</a> and <a
* href="http://en.wikipedia.org/wiki/Escape_character">escape
* characters</a> on Wikipedia.
* -->
*
* ( end auto-generated )
* @webref data:string_functions
* @usage web_application
* @param value the String to be split
* @param delim the character or String used to separate the data
*/
static public String[] split(String value, char delim) {
// do this so that the exception occurs inside the user's
// program, rather than appearing to be a bug inside split()
if (value == null) return null;
//return split(what, String.valueOf(delim)); // huh
char chars[] = value.toCharArray();
int splitCount = 0; //1;
for (int i = 0; i < chars.length; i++) {
if (chars[i] == delim) splitCount++;
}
// make sure that there is something in the input string
//if (chars.length > 0) {
// if the last char is a delimeter, get rid of it..
//if (chars[chars.length-1] == delim) splitCount--;
// on second thought, i don't agree with this, will disable
//}
if (splitCount == 0) {
String splits[] = new String[1];
splits[0] = new String(value);
return splits;
}
//int pieceCount = splitCount + 1;
String splits[] = new String[splitCount + 1];
int splitIndex = 0;
int startIndex = 0;
for (int i = 0; i < chars.length; i++) {
if (chars[i] == delim) {
splits[splitIndex++] =
new String(chars, startIndex, i-startIndex);
startIndex = i + 1;
}
}
//if (startIndex != chars.length) {
splits[splitIndex] =
new String(chars, startIndex, chars.length-startIndex);
//}
return splits;
}
static public String[] split(String value, String delim) {
ArrayList<String> items = new ArrayList<String>();
int index;
int offset = 0;
while ((index = value.indexOf(delim, offset)) != -1) {
items.add(value.substring(offset, index));
offset = index + delim.length();
}
items.add(value.substring(offset));
String[] outgoing = new String[items.size()];
items.toArray(outgoing);
return outgoing;
}
static protected HashMap<String, Pattern> matchPatterns;
static Pattern matchPattern(String regexp) {
Pattern p = null;
if (matchPatterns == null) {
matchPatterns = new HashMap<String, Pattern>();
} else {
p = matchPatterns.get(regexp);
}
if (p == null) {
if (matchPatterns.size() == 10) {
// Just clear out the match patterns here if more than 10 are being
// used. It's not terribly efficient, but changes that you have >10
// different match patterns are very slim, unless you're doing
// something really tricky (like custom match() methods), in which
// case match() won't be efficient anyway. (And you should just be
// using your own Java code.) The alternative is using a queue here,
// but that's a silly amount of work for negligible benefit.
matchPatterns.clear();
}
p = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL);
matchPatterns.put(regexp, p);
}
return p;
}
/**
* ( begin auto-generated from match.xml )
*
* The match() function is used to apply a regular expression to a piece of
* text, and return matching groups (elements found inside parentheses) as
* a String array. No match will return null. If no groups are specified in
* the regexp, but the sequence matches, an array of length one (with the
* matched text as the first element of the array) will be returned.<br />
* <br />
* To use the function, first check to see if the result is null. If the
* result is null, then the sequence did not match. If the sequence did
* match, an array is returned.
* If there are groups (specified by sets of parentheses) in the regexp,
* then the contents of each will be returned in the array.
* Element [0] of a regexp match returns the entire matching string, and
* the match groups start at element [1] (the first group is [1], the
* second [2], and so on).<br />
* <br />
* The syntax can be found in the reference for Java's <a
* href="http://download.oracle.com/javase/6/docs/api/">Pattern</a> class.
* For regular expression syntax, read the <a
* href="http://download.oracle.com/javase/tutorial/essential/regex/">Java
* Tutorial</a> on the topic.
*
* ( end auto-generated )
* @webref data:string_functions
* @param str the String to be searched
* @param regexp the regexp to be used for matching
* @see PApplet#matchAll(String, String)
* @see PApplet#split(String, String)
* @see PApplet#splitTokens(String, String)
* @see PApplet#join(String[], String)
* @see PApplet#trim(String)
*/
static public String[] match(String str, String regexp) {
Pattern p = matchPattern(regexp);
Matcher m = p.matcher(str);
if (m.find()) {
int count = m.groupCount() + 1;
String[] groups = new String[count];
for (int i = 0; i < count; i++) {
groups[i] = m.group(i);
}
return groups;
}
return null;
}
/**
* ( begin auto-generated from matchAll.xml )
*
* This function is used to apply a regular expression to a piece of text,
* and return a list of matching groups (elements found inside parentheses)
* as a two-dimensional String array. No matches will return null. If no
* groups are specified in the regexp, but the sequence matches, a two
* dimensional array is still returned, but the second dimension is only of
* length one.<br />
* <br />
* To use the function, first check to see if the result is null. If the
* result is null, then the sequence did not match at all. If the sequence
* did match, a 2D array is returned. If there are groups (specified by
* sets of parentheses) in the regexp, then the contents of each will be
* returned in the array.
* Assuming, a loop with counter variable i, element [i][0] of a regexp
* match returns the entire matching string, and the match groups start at
* element [i][1] (the first group is [i][1], the second [i][2], and so
* on).<br />
* <br />
* The syntax can be found in the reference for Java's <a
* href="http://download.oracle.com/javase/6/docs/api/">Pattern</a> class.
* For regular expression syntax, read the <a
* href="http://download.oracle.com/javase/tutorial/essential/regex/">Java
* Tutorial</a> on the topic.
*
* ( end auto-generated )
* @webref data:string_functions
* @param str the String to be searched
* @param regexp the regexp to be used for matching
* @see PApplet#match(String, String)
* @see PApplet#split(String, String)
* @see PApplet#splitTokens(String, String)
* @see PApplet#join(String[], String)
* @see PApplet#trim(String)
*/
static public String[][] matchAll(String str, String regexp) {
Pattern p = matchPattern(regexp);
Matcher m = p.matcher(str);
ArrayList<String[]> results = new ArrayList<String[]>();
int count = m.groupCount() + 1;
while (m.find()) {
String[] groups = new String[count];
for (int i = 0; i < count; i++) {
groups[i] = m.group(i);
}
results.add(groups);
}
if (results.isEmpty()) {
return null;
}
String[][] matches = new String[results.size()][count];
for (int i = 0; i < matches.length; i++) {
matches[i] = results.get(i);
}
return matches;
}
//////////////////////////////////////////////////////////////
// CASTING FUNCTIONS, INSERTED BY PREPROC
/**
* Convert a char to a boolean. 'T', 't', and '1' will become the
* boolean value true, while 'F', 'f', or '0' will become false.
*/
/*
static final public boolean parseBoolean(char what) {
return ((what == 't') || (what == 'T') || (what == '1'));
}
*/
/**
* <p>Convert an integer to a boolean. Because of how Java handles upgrading
* numbers, this will also cover byte and char (as they will upgrade to
* an int without any sort of explicit cast).</p>
* <p>The preprocessor will convert boolean(what) to parseBoolean(what).</p>
* @return false if 0, true if any other number
*/
static final public boolean parseBoolean(int what) {
return (what != 0);
}
/*
// removed because this makes no useful sense
static final public boolean parseBoolean(float what) {
return (what != 0);
}
*/
/**
* Convert the string "true" or "false" to a boolean.
* @return true if 'what' is "true" or "TRUE", false otherwise
*/
static final public boolean parseBoolean(String what) {
return new Boolean(what).booleanValue();
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
// removed, no need to introduce strange syntax from other languages
static final public boolean[] parseBoolean(char what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] =
((what[i] == 't') || (what[i] == 'T') || (what[i] == '1'));
}
return outgoing;
}
*/
/**
* Convert a byte array to a boolean array. Each element will be
* evaluated identical to the integer case, where a byte equal
* to zero will return false, and any other value will return true.
* @return array of boolean elements
*/
/*
static final public boolean[] parseBoolean(byte what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (what[i] != 0);
}
return outgoing;
}
*/
/**
* Convert an int array to a boolean array. An int equal
* to zero will return false, and any other value will return true.
* @return array of boolean elements
*/
static final public boolean[] parseBoolean(int what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (what[i] != 0);
}
return outgoing;
}
/*
// removed, not necessary... if necessary, convert to int array first
static final public boolean[] parseBoolean(float what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (what[i] != 0);
}
return outgoing;
}
*/
static final public boolean[] parseBoolean(String what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = new Boolean(what[i]).booleanValue();
}
return outgoing;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public byte parseByte(boolean what) {
return what ? (byte)1 : 0;
}
static final public byte parseByte(char what) {
return (byte) what;
}
static final public byte parseByte(int what) {
return (byte) what;
}
static final public byte parseByte(float what) {
return (byte) what;
}
/*
// nixed, no precedent
static final public byte[] parseByte(String what) { // note: array[]
return what.getBytes();
}
*/
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public byte[] parseByte(boolean what[]) {
byte outgoing[] = new byte[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = what[i] ? (byte)1 : 0;
}
return outgoing;
}
static final public byte[] parseByte(char what[]) {
byte outgoing[] = new byte[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (byte) what[i];
}
return outgoing;
}
static final public byte[] parseByte(int what[]) {
byte outgoing[] = new byte[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (byte) what[i];
}
return outgoing;
}
static final public byte[] parseByte(float what[]) {
byte outgoing[] = new byte[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (byte) what[i];
}
return outgoing;
}
/*
static final public byte[][] parseByte(String what[]) { // note: array[][]
byte outgoing[][] = new byte[what.length][];
for (int i = 0; i < what.length; i++) {
outgoing[i] = what[i].getBytes();
}
return outgoing;
}
*/
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
static final public char parseChar(boolean what) { // 0/1 or T/F ?
return what ? 't' : 'f';
}
*/
static final public char parseChar(byte what) {
return (char) (what & 0xff);
}
static final public char parseChar(int what) {
return (char) what;
}
/*
static final public char parseChar(float what) { // nonsensical
return (char) what;
}
static final public char[] parseChar(String what) { // note: array[]
return what.toCharArray();
}
*/
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
static final public char[] parseChar(boolean what[]) { // 0/1 or T/F ?
char outgoing[] = new char[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = what[i] ? 't' : 'f';
}
return outgoing;
}
*/
static final public char[] parseChar(byte what[]) {
char outgoing[] = new char[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (char) (what[i] & 0xff);
}
return outgoing;
}
static final public char[] parseChar(int what[]) {
char outgoing[] = new char[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (char) what[i];
}
return outgoing;
}
/*
static final public char[] parseChar(float what[]) { // nonsensical
char outgoing[] = new char[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (char) what[i];
}
return outgoing;
}
static final public char[][] parseChar(String what[]) { // note: array[][]
char outgoing[][] = new char[what.length][];
for (int i = 0; i < what.length; i++) {
outgoing[i] = what[i].toCharArray();
}
return outgoing;
}
*/
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public int parseInt(boolean what) {
return what ? 1 : 0;
}
/**
* Note that parseInt() will un-sign a signed byte value.
*/
static final public int parseInt(byte what) {
return what & 0xff;
}
/**
* Note that parseInt('5') is unlike String in the sense that it
* won't return 5, but the ascii value. This is because ((int) someChar)
* returns the ascii value, and parseInt() is just longhand for the cast.
*/
static final public int parseInt(char what) {
return what;
}
/**
* Same as floor(), or an (int) cast.
*/
static final public int parseInt(float what) {
return (int) what;
}
/**
* Parse a String into an int value. Returns 0 if the value is bad.
*/
static final public int parseInt(String what) {
return parseInt(what, 0);
}
/**
* Parse a String to an int, and provide an alternate value that
* should be used when the number is invalid.
*/
static final public int parseInt(String what, int otherwise) {
try {
int offset = what.indexOf('.');
if (offset == -1) {
return Integer.parseInt(what);
} else {
return Integer.parseInt(what.substring(0, offset));
}
} catch (NumberFormatException e) { }
return otherwise;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public int[] parseInt(boolean what[]) {
int list[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
list[i] = what[i] ? 1 : 0;
}
return list;
}
static final public int[] parseInt(byte what[]) { // note this unsigns
int list[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
list[i] = (what[i] & 0xff);
}
return list;
}
static final public int[] parseInt(char what[]) {
int list[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
list[i] = what[i];
}
return list;
}
static public int[] parseInt(float what[]) {
int inties[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
inties[i] = (int)what[i];
}
return inties;
}
/**
* Make an array of int elements from an array of String objects.
* If the String can't be parsed as a number, it will be set to zero.
*
* String s[] = { "1", "300", "44" };
* int numbers[] = parseInt(s);
*
* numbers will contain { 1, 300, 44 }
*/
static public int[] parseInt(String what[]) {
return parseInt(what, 0);
}
/**
* Make an array of int elements from an array of String objects.
* If the String can't be parsed as a number, its entry in the
* array will be set to the value of the "missing" parameter.
*
* String s[] = { "1", "300", "apple", "44" };
* int numbers[] = parseInt(s, 9999);
*
* numbers will contain { 1, 300, 9999, 44 }
*/
static public int[] parseInt(String what[], int missing) {
int output[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
try {
output[i] = Integer.parseInt(what[i]);
} catch (NumberFormatException e) {
output[i] = missing;
}
}
return output;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
static final public float parseFloat(boolean what) {
return what ? 1 : 0;
}
*/
/**
* Convert an int to a float value. Also handles bytes because of
* Java's rules for upgrading values.
*/
static final public float parseFloat(int what) { // also handles byte
return what;
}
static final public float parseFloat(String what) {
return parseFloat(what, Float.NaN);
}
static final public float parseFloat(String what, float otherwise) {
try {
return new Float(what).floatValue();
} catch (NumberFormatException e) { }
return otherwise;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
static final public float[] parseFloat(boolean what[]) {
float floaties[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
floaties[i] = what[i] ? 1 : 0;
}
return floaties;
}
static final public float[] parseFloat(char what[]) {
float floaties[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
floaties[i] = (char) what[i];
}
return floaties;
}
*/
static final public float[] parseByte(byte what[]) {
float floaties[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
floaties[i] = what[i];
}
return floaties;
}
static final public float[] parseFloat(int what[]) {
float floaties[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
floaties[i] = what[i];
}
return floaties;
}
static final public float[] parseFloat(String what[]) {
return parseFloat(what, Float.NaN);
}
static final public float[] parseFloat(String what[], float missing) {
float output[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
try {
output[i] = new Float(what[i]).floatValue();
} catch (NumberFormatException e) {
output[i] = missing;
}
}
return output;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public String str(boolean x) {
return String.valueOf(x);
}
static final public String str(byte x) {
return String.valueOf(x);
}
static final public String str(char x) {
return String.valueOf(x);
}
static final public String str(int x) {
return String.valueOf(x);
}
static final public String str(float x) {
return String.valueOf(x);
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public String[] str(boolean x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
static final public String[] str(byte x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
static final public String[] str(char x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
static final public String[] str(int x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
static final public String[] str(float x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
//////////////////////////////////////////////////////////////
// INT NUMBER FORMATTING
/**
* Integer number formatter.
*/
static private NumberFormat int_nf;
static private int int_nf_digits;
static private boolean int_nf_commas;
static public String[] nf(int num[], int digits) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nf(num[i], digits);
}
return formatted;
}
/**
* ( begin auto-generated from nf.xml )
*
* Utility function for formatting numbers into strings. There are two
* versions, one for formatting floats and one for formatting ints. The
* values for the <b>digits</b>, <b>left</b>, and <b>right</b> parameters
* should always be positive integers.<br /><br />As shown in the above
* example, <b>nf()</b> is used to add zeros to the left and/or right of a
* number. This is typically for aligning a list of numbers. To
* <em>remove</em> digits from a floating-point number, use the
* <b>int()</b>, <b>ceil()</b>, <b>floor()</b>, or <b>round()</b>
* functions.
*
* ( end auto-generated )
* @webref data:string_functions
* @param num the number(s) to format
* @param digits number of digits to pad with zero
* @see PApplet#nfs(float, int, int)
* @see PApplet#nfp(float, int, int)
* @see PApplet#nfc(float, int)
* @see PApplet#int(float)
*/
static public String nf(int num, int digits) {
if ((int_nf != null) &&
(int_nf_digits == digits) &&
!int_nf_commas) {
return int_nf.format(num);
}
int_nf = NumberFormat.getInstance();
int_nf.setGroupingUsed(false); // no commas
int_nf_commas = false;
int_nf.setMinimumIntegerDigits(digits);
int_nf_digits = digits;
return int_nf.format(num);
}
/**
* ( begin auto-generated from nfc.xml )
*
* Utility function for formatting numbers into strings and placing
* appropriate commas to mark units of 1000. There are two versions, one
* for formatting ints and one for formatting an array of ints. The value
* for the <b>digits</b> parameter should always be a positive integer.
* <br/> <br/>
* For a non-US locale, this will insert periods instead of commas, or
* whatever is apprioriate for that region.
*
* ( end auto-generated )
* @webref data:string_functions
* @param num the number(s) to format
* @see PApplet#nf(float, int, int)
* @see PApplet#nfp(float, int, int)
* @see PApplet#nfc(float, int)
*/
static public String[] nfc(int num[]) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfc(num[i]);
}
return formatted;
}
/**
* nfc() or "number format with commas". This is an unfortunate misnomer
* because in locales where a comma is not the separator for numbers, it
* won't actually be outputting a comma, it'll use whatever makes sense for
* the locale.
*/
static public String nfc(int num) {
if ((int_nf != null) &&
(int_nf_digits == 0) &&
int_nf_commas) {
return int_nf.format(num);
}
int_nf = NumberFormat.getInstance();
int_nf.setGroupingUsed(true);
int_nf_commas = true;
int_nf.setMinimumIntegerDigits(0);
int_nf_digits = 0;
return int_nf.format(num);
}
/**
* number format signed (or space)
* Formats a number but leaves a blank space in the front
* when it's positive so that it can be properly aligned with
* numbers that have a negative sign in front of them.
*/
/**
* ( begin auto-generated from nfs.xml )
*
* Utility function for formatting numbers into strings. Similar to
* <b>nf()</b> but leaves a blank space in front of positive numbers so
* they align with negative numbers in spite of the minus symbol. There are
* two versions, one for formatting floats and one for formatting ints. The
* values for the <b>digits</b>, <b>left</b>, and <b>right</b> parameters
* should always be positive integers.
*
* ( end auto-generated )
* @webref data:string_functions
* @param num the number(s) to format
* @param digits number of digits to pad with zeroes
* @see PApplet#nf(float, int, int)
* @see PApplet#nfp(float, int, int)
* @see PApplet#nfc(float, int)
*/
static public String nfs(int num, int digits) {
return (num < 0) ? nf(num, digits) : (' ' + nf(num, digits));
}
static public String[] nfs(int num[], int digits) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfs(num[i], digits);
}
return formatted;
}
//
/**
* number format positive (or plus)
* Formats a number, always placing a - or + sign
* in the front when it's negative or positive.
*/
/**
* ( begin auto-generated from nfp.xml )
*
* Utility function for formatting numbers into strings. Similar to
* <b>nf()</b> but puts a "+" in front of positive numbers and a "-" in
* front of negative numbers. There are two versions, one for formatting
* floats and one for formatting ints. The values for the <b>digits</b>,
* <b>left</b>, and <b>right</b> parameters should always be positive integers.
*
* ( end auto-generated )
* @webref data:string_functions
* @param num the number(s) to format
* @param digits number of digits to pad with zeroes
* @see PApplet#nf(float, int, int)
* @see PApplet#nfs(float, int, int)
* @see PApplet#nfc(float, int)
*/
static public String nfp(int num, int digits) {
return (num < 0) ? nf(num, digits) : ('+' + nf(num, digits));
}
static public String[] nfp(int num[], int digits) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfp(num[i], digits);
}
return formatted;
}
//////////////////////////////////////////////////////////////
// FLOAT NUMBER FORMATTING
static private NumberFormat float_nf;
static private int float_nf_left, float_nf_right;
static private boolean float_nf_commas;
static public String[] nf(float num[], int left, int right) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nf(num[i], left, right);
}
return formatted;
}
/**
* @param num[] the number(s) to format
* @param left number of digits to the left of the decimal point
* @param right number of digits to the right of the decimal point
*/
static public String nf(float num, int left, int right) {
if ((float_nf != null) &&
(float_nf_left == left) &&
(float_nf_right == right) &&
!float_nf_commas) {
return float_nf.format(num);
}
float_nf = NumberFormat.getInstance();
float_nf.setGroupingUsed(false);
float_nf_commas = false;
if (left != 0) float_nf.setMinimumIntegerDigits(left);
if (right != 0) {
float_nf.setMinimumFractionDigits(right);
float_nf.setMaximumFractionDigits(right);
}
float_nf_left = left;
float_nf_right = right;
return float_nf.format(num);
}
/**
* @param num[] the number(s) to format
* @param right number of digits to the right of the decimal point
*/
static public String[] nfc(float num[], int right) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfc(num[i], right);
}
return formatted;
}
static public String nfc(float num, int right) {
if ((float_nf != null) &&
(float_nf_left == 0) &&
(float_nf_right == right) &&
float_nf_commas) {
return float_nf.format(num);
}
float_nf = NumberFormat.getInstance();
float_nf.setGroupingUsed(true);
float_nf_commas = true;
if (right != 0) {
float_nf.setMinimumFractionDigits(right);
float_nf.setMaximumFractionDigits(right);
}
float_nf_left = 0;
float_nf_right = right;
return float_nf.format(num);
}
/**
* @param num[] the number(s) to format
* @param left the number of digits to the left of the decimal point
* @param right the number of digits to the right of the decimal point
*/
static public String[] nfs(float num[], int left, int right) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfs(num[i], left, right);
}
return formatted;
}
static public String nfs(float num, int left, int right) {
return (num < 0) ? nf(num, left, right) : (' ' + nf(num, left, right));
}
/**
* @param left the number of digits to the left of the decimal point
* @param right the number of digits to the right of the decimal point
*/
static public String[] nfp(float num[], int left, int right) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfp(num[i], left, right);
}
return formatted;
}
static public String nfp(float num, int left, int right) {
return (num < 0) ? nf(num, left, right) : ('+' + nf(num, left, right));
}
//////////////////////////////////////////////////////////////
// HEX/BINARY CONVERSION
/**
* ( begin auto-generated from hex.xml )
*
* Converts a byte, char, int, or color to a String containing the
* equivalent hexadecimal notation. For example color(0, 102, 153) will
* convert to the String "FF006699". This function can help make your geeky
* debugging sessions much happier.
* <br/> <br/>
* Note that the maximum number of digits is 8, because an int value can
* only represent up to 32 bits. Specifying more than eight digits will
* simply shorten the string to eight anyway.
*
* ( end auto-generated )
* @webref data:conversion
* @param value the value to convert
* @see PApplet#unhex(String)
* @see PApplet#binary(byte)
* @see PApplet#unbinary(String)
*/
static final public String hex(byte value) {
return hex(value, 2);
}
static final public String hex(char value) {
return hex(value, 4);
}
static final public String hex(int value) {
return hex(value, 8);
}
/**
* @param digits the number of digits (maximum 8)
*/
static final public String hex(int value, int digits) {
String stuff = Integer.toHexString(value).toUpperCase();
if (digits > 8) {
digits = 8;
}
int length = stuff.length();
if (length > digits) {
return stuff.substring(length - digits);
} else if (length < digits) {
return "00000000".substring(8 - (digits-length)) + stuff;
}
return stuff;
}
/**
* ( begin auto-generated from unhex.xml )
*
* Converts a String representation of a hexadecimal number to its
* equivalent integer value.
*
* ( end auto-generated )
*
* @webref data:conversion
* @param value String to convert to an integer
* @see PApplet#hex(int, int)
* @see PApplet#binary(byte)
* @see PApplet#unbinary(String)
*/
static final public int unhex(String value) {
// has to parse as a Long so that it'll work for numbers bigger than 2^31
return (int) (Long.parseLong(value, 16));
}
//
/**
* Returns a String that contains the binary value of a byte.
* The returned value will always have 8 digits.
*/
static final public String binary(byte value) {
return binary(value, 8);
}
/**
* Returns a String that contains the binary value of a char.
* The returned value will always have 16 digits because chars
* are two bytes long.
*/
static final public String binary(char value) {
return binary(value, 16);
}
/**
* Returns a String that contains the binary value of an int. The length
* depends on the size of the number itself. If you want a specific number
* of digits use binary(int what, int digits) to specify how many.
*/
static final public String binary(int value) {
return binary(value, 32);
}
/*
* Returns a String that contains the binary value of an int.
* The digits parameter determines how many digits will be used.
*/
/**
* ( begin auto-generated from binary.xml )
*
* Converts a byte, char, int, or color to a String containing the
* equivalent binary notation. For example color(0, 102, 153, 255) will
* convert to the String "11111111000000000110011010011001". This function
* can help make your geeky debugging sessions much happier.
* <br/> <br/>
* Note that the maximum number of digits is 32, because an int value can
* only represent up to 32 bits. Specifying more than 32 digits will simply
* shorten the string to 32 anyway.
*
* ( end auto-generated )
* @webref data:conversion
* @param value value to convert
* @param digits number of digits to return
* @see PApplet#unbinary(String)
* @see PApplet#hex(int,int)
* @see PApplet#unhex(String)
*/
static final public String binary(int value, int digits) {
String stuff = Integer.toBinaryString(value);
if (digits > 32) {
digits = 32;
}
int length = stuff.length();
if (length > digits) {
return stuff.substring(length - digits);
} else if (length < digits) {
int offset = 32 - (digits-length);
return "00000000000000000000000000000000".substring(offset) + stuff;
}
return stuff;
}
/**
* ( begin auto-generated from unbinary.xml )
*
* Converts a String representation of a binary number to its equivalent
* integer value. For example, unbinary("00001000") will return 8.
*
* ( end auto-generated )
* @webref data:conversion
* @param value String to convert to an integer
* @see PApplet#binary(byte)
* @see PApplet#hex(int,int)
* @see PApplet#unhex(String)
*/
static final public int unbinary(String value) {
return Integer.parseInt(value, 2);
}
//////////////////////////////////////////////////////////////
// COLOR FUNCTIONS
// moved here so that they can work without
// the graphics actually being instantiated (outside setup)
/**
* ( begin auto-generated from color.xml )
*
* Creates colors for storing in variables of the <b>color</b> datatype.
* The parameters are interpreted as RGB or HSB values depending on the
* current <b>colorMode()</b>. The default mode is RGB values from 0 to 255
* and therefore, the function call <b>color(255, 204, 0)</b> will return a
* bright yellow color. More about how colors are stored can be found in
* the reference for the <a href="color_datatype.html">color</a> datatype.
*
* ( end auto-generated )
* @webref color:creating_reading
* @param gray number specifying value between white and black
* @see PApplet#colorMode(int)
*/
public final int color(int gray) {
if (g == null) {
if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
return 0xff000000 | (gray << 16) | (gray << 8) | gray;
}
return g.color(gray);
}
/**
* @nowebref
* @param fgray number specifying value between white and black
*/
public final int color(float fgray) {
if (g == null) {
int gray = (int) fgray;
if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
return 0xff000000 | (gray << 16) | (gray << 8) | gray;
}
return g.color(fgray);
}
/**
* As of 0116 this also takes color(#FF8800, alpha)
* @param alpha relative to current color range
*/
public final int color(int gray, int alpha) {
if (g == null) {
if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
if (gray > 255) {
// then assume this is actually a #FF8800
return (alpha << 24) | (gray & 0xFFFFFF);
} else {
//if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
return (alpha << 24) | (gray << 16) | (gray << 8) | gray;
}
}
return g.color(gray, alpha);
}
/**
* @nowebref
*/
public final int color(float fgray, float falpha) {
if (g == null) {
int gray = (int) fgray;
int alpha = (int) falpha;
if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
return 0xff000000 | (gray << 16) | (gray << 8) | gray;
}
return g.color(fgray, falpha);
}
/**
* @param v1 red or hue values relative to the current color range
* @param v2 green or saturation values relative to the current color range
* @param v3 blue or brightness values relative to the current color range
*/
public final int color(int v1, int v2, int v3) {
if (g == null) {
if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0;
if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0;
if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0;
return 0xff000000 | (v1 << 16) | (v2 << 8) | v3;
}
return g.color(v1, v2, v3);
}
public final int color(int v1, int v2, int v3, int alpha) {
if (g == null) {
if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0;
if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0;
if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0;
return (alpha << 24) | (v1 << 16) | (v2 << 8) | v3;
}
return g.color(v1, v2, v3, alpha);
}
public final int color(float v1, float v2, float v3) {
if (g == null) {
if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0;
if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0;
if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0;
return 0xff000000 | ((int)v1 << 16) | ((int)v2 << 8) | (int)v3;
}
return g.color(v1, v2, v3);
}
public final int color(float v1, float v2, float v3, float alpha) {
if (g == null) {
if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0;
if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0;
if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0;
return ((int)alpha << 24) | ((int)v1 << 16) | ((int)v2 << 8) | (int)v3;
}
return g.color(v1, v2, v3, alpha);
}
static public int blendColor(int c1, int c2, int mode) {
return PImage.blendColor(c1, c2, mode);
}
//////////////////////////////////////////////////////////////
// MAIN
/**
* Set this sketch to communicate its state back to the PDE.
* <p/>
* This uses the stderr stream to write positions of the window
* (so that it will be saved by the PDE for the next run) and
* notify on quit. See more notes in the Worker class.
*/
public void setupExternalMessages() {
frame.addComponentListener(new ComponentAdapter() {
@Override
public void componentMoved(ComponentEvent e) {
Point where = ((Frame) e.getSource()).getLocation();
System.err.println(PApplet.EXTERNAL_MOVE + " " +
where.x + " " + where.y);
System.err.flush(); // doesn't seem to help or hurt
}
});
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
// System.err.println(PApplet.EXTERNAL_QUIT);
// System.err.flush(); // important
// System.exit(0);
exit(); // don't quit, need to just shut everything down (0133)
}
});
}
/**
* Set up a listener that will fire proper component resize events
* in cases where frame.setResizable(true) is called.
*/
public void setupFrameResizeListener() {
frame.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
// Ignore bad resize events fired during setup to fix
// http://dev.processing.org/bugs/show_bug.cgi?id=341
// This should also fix the blank screen on Linux bug
// http://dev.processing.org/bugs/show_bug.cgi?id=282
if (frame.isResizable()) {
// might be multiple resize calls before visible (i.e. first
// when pack() is called, then when it's resized for use).
// ignore them because it's not the user resizing things.
Frame farm = (Frame) e.getComponent();
if (farm.isVisible()) {
Insets insets = farm.getInsets();
Dimension windowSize = farm.getSize();
Rectangle newBounds =
new Rectangle(insets.left, insets.top,
windowSize.width - insets.left - insets.right,
windowSize.height - insets.top - insets.bottom);
Rectangle oldBounds = getBounds();
if (!newBounds.equals(oldBounds)) {
// the ComponentListener in PApplet will handle calling size()
setBounds(newBounds);
}
}
}
}
});
}
// /**
// * GIF image of the Processing logo.
// */
// static public final byte[] ICON_IMAGE = {
// 71, 73, 70, 56, 57, 97, 16, 0, 16, 0, -77, 0, 0, 0, 0, 0, -1, -1, -1, 12,
// 12, 13, -15, -15, -14, 45, 57, 74, 54, 80, 111, 47, 71, 97, 62, 88, 117,
// 1, 14, 27, 7, 41, 73, 15, 52, 85, 2, 31, 55, 4, 54, 94, 18, 69, 109, 37,
// 87, 126, -1, -1, -1, 33, -7, 4, 1, 0, 0, 15, 0, 44, 0, 0, 0, 0, 16, 0, 16,
// 0, 0, 4, 122, -16, -107, 114, -86, -67, 83, 30, -42, 26, -17, -100, -45,
// 56, -57, -108, 48, 40, 122, -90, 104, 67, -91, -51, 32, -53, 77, -78, -100,
// 47, -86, 12, 76, -110, -20, -74, -101, 97, -93, 27, 40, 20, -65, 65, 48,
// -111, 99, -20, -112, -117, -123, -47, -105, 24, 114, -112, 74, 69, 84, 25,
// 93, 88, -75, 9, 46, 2, 49, 88, -116, -67, 7, -19, -83, 60, 38, 3, -34, 2,
// 66, -95, 27, -98, 13, 4, -17, 55, 33, 109, 11, 11, -2, -128, 121, 123, 62,
// 91, 120, -128, 127, 122, 115, 102, 2, 119, 0, -116, -113, -119, 6, 102,
// 121, -108, -126, 5, 18, 6, 4, -102, -101, -100, 114, 15, 17, 0, 59
// };
static ArrayList<Image> iconImages;
protected void setIconImage(Frame frame) {
// On OS X, this only affects what shows up in the dock when minimized.
// So this is actually a step backwards. Brilliant.
if (platform != MACOSX) {
//Image image = Toolkit.getDefaultToolkit().createImage(ICON_IMAGE);
//frame.setIconImage(image);
try {
if (iconImages == null) {
iconImages = new ArrayList<Image>();
final int[] sizes = { 16, 24, 32, 48, 64 };
for (int sz : sizes) {
URL url = getClass().getResource("/icon/icon-" + sz + ".png");
Image image = Toolkit.getDefaultToolkit().getImage(url);
iconImages.add(image);
//iconImages.add(Toolkit.getLibImage("icons/pde-" + sz + ".png", frame));
}
}
frame.setIconImages(iconImages);
} catch (Exception e) {
//e.printStackTrace(); // more or less harmless; don't spew errors
}
}
}
// Not gonna do this dynamically, only on startup. Too much headache.
// public void fullscreen() {
// if (frame != null) {
// if (PApplet.platform == MACOSX) {
// japplemenubar.JAppleMenuBar.hide();
// }
// GraphicsConfiguration gc = frame.getGraphicsConfiguration();
// Rectangle rect = gc.getBounds();
//// GraphicsDevice device = gc.getDevice();
// frame.setBounds(rect.x, rect.y, rect.width, rect.height);
// }
// }
/**
* main() method for running this class from the command line.
* <p>
* <B>The options shown here are not yet finalized and will be
* changing over the next several releases.</B>
* <p>
* The simplest way to turn and applet into an application is to
* add the following code to your program:
* <PRE>static public void main(String args[]) {
* PApplet.main("YourSketchName", args);
* }</PRE>
* This will properly launch your applet from a double-clickable
* .jar or from the command line.
* <PRE>
* Parameters useful for launching or also used by the PDE:
*
* --location=x,y upper-lefthand corner of where the applet
* should appear on screen. if not used,
* the default is to center on the main screen.
*
* --full-screen put the applet into full screen "present" mode.
*
* --hide-stop use to hide the stop button in situations where
* you don't want to allow users to exit. also
* see the FAQ on information for capturing the ESC
* key when running in presentation mode.
*
* --stop-color=#xxxxxx color of the 'stop' text used to quit an
* sketch when it's in present mode.
*
* --bgcolor=#xxxxxx background color of the window.
*
* --sketch-path location of where to save files from functions
* like saveStrings() or saveFrame(). defaults to
* the folder that the java application was
* launched from, which means if this isn't set by
* the pde, everything goes into the same folder
* as processing.exe.
*
* --display=n set what display should be used by this sketch.
* displays are numbered starting from 0.
*
* Parameters used by Processing when running via the PDE
*
* --external set when the applet is being used by the PDE
*
* --editor-location=x,y position of the upper-lefthand corner of the
* editor window, for placement of applet window
* </PRE>
*/
static public void main(final String[] args) {
runSketch(args, null);
}
/**
* Convenience method so that PApplet.main("YourSketch") launches a sketch,
* rather than having to wrap it into a String array.
* @param mainClass name of the class to load (with package if any)
*/
static public void main(final String mainClass) {
main(mainClass, null);
}
/**
* Convenience method so that PApplet.main("YourSketch", args) launches a
* sketch, rather than having to wrap it into a String array, and appending
* the 'args' array when not null.
* @param mainClass name of the class to load (with package if any)
* @param args command line arguments to pass to the sketch
*/
static public void main(final String mainClass, final String[] passedArgs) {
String[] args = new String[] { mainClass };
if (passedArgs != null) {
args = concat(args, passedArgs);
}
runSketch(args, null);
}
static public void runSketch(final String args[], final PApplet constructedApplet) {
// Disable abyssmally slow Sun renderer on OS X 10.5.
if (platform == MACOSX) {
// Only run this on OS X otherwise it can cause a permissions error.
// http://dev.processing.org/bugs/show_bug.cgi?id=976
System.setProperty("apple.awt.graphics.UseQuartz",
String.valueOf(useQuartz));
}
// Doesn't seem to do much to help avoid flicker
System.setProperty("sun.awt.noerasebackground", "true");
// This doesn't do anything.
// if (platform == WINDOWS) {
// // For now, disable the D3D renderer on Java 6u10 because
// // it causes problems with Present mode.
// // http://dev.processing.org/bugs/show_bug.cgi?id=1009
// System.setProperty("sun.java2d.d3d", "false");
// }
if (args.length < 1) {
System.err.println("Usage: PApplet <appletname>");
System.err.println("For additional options, " +
"see the Javadoc for PApplet");
System.exit(1);
}
// EventQueue.invokeLater(new Runnable() {
// public void run() {
// runSketchEDT(args, constructedApplet);
// }
// });
// }
//
//
// static public void runSketchEDT(final String args[], final PApplet constructedApplet) {
boolean external = false;
int[] location = null;
int[] editorLocation = null;
String name = null;
boolean present = false;
// boolean exclusive = false;
// Color backgroundColor = Color.BLACK;
Color backgroundColor = null; //Color.BLACK;
Color stopColor = Color.GRAY;
GraphicsDevice displayDevice = null;
boolean hideStop = false;
String param = null, value = null;
// try to get the user folder. if running under java web start,
// this may cause a security exception if the code is not signed.
// http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Integrate;action=display;num=1159386274
String folder = null;
try {
folder = System.getProperty("user.dir");
} catch (Exception e) { }
int argIndex = 0;
while (argIndex < args.length) {
int equals = args[argIndex].indexOf('=');
if (equals != -1) {
param = args[argIndex].substring(0, equals);
value = args[argIndex].substring(equals + 1);
if (param.equals(ARGS_EDITOR_LOCATION)) {
external = true;
editorLocation = parseInt(split(value, ','));
} else if (param.equals(ARGS_DISPLAY)) {
int deviceIndex = Integer.parseInt(value);
GraphicsEnvironment environment =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice devices[] = environment.getScreenDevices();
if ((deviceIndex >= 0) && (deviceIndex < devices.length)) {
displayDevice = devices[deviceIndex];
} else {
System.err.println("Display " + value + " does not exist, " +
"using the default display instead.");
for (int i = 0; i < devices.length; i++) {
System.err.println(i + " is " + devices[i]);
}
}
} else if (param.equals(ARGS_BGCOLOR)) {
if (value.charAt(0) == '#') value = value.substring(1);
backgroundColor = new Color(Integer.parseInt(value, 16));
} else if (param.equals(ARGS_STOP_COLOR)) {
if (value.charAt(0) == '#') value = value.substring(1);
stopColor = new Color(Integer.parseInt(value, 16));
} else if (param.equals(ARGS_SKETCH_FOLDER)) {
folder = value;
} else if (param.equals(ARGS_LOCATION)) {
location = parseInt(split(value, ','));
}
} else {
if (args[argIndex].equals(ARGS_PRESENT)) { // keep for compatability
present = true;
} else if (args[argIndex].equals(ARGS_FULL_SCREEN)) {
present = true;
// } else if (args[argIndex].equals(ARGS_EXCLUSIVE)) {
// exclusive = true;
} else if (args[argIndex].equals(ARGS_HIDE_STOP)) {
hideStop = true;
} else if (args[argIndex].equals(ARGS_EXTERNAL)) {
external = true;
} else {
name = args[argIndex];
break; // because of break, argIndex won't increment again
}
}
argIndex++;
}
// Set this property before getting into any GUI init code
//System.setProperty("com.apple.mrj.application.apple.menu.about.name", name);
// This )*)(*@#$ Apple crap don't work no matter where you put it
// (static method of the class, at the top of main, wherever)
if (displayDevice == null) {
GraphicsEnvironment environment =
GraphicsEnvironment.getLocalGraphicsEnvironment();
displayDevice = environment.getDefaultScreenDevice();
}
Frame frame = new Frame(displayDevice.getDefaultConfiguration());
// JFrame frame = new JFrame(displayDevice.getDefaultConfiguration());
/*
Frame frame = null;
if (displayDevice != null) {
frame = new Frame(displayDevice.getDefaultConfiguration());
} else {
frame = new Frame();
}
*/
//Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
// remove the grow box by default
// users who want it back can call frame.setResizable(true)
// frame.setResizable(false);
// moved later (issue #467)
final PApplet applet;
if (constructedApplet != null) {
applet = constructedApplet;
} else {
try {
Class<?> c = Thread.currentThread().getContextClassLoader().loadClass(name);
applet = (PApplet) c.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// Set the trimmings around the image
applet.setIconImage(frame);
frame.setTitle(name);
// frame.setIgnoreRepaint(true); // does nothing
// frame.addComponentListener(new ComponentAdapter() {
// public void componentResized(ComponentEvent e) {
// Component c = e.getComponent();
//// Rectangle bounds = c.getBounds();
// System.out.println(" " + c.getName() + " wants to be: " + c.getSize());
// }
// });
// frame.addComponentListener(new ComponentListener() {
//
// public void componentShown(ComponentEvent e) {
// debug("frame: " + e);
// debug(" applet valid? " + applet.isValid());
//// ((PGraphicsJava2D) applet.g).redraw();
// }
//
// public void componentResized(ComponentEvent e) {
// println("frame: " + e + " " + applet.frame.getInsets());
// Insets insets = applet.frame.getInsets();
// int wide = e.getComponent().getWidth() - (insets.left + insets.right);
// int high = e.getComponent().getHeight() - (insets.top + insets.bottom);
// if (applet.getWidth() != wide || applet.getHeight() != high) {
// debug("Frame.componentResized() setting applet size " + wide + " " + high);
// applet.setSize(wide, high);
// }
// }
//
// public void componentMoved(ComponentEvent e) {
// //println("frame: " + e + " " + applet.frame.getInsets());
// Insets insets = applet.frame.getInsets();
// int wide = e.getComponent().getWidth() - (insets.left + insets.right);
// int high = e.getComponent().getHeight() - (insets.top + insets.bottom);
// //applet.g.setsi
// if (applet.getWidth() != wide || applet.getHeight() != high) {
// debug("Frame.componentMoved() setting applet size " + wide + " " + high);
// applet.setSize(wide, high);
// }
// }
//
// public void componentHidden(ComponentEvent e) {
// debug("frame: " + e);
// }
// });
// A handful of things that need to be set before init/start.
applet.frame = frame;
applet.sketchPath = folder;
// If the applet doesn't call for full screen, but the command line does,
// enable it. Conversely, if the command line does not, don't disable it.
// applet.fullScreen |= present;
// Query the applet to see if it wants to be full screen all the time.
present |= applet.sketchFullScreen();
// pass everything after the class name in as args to the sketch itself
// (fixed for 2.0a5, this was just subsetting by 1, which didn't skip opts)
applet.args = PApplet.subset(args, argIndex + 1);
applet.external = external;
// Need to save the window bounds at full screen,
// because pack() will cause the bounds to go to zero.
// http://dev.processing.org/bugs/show_bug.cgi?id=923
Rectangle screenRect =
displayDevice.getDefaultConfiguration().getBounds();
// DisplayMode doesn't work here, because we can't get the upper-left
// corner of the display, which is important for multi-display setups.
// Sketch has already requested to be the same as the screen's
// width and height, so let's roll with full screen mode.
if (screenRect.width == applet.sketchWidth() &&
screenRect.height == applet.sketchHeight()) {
present = true;
}
// For 0149, moving this code (up to the pack() method) before init().
// For OpenGL (and perhaps other renderers in the future), a peer is
// needed before a GLDrawable can be created. So pack() needs to be
// called on the Frame before applet.init(), which itself calls size(),
// and launches the Thread that will kick off setup().
// http://dev.processing.org/bugs/show_bug.cgi?id=891
// http://dev.processing.org/bugs/show_bug.cgi?id=908
if (present) {
// if (platform == MACOSX) {
// // Call some native code to remove the menu bar on OS X. Not necessary
// // on Linux and Windows, who are happy to make full screen windows.
// japplemenubar.JAppleMenuBar.hide();
// }
frame.setUndecorated(true);
if (backgroundColor != null) {
frame.setBackground(backgroundColor);
}
// if (exclusive) {
// displayDevice.setFullScreenWindow(frame);
// // this trashes the location of the window on os x
// //frame.setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
// fullScreenRect = frame.getBounds();
// } else {
frame.setBounds(screenRect);
frame.setVisible(true);
// }
}
frame.setLayout(null);
frame.add(applet);
if (present) {
frame.invalidate();
} else {
frame.pack();
}
// insufficient, places the 100x100 sketches offset strangely
//frame.validate();
// disabling resize has to happen after pack() to avoid apparent Apple bug
// http://code.google.com/p/processing/issues/detail?id=467
frame.setResizable(false);
applet.init();
// applet.start();
// Wait until the applet has figured out its width.
// In a static mode app, this will be after setup() has completed,
// and the empty draw() has set "finished" to true.
// TODO make sure this won't hang if the applet has an exception.
while (applet.defaultSize && !applet.finished) {
//System.out.println("default size");
try {
Thread.sleep(5);
} catch (InterruptedException e) {
//System.out.println("interrupt");
}
}
// // If 'present' wasn't already set, but the applet initializes
// // to full screen, attempt to make things full screen anyway.
// if (!present &&
// applet.width == screenRect.width &&
// applet.height == screenRect.height) {
// // bounds will be set below, but can't change to setUndecorated() now
// present = true;
// }
// // Opting not to do this, because we can't remove the decorations on the
// // window at this point. And re-opening a new winodw is a lot of mess.
// // Better all around to just encourage the use of sketchFullScreen()
// // or cmd/ctrl-shift-R in the PDE.
if (present) {
if (platform == MACOSX) {
// Call some native code to remove the menu bar on OS X. Not necessary
// on Linux and Windows, who are happy to make full screen windows.
japplemenubar.JAppleMenuBar.hide();
}
// After the pack(), the screen bounds are gonna be 0s
frame.setBounds(screenRect);
applet.setBounds((screenRect.width - applet.width) / 2,
(screenRect.height - applet.height) / 2,
applet.width, applet.height);
if (!hideStop) {
Label label = new Label("stop");
label.setForeground(stopColor);
label.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(java.awt.event.MouseEvent e) {
System.exit(0);
}
});
frame.add(label);
Dimension labelSize = label.getPreferredSize();
// sometimes shows up truncated on mac
//System.out.println("label width is " + labelSize.width);
labelSize = new Dimension(100, labelSize.height);
label.setSize(labelSize);
label.setLocation(20, screenRect.height - labelSize.height - 20);
}
// not always running externally when in present mode
if (external) {
applet.setupExternalMessages();
}
} else { // if not presenting
// can't do pack earlier cuz present mode don't like it
// (can't go full screen with a frame after calling pack)
// frame.pack(); // get insets. get more.
Insets insets = frame.getInsets();
int windowW = Math.max(applet.width, MIN_WINDOW_WIDTH) +
insets.left + insets.right;
int windowH = Math.max(applet.height, MIN_WINDOW_HEIGHT) +
insets.top + insets.bottom;
frame.setSize(windowW, windowH);
if (location != null) {
// a specific location was received from the Runner
// (applet has been run more than once, user placed window)
frame.setLocation(location[0], location[1]);
} else if (external && editorLocation != null) {
int locationX = editorLocation[0] - 20;
int locationY = editorLocation[1];
if (locationX - windowW > 10) {
// if it fits to the left of the window
frame.setLocation(locationX - windowW, locationY);
} else { // doesn't fit
// if it fits inside the editor window,
// offset slightly from upper lefthand corner
// so that it's plunked inside the text area
locationX = editorLocation[0] + 66;
locationY = editorLocation[1] + 66;
if ((locationX + windowW > applet.displayWidth - 33) ||
(locationY + windowH > applet.displayHeight - 33)) {
// otherwise center on screen
locationX = (applet.displayWidth - windowW) / 2;
locationY = (applet.displayHeight - windowH) / 2;
}
frame.setLocation(locationX, locationY);
}
} else { // just center on screen
// Can't use frame.setLocationRelativeTo(null) because it sends the
// frame to the main display, which undermines the --display setting.
frame.setLocation(screenRect.x + (screenRect.width - applet.width) / 2,
screenRect.y + (screenRect.height - applet.height) / 2);
}
Point frameLoc = frame.getLocation();
if (frameLoc.y < 0) {
// Windows actually allows you to place frames where they can't be
// closed. Awesome. http://dev.processing.org/bugs/show_bug.cgi?id=1508
frame.setLocation(frameLoc.x, 30);
}
if (backgroundColor != null) {
// if (backgroundColor == Color.black) { //BLACK) {
// // this means no bg color unless specified
// backgroundColor = SystemColor.control;
// }
frame.setBackground(backgroundColor);
}
int usableWindowH = windowH - insets.top - insets.bottom;
applet.setBounds((windowW - applet.width)/2,
insets.top + (usableWindowH - applet.height)/2,
applet.width, applet.height);
if (external) {
applet.setupExternalMessages();
} else { // !external
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
}
// handle frame resizing events
applet.setupFrameResizeListener();
// all set for rockin
if (applet.displayable()) {
frame.setVisible(true);
}
}
// Disabling for 0185, because it causes an assertion failure on OS X
// http://code.google.com/p/processing/issues/detail?id=258
// (Although this doesn't seem to be the one that was causing problems.)
//applet.requestFocus(); // ask for keydowns
}
/**
* These methods provide a means for running an already-constructed
* sketch. In particular, it makes it easy to launch a sketch in
* Jython:
*
* <pre>class MySketch(PApplet):
* pass
*
*MySketch().runSketch();</pre>
*/
protected void runSketch(final String[] args) {
final String[] argsWithSketchName = new String[args.length + 1];
System.arraycopy(args, 0, argsWithSketchName, 0, args.length);
final String className = this.getClass().getSimpleName();
final String cleanedClass =
className.replaceAll("__[^_]+__\\$", "").replaceAll("\\$\\d+", "");
argsWithSketchName[args.length] = cleanedClass;
runSketch(argsWithSketchName, this);
}
protected void runSketch() {
runSketch(new String[0]);
}
//////////////////////////////////////////////////////////////
/**
* ( begin auto-generated from beginRecord.xml )
*
* Opens a new file and all subsequent drawing functions are echoed to this
* file as well as the display window. The <b>beginRecord()</b> function
* requires two parameters, the first is the renderer and the second is the
* file name. This function is always used with <b>endRecord()</b> to stop
* the recording process and close the file.
* <br /> <br />
* Note that beginRecord() will only pick up any settings that happen after
* it has been called. For instance, if you call textFont() before
* beginRecord(), then that font will not be set for the file that you're
* recording to.
*
* ( end auto-generated )
*
* @webref output:files
* @param renderer for example, PDF
* @param filename filename for output
* @see PApplet#endRecord()
*/
public PGraphics beginRecord(String renderer, String filename) {
filename = insertFrame(filename);
PGraphics rec = createGraphics(width, height, renderer, filename);
beginRecord(rec);
return rec;
}
/**
* @nowebref
* Begin recording (echoing) commands to the specified PGraphics object.
*/
public void beginRecord(PGraphics recorder) {
this.recorder = recorder;
recorder.beginDraw();
}
/**
* ( begin auto-generated from endRecord.xml )
*
* Stops the recording process started by <b>beginRecord()</b> and closes
* the file.
*
* ( end auto-generated )
* @webref output:files
* @see PApplet#beginRecord(String, String)
*/
public void endRecord() {
if (recorder != null) {
recorder.endDraw();
recorder.dispose();
recorder = null;
}
}
/**
* ( begin auto-generated from beginRaw.xml )
*
* To create vectors from 3D data, use the <b>beginRaw()</b> and
* <b>endRaw()</b> commands. These commands will grab the shape data just
* before it is rendered to the screen. At this stage, your entire scene is
* nothing but a long list of individual lines and triangles. This means
* that a shape created with <b>sphere()</b> function will be made up of
* hundreds of triangles, rather than a single object. Or that a
* multi-segment line shape (such as a curve) will be rendered as
* individual segments.
* <br /><br />
* When using <b>beginRaw()</b> and <b>endRaw()</b>, it's possible to write
* to either a 2D or 3D renderer. For instance, <b>beginRaw()</b> with the
* PDF library will write the geometry as flattened triangles and lines,
* even if recording from the <b>P3D</b> renderer.
* <br /><br />
* If you want a background to show up in your files, use <b>rect(0, 0,
* width, height)</b> after setting the <b>fill()</b> to the background
* color. Otherwise the background will not be rendered to the file because
* the background is not shape.
* <br /><br />
* Using <b>hint(ENABLE_DEPTH_SORT)</b> can improve the appearance of 3D
* geometry drawn to 2D file formats. See the <b>hint()</b> reference for
* more details.
* <br /><br />
* See examples in the reference for the <b>PDF</b> and <b>DXF</b>
* libraries for more information.
*
* ( end auto-generated )
*
* @webref output:files
* @param renderer for example, PDF or DXF
* @param filename filename for output
* @see PApplet#endRaw()
* @see PApplet#hint(int)
*/
public PGraphics beginRaw(String renderer, String filename) {
filename = insertFrame(filename);
PGraphics rec = createGraphics(width, height, renderer, filename);
g.beginRaw(rec);
return rec;
}
/**
* @nowebref
* Begin recording raw shape data to the specified renderer.
*
* This simply echoes to g.beginRaw(), but since is placed here (rather than
* generated by preproc.pl) for clarity and so that it doesn't echo the
* command should beginRecord() be in use.
*
* @param rawGraphics ???
*/
public void beginRaw(PGraphics rawGraphics) {
g.beginRaw(rawGraphics);
}
/**
* ( begin auto-generated from endRaw.xml )
*
* Complement to <b>beginRaw()</b>; they must always be used together. See
* the <b>beginRaw()</b> reference for details.
*
* ( end auto-generated )
*
* @webref output:files
* @see PApplet#beginRaw(String, String)
*/
public void endRaw() {
g.endRaw();
}
/**
* Starts shape recording and returns the PShape object that will
* contain the geometry.
*/
/*
public PShape beginRecord() {
return g.beginRecord();
}
*/
//////////////////////////////////////////////////////////////
/**
* ( begin auto-generated from loadPixels.xml )
*
* Loads the pixel data for the display window into the <b>pixels[]</b>
* array. This function must always be called before reading from or
* writing to <b>pixels[]</b>.
* <br/><br/> renderers may or may not seem to require <b>loadPixels()</b>
* or <b>updatePixels()</b>. However, the rule is that any time you want to
* manipulate the <b>pixels[]</b> array, you must first call
* <b>loadPixels()</b>, and after changes have been made, call
* <b>updatePixels()</b>. Even if the renderer may not seem to use this
* function in the current Processing release, this will always be subject
* to change.
*
* ( end auto-generated )
* <h3>Advanced</h3>
* Override the g.pixels[] function to set the pixels[] array
* that's part of the PApplet object. Allows the use of
* pixels[] in the code, rather than g.pixels[].
*
* @webref image:pixels
* @see PApplet#pixels
* @see PApplet#updatePixels()
*/
public void loadPixels() {
g.loadPixels();
pixels = g.pixels;
}
/**
* ( begin auto-generated from updatePixels.xml )
*
* Updates the display window with the data in the <b>pixels[]</b> array.
* Use in conjunction with <b>loadPixels()</b>. If you're only reading
* pixels from the array, there's no need to call <b>updatePixels()</b>
* unless there are changes.
* <br/><br/> renderers may or may not seem to require <b>loadPixels()</b>
* or <b>updatePixels()</b>. However, the rule is that any time you want to
* manipulate the <b>pixels[]</b> array, you must first call
* <b>loadPixels()</b>, and after changes have been made, call
* <b>updatePixels()</b>. Even if the renderer may not seem to use this
* function in the current Processing release, this will always be subject
* to change.
* <br/> <br/>
* Currently, none of the renderers use the additional parameters to
* <b>updatePixels()</b>, however this may be implemented in the future.
*
* ( end auto-generated )
* @webref image:pixels
* @see PApplet#loadPixels()
* @see PApplet#pixels
*/
public void updatePixels() {
g.updatePixels();
}
/**
* @nowebref
* @param x1 x-coordinate of the upper-left corner
* @param y1 y-coordinate of the upper-left corner
* @param x2 width of the region
* @param y2 height of the region
*/
public void updatePixels(int x1, int y1, int x2, int y2) {
g.updatePixels(x1, y1, x2, y2);
}
//////////////////////////////////////////////////////////////
// EVERYTHING BELOW THIS LINE IS AUTOMATICALLY GENERATED. DO NOT TOUCH!
// This includes the Javadoc comments, which are automatically copied from
// the PImage and PGraphics source code files.
// public functions for processing.core
/**
* Store data of some kind for the renderer that requires extra metadata of
* some kind. Usually this is a renderer-specific representation of the
* image data, for instance a BufferedImage with tint() settings applied for
* PGraphicsJava2D, or resized image data and OpenGL texture indices for
* PGraphicsOpenGL.
* @param renderer The PGraphics renderer associated to the image
* @param storage The metadata required by the renderer
*/
public void setCache(PImage image, Object storage) {
if (recorder != null) recorder.setCache(image, storage);
g.setCache(image, storage);
}
/**
* Get cache storage data for the specified renderer. Because each renderer
* will cache data in different formats, it's necessary to store cache data
* keyed by the renderer object. Otherwise, attempting to draw the same
* image to both a PGraphicsJava2D and a PGraphicsOpenGL will cause errors.
* @param renderer The PGraphics renderer associated to the image
* @return metadata stored for the specified renderer
*/
public Object getCache(PImage image) {
return g.getCache(image);
}
/**
* Remove information associated with this renderer from the cache, if any.
* @param renderer The PGraphics renderer whose cache data should be removed
*/
public void removeCache(PImage image) {
if (recorder != null) recorder.removeCache(image);
g.removeCache(image);
}
public PGL beginPGL() {
return g.beginPGL();
}
public void endPGL() {
if (recorder != null) recorder.endPGL();
g.endPGL();
}
public void flush() {
if (recorder != null) recorder.flush();
g.flush();
}
public void hint(int which) {
if (recorder != null) recorder.hint(which);
g.hint(which);
}
/**
* Start a new shape of type POLYGON
*/
public void beginShape() {
if (recorder != null) recorder.beginShape();
g.beginShape();
}
/**
* ( begin auto-generated from beginShape.xml )
*
* Using the <b>beginShape()</b> and <b>endShape()</b> functions allow
* creating more complex forms. <b>beginShape()</b> begins recording
* vertices for a shape and <b>endShape()</b> stops recording. The value of
* the <b>MODE</b> parameter tells it which types of shapes to create from
* the provided vertices. With no mode specified, the shape can be any
* irregular polygon. The parameters available for beginShape() are POINTS,
* LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, and QUAD_STRIP.
* After calling the <b>beginShape()</b> function, a series of
* <b>vertex()</b> commands must follow. To stop drawing the shape, call
* <b>endShape()</b>. The <b>vertex()</b> function with two parameters
* specifies a position in 2D and the <b>vertex()</b> function with three
* parameters specifies a position in 3D. Each shape will be outlined with
* the current stroke color and filled with the fill color.
* <br/> <br/>
* Transformations such as <b>translate()</b>, <b>rotate()</b>, and
* <b>scale()</b> do not work within <b>beginShape()</b>. It is also not
* possible to use other shapes, such as <b>ellipse()</b> or <b>rect()</b>
* within <b>beginShape()</b>.
* <br/> <br/>
* The P3D renderer settings allow <b>stroke()</b> and <b>fill()</b>
* settings to be altered per-vertex, however the default P2D renderer does
* not. Settings such as <b>strokeWeight()</b>, <b>strokeCap()</b>, and
* <b>strokeJoin()</b> cannot be changed while inside a
* <b>beginShape()</b>/<b>endShape()</b> block with any renderer.
*
* ( end auto-generated )
* @webref shape:vertex
* @param kind Either POINTS, LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, or QUAD_STRIP
* @see PGraphics#endShape()
* @see PGraphics#vertex(float, float, float, float, float)
* @see PGraphics#curveVertex(float, float, float)
* @see PGraphics#bezierVertex(float, float, float, float, float, float, float, float, float)
*/
public void beginShape(int kind) {
if (recorder != null) recorder.beginShape(kind);
g.beginShape(kind);
}
/**
* Sets whether the upcoming vertex is part of an edge.
* Equivalent to glEdgeFlag(), for people familiar with OpenGL.
*/
public void edge(boolean edge) {
if (recorder != null) recorder.edge(edge);
g.edge(edge);
}
/**
* ( begin auto-generated from normal.xml )
*
* Sets the current normal vector. This is for drawing three dimensional
* shapes and surfaces and specifies a vector perpendicular to the surface
* of the shape which determines how lighting affects it. Processing
* attempts to automatically assign normals to shapes, but since that's
* imperfect, this is a better option when you want more control. This
* function is identical to glNormal3f() in OpenGL.
*
* ( end auto-generated )
* @webref lights_camera:lights
* @param nx x direction
* @param ny y direction
* @param nz z direction
* @see PGraphics#beginShape(int)
* @see PGraphics#endShape(int)
* @see PGraphics#lights()
*/
public void normal(float nx, float ny, float nz) {
if (recorder != null) recorder.normal(nx, ny, nz);
g.normal(nx, ny, nz);
}
/**
* ( begin auto-generated from textureMode.xml )
*
* Sets the coordinate space for texture mapping. There are two options,
* IMAGE, which refers to the actual coordinates of the image, and
* NORMAL, which refers to a normalized space of values ranging from 0
* to 1. The default mode is IMAGE. In IMAGE, if an image is 100 x 200
* pixels, mapping the image onto the entire size of a quad would require
* the points (0,0) (0,100) (100,200) (0,200). The same mapping in
* NORMAL_SPACE is (0,0) (0,1) (1,1) (0,1).
*
* ( end auto-generated )
* @webref image:textures
* @param mode either IMAGE or NORMAL
* @see PGraphics#texture(PImage)
*/
public void textureMode(int mode) {
if (recorder != null) recorder.textureMode(mode);
g.textureMode(mode);
}
/**
* ( begin auto-generated from textureWrap.xml )
*
* Description to come...
*
* ( end auto-generated from textureWrap.xml )
*
* @webref image:textures
* @param wrap Either CLAMP (default) or REPEAT
*/
public void textureWrap(int wrap) {
if (recorder != null) recorder.textureWrap(wrap);
g.textureWrap(wrap);
}
/**
* ( begin auto-generated from texture.xml )
*
* Sets a texture to be applied to vertex points. The <b>texture()</b>
* function must be called between <b>beginShape()</b> and
* <b>endShape()</b> and before any calls to <b>vertex()</b>.
* <br/> <br/>
* When textures are in use, the fill color is ignored. Instead, use tint()
* to specify the color of the texture as it is applied to the shape.
*
* ( end auto-generated )
* @webref image:textures
* @param image reference to a PImage object
* @see PGraphics#textureMode(int)
* @see PGraphics#beginShape(int)
* @see PGraphics#endShape(int)
* @see PGraphics#vertex(float, float, float, float, float)
*/
public void texture(PImage image) {
if (recorder != null) recorder.texture(image);
g.texture(image);
}
/**
* Removes texture image for current shape.
* Needs to be called between beginShape and endShape
*
*/
public void noTexture() {
if (recorder != null) recorder.noTexture();
g.noTexture();
}
public void vertex(float x, float y) {
if (recorder != null) recorder.vertex(x, y);
g.vertex(x, y);
}
public void vertex(float x, float y, float z) {
if (recorder != null) recorder.vertex(x, y, z);
g.vertex(x, y, z);
}
/**
* Used by renderer subclasses or PShape to efficiently pass in already
* formatted vertex information.
* @param v vertex parameters, as a float array of length VERTEX_FIELD_COUNT
*/
public void vertex(float[] v) {
if (recorder != null) recorder.vertex(v);
g.vertex(v);
}
public void vertex(float x, float y, float u, float v) {
if (recorder != null) recorder.vertex(x, y, u, v);
g.vertex(x, y, u, v);
}
/**
* ( begin auto-generated from vertex.xml )
*
* All shapes are constructed by connecting a series of vertices.
* <b>vertex()</b> is used to specify the vertex coordinates for points,
* lines, triangles, quads, and polygons and is used exclusively within the
* <b>beginShape()</b> and <b>endShape()</b> function.<br />
* <br />
* Drawing a vertex in 3D using the <b>z</b> parameter requires the P3D
* parameter in combination with size as shown in the above example.<br />
* <br />
* This function is also used to map a texture onto the geometry. The
* <b>texture()</b> function declares the texture to apply to the geometry
* and the <b>u</b> and <b>v</b> coordinates set define the mapping of this
* texture to the form. By default, the coordinates used for <b>u</b> and
* <b>v</b> are specified in relation to the image's size in pixels, but
* this relation can be changed with <b>textureMode()</b>.
*
* ( end auto-generated )
* @webref shape:vertex
* @param x x-coordinate of the vertex
* @param y y-coordinate of the vertex
* @param z z-coordinate of the vertex
* @param u horizontal coordinate for the texture mapping
* @param v vertical coordinate for the texture mapping
* @see PGraphics#beginShape(int)
* @see PGraphics#endShape(int)
* @see PGraphics#bezierVertex(float, float, float, float, float, float, float, float, float)
* @see PGraphics#quadraticVertex(float, float, float, float, float, float)
* @see PGraphics#curveVertex(float, float, float)
* @see PGraphics#texture(PImage)
*/
public void vertex(float x, float y, float z, float u, float v) {
if (recorder != null) recorder.vertex(x, y, z, u, v);
g.vertex(x, y, z, u, v);
}
/**
* @webref shape:vertex
*/
public void beginContour() {
if (recorder != null) recorder.beginContour();
g.beginContour();
}
/**
* @webref shape:vertex
*/
public void endContour() {
if (recorder != null) recorder.endContour();
g.endContour();
}
public void endShape() {
if (recorder != null) recorder.endShape();
g.endShape();
}
/**
* ( begin auto-generated from endShape.xml )
*
* The <b>endShape()</b> function is the companion to <b>beginShape()</b>
* and may only be called after <b>beginShape()</b>. When <b>endshape()</b>
* is called, all of image data defined since the previous call to
* <b>beginShape()</b> is written into the image buffer. The constant CLOSE
* as the value for the MODE parameter to close the shape (to connect the
* beginning and the end).
*
* ( end auto-generated )
* @webref shape:vertex
* @param mode use CLOSE to close the shape
* @see PGraphics#beginShape(int)
*/
public void endShape(int mode) {
if (recorder != null) recorder.endShape(mode);
g.endShape(mode);
}
/**
* @webref shape
* @param filename name of file to load, can be .svg or .obj
* @see PShape
* @see PApplet#createShape()
*/
public PShape loadShape(String filename) {
return g.loadShape(filename);
}
public PShape loadShape(String filename, String options) {
return g.loadShape(filename, options);
}
/**
* @webref shape
* @see PShape
* @see PShape#endShape()
* @see PApplet#loadShape(String)
*/
public PShape createShape() {
return g.createShape();
}
public PShape createShape(PShape source) {
return g.createShape(source);
}
/**
* @param type either POINTS, LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, QUAD_STRIP
*/
public PShape createShape(int type) {
return g.createShape(type);
}
/**
* @param kind either LINE, TRIANGLE, RECT, ELLIPSE, ARC, SPHERE, BOX
* @param p parameters that match the kind of shape
*/
public PShape createShape(int kind, float... p) {
return g.createShape(kind, p);
}
/**
* ( begin auto-generated from loadShader.xml )
*
* This is a new reference entry for Processing 2.0. It will be updated shortly.
*
* ( end auto-generated )
*
* @webref rendering:shaders
* @param fragFilename name of fragment shader file
*/
public PShader loadShader(String fragFilename) {
return g.loadShader(fragFilename);
}
/**
* @param vertFilename name of vertex shader file
*/
public PShader loadShader(String fragFilename, String vertFilename) {
return g.loadShader(fragFilename, vertFilename);
}
/**
* ( begin auto-generated from shader.xml )
*
* This is a new reference entry for Processing 2.0. It will be updated shortly.
*
* ( end auto-generated )
*
* @webref rendering:shaders
* @param shader name of shader file
*/
public void shader(PShader shader) {
if (recorder != null) recorder.shader(shader);
g.shader(shader);
}
/**
* @param kind type of shader, either POINTS, LINES, or TRIANGLES
*/
public void shader(PShader shader, int kind) {
if (recorder != null) recorder.shader(shader, kind);
g.shader(shader, kind);
}
/**
* ( begin auto-generated from resetShader.xml )
*
* This is a new reference entry for Processing 2.0. It will be updated shortly.
*
* ( end auto-generated )
*
* @webref rendering:shaders
*/
public void resetShader() {
if (recorder != null) recorder.resetShader();
g.resetShader();
}
/**
* @param kind type of shader, either POINTS, LINES, or TRIANGLES
*/
public void resetShader(int kind) {
if (recorder != null) recorder.resetShader(kind);
g.resetShader(kind);
}
/**
* @param shader the fragment shader to apply
*/
public void filter(PShader shader) {
if (recorder != null) recorder.filter(shader);
g.filter(shader);
}
/*
* @webref rendering:shaders
* @param a x-coordinate of the rectangle by default
* @param b y-coordinate of the rectangle by default
* @param c width of the rectangle by default
* @param d height of the rectangle by default
*/
public void clip(float a, float b, float c, float d) {
if (recorder != null) recorder.clip(a, b, c, d);
g.clip(a, b, c, d);
}
/*
* @webref rendering:shaders
*/
public void noClip() {
if (recorder != null) recorder.noClip();
g.noClip();
}
/**
* ( begin auto-generated from blendMode.xml )
*
* This is a new reference entry for Processing 2.0. It will be updated shortly.
*
* ( end auto-generated )
*
* @webref Rendering
* @param mode the blending mode to use
*/
public void blendMode(int mode) {
if (recorder != null) recorder.blendMode(mode);
g.blendMode(mode);
}
public void bezierVertex(float x2, float y2,
float x3, float y3,
float x4, float y4) {
if (recorder != null) recorder.bezierVertex(x2, y2, x3, y3, x4, y4);
g.bezierVertex(x2, y2, x3, y3, x4, y4);
}
/**
* ( begin auto-generated from bezierVertex.xml )
*
* Specifies vertex coordinates for Bezier curves. Each call to
* <b>bezierVertex()</b> defines the position of two control points and one
* anchor point of a Bezier curve, adding a new segment to a line or shape.
* The first time <b>bezierVertex()</b> is used within a
* <b>beginShape()</b> call, it must be prefaced with a call to
* <b>vertex()</b> to set the first anchor point. This function must be
* used between <b>beginShape()</b> and <b>endShape()</b> and only when
* there is no MODE parameter specified to <b>beginShape()</b>. Using the
* 3D version requires rendering with P3D (see the Environment reference
* for more information).
*
* ( end auto-generated )
* @webref shape:vertex
* @param x2 the x-coordinate of the 1st control point
* @param y2 the y-coordinate of the 1st control point
* @param z2 the z-coordinate of the 1st control point
* @param x3 the x-coordinate of the 2nd control point
* @param y3 the y-coordinate of the 2nd control point
* @param z3 the z-coordinate of the 2nd control point
* @param x4 the x-coordinate of the anchor point
* @param y4 the y-coordinate of the anchor point
* @param z4 the z-coordinate of the anchor point
* @see PGraphics#curveVertex(float, float, float)
* @see PGraphics#vertex(float, float, float, float, float)
* @see PGraphics#quadraticVertex(float, float, float, float, float, float)
* @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
*/
public void bezierVertex(float x2, float y2, float z2,
float x3, float y3, float z3,
float x4, float y4, float z4) {
if (recorder != null) recorder.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4);
g.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4);
}
/**
* @webref shape:vertex
* @param cx the x-coordinate of the control point
* @param cy the y-coordinate of the control point
* @param x3 the x-coordinate of the anchor point
* @param y3 the y-coordinate of the anchor point
* @see PGraphics#curveVertex(float, float, float)
* @see PGraphics#vertex(float, float, float, float, float)
* @see PGraphics#bezierVertex(float, float, float, float, float, float)
* @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
*/
public void quadraticVertex(float cx, float cy,
float x3, float y3) {
if (recorder != null) recorder.quadraticVertex(cx, cy, x3, y3);
g.quadraticVertex(cx, cy, x3, y3);
}
/**
* @param cz the z-coordinate of the control point
* @param z3 the z-coordinate of the anchor point
*/
public void quadraticVertex(float cx, float cy, float cz,
float x3, float y3, float z3) {
if (recorder != null) recorder.quadraticVertex(cx, cy, cz, x3, y3, z3);
g.quadraticVertex(cx, cy, cz, x3, y3, z3);
}
/**
* ( begin auto-generated from curveVertex.xml )
*
* Specifies vertex coordinates for curves. This function may only be used
* between <b>beginShape()</b> and <b>endShape()</b> and only when there is
* no MODE parameter specified to <b>beginShape()</b>. The first and last
* points in a series of <b>curveVertex()</b> lines will be used to guide
* the beginning and end of a the curve. A minimum of four points is
* required to draw a tiny curve between the second and third points.
* Adding a fifth point with <b>curveVertex()</b> will draw the curve
* between the second, third, and fourth points. The <b>curveVertex()</b>
* function is an implementation of Catmull-Rom splines. Using the 3D
* version requires rendering with P3D (see the Environment reference for
* more information).
*
* ( end auto-generated )
*
* @webref shape:vertex
* @param x the x-coordinate of the vertex
* @param y the y-coordinate of the vertex
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#beginShape(int)
* @see PGraphics#endShape(int)
* @see PGraphics#vertex(float, float, float, float, float)
* @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#quadraticVertex(float, float, float, float, float, float)
*/
public void curveVertex(float x, float y) {
if (recorder != null) recorder.curveVertex(x, y);
g.curveVertex(x, y);
}
/**
* @param z the z-coordinate of the vertex
*/
public void curveVertex(float x, float y, float z) {
if (recorder != null) recorder.curveVertex(x, y, z);
g.curveVertex(x, y, z);
}
/**
* ( begin auto-generated from point.xml )
*
* Draws a point, a coordinate in space at the dimension of one pixel. The
* first parameter is the horizontal value for the point, the second value
* is the vertical value for the point, and the optional third value is the
* depth value. Drawing this shape in 3D with the <b>z</b> parameter
* requires the P3D parameter in combination with <b>size()</b> as shown in
* the above example.
*
* ( end auto-generated )
*
* @webref shape:2d_primitives
* @param x x-coordinate of the point
* @param y y-coordinate of the point
*/
public void point(float x, float y) {
if (recorder != null) recorder.point(x, y);
g.point(x, y);
}
/**
* @param z z-coordinate of the point
*/
public void point(float x, float y, float z) {
if (recorder != null) recorder.point(x, y, z);
g.point(x, y, z);
}
/**
* ( begin auto-generated from line.xml )
*
* Draws a line (a direct path between two points) to the screen. The
* version of <b>line()</b> with four parameters draws the line in 2D. To
* color a line, use the <b>stroke()</b> function. A line cannot be filled,
* therefore the <b>fill()</b> function will not affect the color of a
* line. 2D lines are drawn with a width of one pixel by default, but this
* can be changed with the <b>strokeWeight()</b> function. The version with
* six parameters allows the line to be placed anywhere within XYZ space.
* Drawing this shape in 3D with the <b>z</b> parameter requires the P3D
* parameter in combination with <b>size()</b> as shown in the above example.
*
* ( end auto-generated )
* @webref shape:2d_primitives
* @param x1 x-coordinate of the first point
* @param y1 y-coordinate of the first point
* @param x2 x-coordinate of the second point
* @param y2 y-coordinate of the second point
* @see PGraphics#strokeWeight(float)
* @see PGraphics#strokeJoin(int)
* @see PGraphics#strokeCap(int)
* @see PGraphics#beginShape()
*/
public void line(float x1, float y1, float x2, float y2) {
if (recorder != null) recorder.line(x1, y1, x2, y2);
g.line(x1, y1, x2, y2);
}
/**
* @param z1 z-coordinate of the first point
* @param z2 z-coordinate of the second point
*/
public void line(float x1, float y1, float z1,
float x2, float y2, float z2) {
if (recorder != null) recorder.line(x1, y1, z1, x2, y2, z2);
g.line(x1, y1, z1, x2, y2, z2);
}
/**
* ( begin auto-generated from triangle.xml )
*
* A triangle is a plane created by connecting three points. The first two
* arguments specify the first point, the middle two arguments specify the
* second point, and the last two arguments specify the third point.
*
* ( end auto-generated )
* @webref shape:2d_primitives
* @param x1 x-coordinate of the first point
* @param y1 y-coordinate of the first point
* @param x2 x-coordinate of the second point
* @param y2 y-coordinate of the second point
* @param x3 x-coordinate of the third point
* @param y3 y-coordinate of the third point
* @see PApplet#beginShape()
*/
public void triangle(float x1, float y1, float x2, float y2,
float x3, float y3) {
if (recorder != null) recorder.triangle(x1, y1, x2, y2, x3, y3);
g.triangle(x1, y1, x2, y2, x3, y3);
}
/**
* ( begin auto-generated from quad.xml )
*
* A quad is a quadrilateral, a four sided polygon. It is similar to a
* rectangle, but the angles between its edges are not constrained to
* ninety degrees. The first pair of parameters (x1,y1) sets the first
* vertex and the subsequent pairs should proceed clockwise or
* counter-clockwise around the defined shape.
*
* ( end auto-generated )
* @webref shape:2d_primitives
* @param x1 x-coordinate of the first corner
* @param y1 y-coordinate of the first corner
* @param x2 x-coordinate of the second corner
* @param y2 y-coordinate of the second corner
* @param x3 x-coordinate of the third corner
* @param y3 y-coordinate of the third corner
* @param x4 x-coordinate of the fourth corner
* @param y4 y-coordinate of the fourth corner
*/
public void quad(float x1, float y1, float x2, float y2,
float x3, float y3, float x4, float y4) {
if (recorder != null) recorder.quad(x1, y1, x2, y2, x3, y3, x4, y4);
g.quad(x1, y1, x2, y2, x3, y3, x4, y4);
}
/**
* ( begin auto-generated from rectMode.xml )
*
* Modifies the location from which rectangles draw. The default mode is
* <b>rectMode(CORNER)</b>, which specifies the location to be the upper
* left corner of the shape and uses the third and fourth parameters of
* <b>rect()</b> to specify the width and height. The syntax
* <b>rectMode(CORNERS)</b> uses the first and second parameters of
* <b>rect()</b> to set the location of one corner and uses the third and
* fourth parameters to set the opposite corner. The syntax
* <b>rectMode(CENTER)</b> draws the image from its center point and uses
* the third and forth parameters of <b>rect()</b> to specify the image's
* width and height. The syntax <b>rectMode(RADIUS)</b> draws the image
* from its center point and uses the third and forth parameters of
* <b>rect()</b> to specify half of the image's width and height. The
* parameter must be written in ALL CAPS because Processing is a case
* sensitive language. Note: In version 125, the mode named CENTER_RADIUS
* was shortened to RADIUS.
*
* ( end auto-generated )
* @webref shape:attributes
* @param mode either CORNER, CORNERS, CENTER, or RADIUS
* @see PGraphics#rect(float, float, float, float)
*/
public void rectMode(int mode) {
if (recorder != null) recorder.rectMode(mode);
g.rectMode(mode);
}
/**
* ( begin auto-generated from rect.xml )
*
* Draws a rectangle to the screen. A rectangle is a four-sided shape with
* every angle at ninety degrees. By default, the first two parameters set
* the location of the upper-left corner, the third sets the width, and the
* fourth sets the height. These parameters may be changed with the
* <b>rectMode()</b> function.
*
* ( end auto-generated )
*
* @webref shape:2d_primitives
* @param a x-coordinate of the rectangle by default
* @param b y-coordinate of the rectangle by default
* @param c width of the rectangle by default
* @param d height of the rectangle by default
* @see PGraphics#rectMode(int)
* @see PGraphics#quad(float, float, float, float, float, float, float, float)
*/
public void rect(float a, float b, float c, float d) {
if (recorder != null) recorder.rect(a, b, c, d);
g.rect(a, b, c, d);
}
/**
* @param r radii for all four corners
*/
public void rect(float a, float b, float c, float d, float r) {
if (recorder != null) recorder.rect(a, b, c, d, r);
g.rect(a, b, c, d, r);
}
/**
* @param tl radius for top-left corner
* @param tr radius for top-right corner
* @param br radius for bottom-right corner
* @param bl radius for bottom-left corner
*/
public void rect(float a, float b, float c, float d,
float tl, float tr, float br, float bl) {
if (recorder != null) recorder.rect(a, b, c, d, tl, tr, br, bl);
g.rect(a, b, c, d, tl, tr, br, bl);
}
/**
* ( begin auto-generated from ellipseMode.xml )
*
* The origin of the ellipse is modified by the <b>ellipseMode()</b>
* function. The default configuration is <b>ellipseMode(CENTER)</b>, which
* specifies the location of the ellipse as the center of the shape. The
* <b>RADIUS</b> mode is the same, but the width and height parameters to
* <b>ellipse()</b> specify the radius of the ellipse, rather than the
* diameter. The <b>CORNER</b> mode draws the shape from the upper-left
* corner of its bounding box. The <b>CORNERS</b> mode uses the four
* parameters to <b>ellipse()</b> to set two opposing corners of the
* ellipse's bounding box. The parameter must be written in ALL CAPS
* because Processing is a case-sensitive language.
*
* ( end auto-generated )
* @webref shape:attributes
* @param mode either CENTER, RADIUS, CORNER, or CORNERS
* @see PApplet#ellipse(float, float, float, float)
* @see PApplet#arc(float, float, float, float, float, float)
*/
public void ellipseMode(int mode) {
if (recorder != null) recorder.ellipseMode(mode);
g.ellipseMode(mode);
}
/**
* ( begin auto-generated from ellipse.xml )
*
* Draws an ellipse (oval) in the display window. An ellipse with an equal
* <b>width</b> and <b>height</b> is a circle. The first two parameters set
* the location, the third sets the width, and the fourth sets the height.
* The origin may be changed with the <b>ellipseMode()</b> function.
*
* ( end auto-generated )
* @webref shape:2d_primitives
* @param a x-coordinate of the ellipse
* @param b y-coordinate of the ellipse
* @param c width of the ellipse by default
* @param d height of the ellipse by default
* @see PApplet#ellipseMode(int)
* @see PApplet#arc(float, float, float, float, float, float)
*/
public void ellipse(float a, float b, float c, float d) {
if (recorder != null) recorder.ellipse(a, b, c, d);
g.ellipse(a, b, c, d);
}
/**
* ( begin auto-generated from arc.xml )
*
* Draws an arc in the display window. Arcs are drawn along the outer edge
* of an ellipse defined by the <b>x</b>, <b>y</b>, <b>width</b> and
* <b>height</b> parameters. The origin or the arc's ellipse may be changed
* with the <b>ellipseMode()</b> function. The <b>start</b> and <b>stop</b>
* parameters specify the angles at which to draw the arc.
*
* ( end auto-generated )
* @webref shape:2d_primitives
* @param a x-coordinate of the arc's ellipse
* @param b y-coordinate of the arc's ellipse
* @param c width of the arc's ellipse by default
* @param d height of the arc's ellipse by default
* @param start angle to start the arc, specified in radians
* @param stop angle to stop the arc, specified in radians
* @see PApplet#ellipse(float, float, float, float)
* @see PApplet#ellipseMode(int)
* @see PApplet#radians(float)
* @see PApplet#degrees(float)
*/
public void arc(float a, float b, float c, float d,
float start, float stop) {
if (recorder != null) recorder.arc(a, b, c, d, start, stop);
g.arc(a, b, c, d, start, stop);
}
/*
* @param mode either OPEN, CHORD, or PIE
*/
public void arc(float a, float b, float c, float d,
float start, float stop, int mode) {
if (recorder != null) recorder.arc(a, b, c, d, start, stop, mode);
g.arc(a, b, c, d, start, stop, mode);
}
/**
* ( begin auto-generated from box.xml )
*
* A box is an extruded rectangle. A box with equal dimension on all sides
* is a cube.
*
* ( end auto-generated )
*
* @webref shape:3d_primitives
* @param size dimension of the box in all dimensions (creates a cube)
* @see PGraphics#sphere(float)
*/
public void box(float size) {
if (recorder != null) recorder.box(size);
g.box(size);
}
/**
* @param w dimension of the box in the x-dimension
* @param h dimension of the box in the y-dimension
* @param d dimension of the box in the z-dimension
*/
public void box(float w, float h, float d) {
if (recorder != null) recorder.box(w, h, d);
g.box(w, h, d);
}
/**
* ( begin auto-generated from sphereDetail.xml )
*
* Controls the detail used to render a sphere by adjusting the number of
* vertices of the sphere mesh. The default resolution is 30, which creates
* a fairly detailed sphere definition with vertices every 360/30 = 12
* degrees. If you're going to render a great number of spheres per frame,
* it is advised to reduce the level of detail using this function. The
* setting stays active until <b>sphereDetail()</b> is called again with a
* new parameter and so should <i>not</i> be called prior to every
* <b>sphere()</b> statement, unless you wish to render spheres with
* different settings, e.g. using less detail for smaller spheres or ones
* further away from the camera. To control the detail of the horizontal
* and vertical resolution independently, use the version of the functions
* with two parameters.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Code for sphereDetail() submitted by toxi [031031].
* Code for enhanced u/v version from davbol [080801].
*
* @param res number of segments (minimum 3) used per full circle revolution
* @webref shape:3d_primitives
* @see PGraphics#sphere(float)
*/
public void sphereDetail(int res) {
if (recorder != null) recorder.sphereDetail(res);
g.sphereDetail(res);
}
/**
* @param ures number of segments used longitudinally per full circle revolutoin
* @param vres number of segments used latitudinally from top to bottom
*/
public void sphereDetail(int ures, int vres) {
if (recorder != null) recorder.sphereDetail(ures, vres);
g.sphereDetail(ures, vres);
}
/**
* ( begin auto-generated from sphere.xml )
*
* A sphere is a hollow ball made from tessellated triangles.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* <P>
* Implementation notes:
* <P>
* cache all the points of the sphere in a static array
* top and bottom are just a bunch of triangles that land
* in the center point
* <P>
* sphere is a series of concentric circles who radii vary
* along the shape, based on, er.. cos or something
* <PRE>
* [toxi 031031] new sphere code. removed all multiplies with
* radius, as scale() will take care of that anyway
*
* [toxi 031223] updated sphere code (removed modulos)
* and introduced sphereAt(x,y,z,r)
* to avoid additional translate()'s on the user/sketch side
*
* [davbol 080801] now using separate sphereDetailU/V
* </PRE>
*
* @webref shape:3d_primitives
* @param r the radius of the sphere
* @see PGraphics#sphereDetail(int)
*/
public void sphere(float r) {
if (recorder != null) recorder.sphere(r);
g.sphere(r);
}
/**
* ( begin auto-generated from bezierPoint.xml )
*
* Evaluates the Bezier at point t for points a, b, c, d. The parameter t
* varies between 0 and 1, a and d are points on the curve, and b and c are
* the control points. This can be done once with the x coordinates and a
* second time with the y coordinates to get the location of a bezier curve
* at t.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* For instance, to convert the following example:<PRE>
* stroke(255, 102, 0);
* line(85, 20, 10, 10);
* line(90, 90, 15, 80);
* stroke(0, 0, 0);
* bezier(85, 20, 10, 10, 90, 90, 15, 80);
*
* // draw it in gray, using 10 steps instead of the default 20
* // this is a slower way to do it, but useful if you need
* // to do things with the coordinates at each step
* stroke(128);
* beginShape(LINE_STRIP);
* for (int i = 0; i <= 10; i++) {
* float t = i / 10.0f;
* float x = bezierPoint(85, 10, 90, 15, t);
* float y = bezierPoint(20, 10, 90, 80, t);
* vertex(x, y);
* }
* endShape();</PRE>
*
* @webref shape:curves
* @param a coordinate of first point on the curve
* @param b coordinate of first control point
* @param c coordinate of second control point
* @param d coordinate of second point on the curve
* @param t value between 0 and 1
* @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#bezierVertex(float, float, float, float, float, float)
* @see PGraphics#curvePoint(float, float, float, float, float)
*/
public float bezierPoint(float a, float b, float c, float d, float t) {
return g.bezierPoint(a, b, c, d, t);
}
/**
* ( begin auto-generated from bezierTangent.xml )
*
* Calculates the tangent of a point on a Bezier curve. There is a good
* definition of <a href="http://en.wikipedia.org/wiki/Tangent"
* target="new"><em>tangent</em> on Wikipedia</a>.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Code submitted by Dave Bollinger (davol) for release 0136.
*
* @webref shape:curves
* @param a coordinate of first point on the curve
* @param b coordinate of first control point
* @param c coordinate of second control point
* @param d coordinate of second point on the curve
* @param t value between 0 and 1
* @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#bezierVertex(float, float, float, float, float, float)
* @see PGraphics#curvePoint(float, float, float, float, float)
*/
public float bezierTangent(float a, float b, float c, float d, float t) {
return g.bezierTangent(a, b, c, d, t);
}
/**
* ( begin auto-generated from bezierDetail.xml )
*
* Sets the resolution at which Beziers display. The default value is 20.
* This function is only useful when using the P3D renderer as the default
* P2D renderer does not use this information.
*
* ( end auto-generated )
*
* @webref shape:curves
* @param detail resolution of the curves
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#curveVertex(float, float, float)
* @see PGraphics#curveTightness(float)
*/
public void bezierDetail(int detail) {
if (recorder != null) recorder.bezierDetail(detail);
g.bezierDetail(detail);
}
public void bezier(float x1, float y1,
float x2, float y2,
float x3, float y3,
float x4, float y4) {
if (recorder != null) recorder.bezier(x1, y1, x2, y2, x3, y3, x4, y4);
g.bezier(x1, y1, x2, y2, x3, y3, x4, y4);
}
/**
* ( begin auto-generated from bezier.xml )
*
* Draws a Bezier curve on the screen. These curves are defined by a series
* of anchor and control points. The first two parameters specify the first
* anchor point and the last two parameters specify the other anchor point.
* The middle parameters specify the control points which define the shape
* of the curve. Bezier curves were developed by French engineer Pierre
* Bezier. Using the 3D version requires rendering with P3D (see the
* Environment reference for more information).
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Draw a cubic bezier curve. The first and last points are
* the on-curve points. The middle two are the 'control' points,
* or 'handles' in an application like Illustrator.
* <P>
* Identical to typing:
* <PRE>beginShape();
* vertex(x1, y1);
* bezierVertex(x2, y2, x3, y3, x4, y4);
* endShape();
* </PRE>
* In Postscript-speak, this would be:
* <PRE>moveto(x1, y1);
* curveto(x2, y2, x3, y3, x4, y4);</PRE>
* If you were to try and continue that curve like so:
* <PRE>curveto(x5, y5, x6, y6, x7, y7);</PRE>
* This would be done in processing by adding these statements:
* <PRE>bezierVertex(x5, y5, x6, y6, x7, y7)
* </PRE>
* To draw a quadratic (instead of cubic) curve,
* use the control point twice by doubling it:
* <PRE>bezier(x1, y1, cx, cy, cx, cy, x2, y2);</PRE>
*
* @webref shape:curves
* @param x1 coordinates for the first anchor point
* @param y1 coordinates for the first anchor point
* @param z1 coordinates for the first anchor point
* @param x2 coordinates for the first control point
* @param y2 coordinates for the first control point
* @param z2 coordinates for the first control point
* @param x3 coordinates for the second control point
* @param y3 coordinates for the second control point
* @param z3 coordinates for the second control point
* @param x4 coordinates for the second anchor point
* @param y4 coordinates for the second anchor point
* @param z4 coordinates for the second anchor point
*
* @see PGraphics#bezierVertex(float, float, float, float, float, float)
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
*/
public void bezier(float x1, float y1, float z1,
float x2, float y2, float z2,
float x3, float y3, float z3,
float x4, float y4, float z4) {
if (recorder != null) recorder.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
g.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
}
/**
* ( begin auto-generated from curvePoint.xml )
*
* Evalutes the curve at point t for points a, b, c, d. The parameter t
* varies between 0 and 1, a and d are points on the curve, and b and c are
* the control points. This can be done once with the x coordinates and a
* second time with the y coordinates to get the location of a curve at t.
*
* ( end auto-generated )
*
* @webref shape:curves
* @param a coordinate of first point on the curve
* @param b coordinate of second point on the curve
* @param c coordinate of third point on the curve
* @param d coordinate of fourth point on the curve
* @param t value between 0 and 1
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#curveVertex(float, float)
* @see PGraphics#bezierPoint(float, float, float, float, float)
*/
public float curvePoint(float a, float b, float c, float d, float t) {
return g.curvePoint(a, b, c, d, t);
}
/**
* ( begin auto-generated from curveTangent.xml )
*
* Calculates the tangent of a point on a curve. There's a good definition
* of <em><a href="http://en.wikipedia.org/wiki/Tangent"
* target="new">tangent</em> on Wikipedia</a>.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Code thanks to Dave Bollinger (Bug #715)
*
* @webref shape:curves
* @param a coordinate of first point on the curve
* @param b coordinate of first control point
* @param c coordinate of second control point
* @param d coordinate of second point on the curve
* @param t value between 0 and 1
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#curveVertex(float, float)
* @see PGraphics#curvePoint(float, float, float, float, float)
* @see PGraphics#bezierTangent(float, float, float, float, float)
*/
public float curveTangent(float a, float b, float c, float d, float t) {
return g.curveTangent(a, b, c, d, t);
}
/**
* ( begin auto-generated from curveDetail.xml )
*
* Sets the resolution at which curves display. The default value is 20.
* This function is only useful when using the P3D renderer as the default
* P2D renderer does not use this information.
*
* ( end auto-generated )
*
* @webref shape:curves
* @param detail resolution of the curves
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#curveVertex(float, float)
* @see PGraphics#curveTightness(float)
*/
public void curveDetail(int detail) {
if (recorder != null) recorder.curveDetail(detail);
g.curveDetail(detail);
}
/**
* ( begin auto-generated from curveTightness.xml )
*
* Modifies the quality of forms created with <b>curve()</b> and
* <b>curveVertex()</b>. The parameter <b>squishy</b> determines how the
* curve fits to the vertex points. The value 0.0 is the default value for
* <b>squishy</b> (this value defines the curves to be Catmull-Rom splines)
* and the value 1.0 connects all the points with straight lines. Values
* within the range -5.0 and 5.0 will deform the curves but will leave them
* recognizable and as values increase in magnitude, they will continue to deform.
*
* ( end auto-generated )
*
* @webref shape:curves
* @param tightness amount of deformation from the original vertices
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#curveVertex(float, float)
*/
public void curveTightness(float tightness) {
if (recorder != null) recorder.curveTightness(tightness);
g.curveTightness(tightness);
}
/**
* ( begin auto-generated from curve.xml )
*
* Draws a curved line on the screen. The first and second parameters
* specify the beginning control point and the last two parameters specify
* the ending control point. The middle parameters specify the start and
* stop of the curve. Longer curves can be created by putting a series of
* <b>curve()</b> functions together or using <b>curveVertex()</b>. An
* additional function called <b>curveTightness()</b> provides control for
* the visual quality of the curve. The <b>curve()</b> function is an
* implementation of Catmull-Rom splines. Using the 3D version requires
* rendering with P3D (see the Environment reference for more information).
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* As of revision 0070, this function no longer doubles the first
* and last points. The curves are a bit more boring, but it's more
* mathematically correct, and properly mirrored in curvePoint().
* <P>
* Identical to typing out:<PRE>
* beginShape();
* curveVertex(x1, y1);
* curveVertex(x2, y2);
* curveVertex(x3, y3);
* curveVertex(x4, y4);
* endShape();
* </PRE>
*
* @webref shape:curves
* @param x1 coordinates for the beginning control point
* @param y1 coordinates for the beginning control point
* @param x2 coordinates for the first point
* @param y2 coordinates for the first point
* @param x3 coordinates for the second point
* @param y3 coordinates for the second point
* @param x4 coordinates for the ending control point
* @param y4 coordinates for the ending control point
* @see PGraphics#curveVertex(float, float)
* @see PGraphics#curveTightness(float)
* @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
*/
public void curve(float x1, float y1,
float x2, float y2,
float x3, float y3,
float x4, float y4) {
if (recorder != null) recorder.curve(x1, y1, x2, y2, x3, y3, x4, y4);
g.curve(x1, y1, x2, y2, x3, y3, x4, y4);
}
/**
* @param z1 coordinates for the beginning control point
* @param z2 coordinates for the first point
* @param z3 coordinates for the second point
* @param z4 coordinates for the ending control point
*/
public void curve(float x1, float y1, float z1,
float x2, float y2, float z2,
float x3, float y3, float z3,
float x4, float y4, float z4) {
if (recorder != null) recorder.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
g.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
}
/**
* ( begin auto-generated from smooth.xml )
*
* Draws all geometry with smooth (anti-aliased) edges. This will sometimes
* slow down the frame rate of the application, but will enhance the visual
* refinement. Note that <b>smooth()</b> will also improve image quality of
* resized images, and <b>noSmooth()</b> will disable image (and font)
* smoothing altogether.
*
* ( end auto-generated )
*
* @webref shape:attributes
* @see PGraphics#noSmooth()
* @see PGraphics#hint(int)
* @see PApplet#size(int, int, String)
*/
public void smooth() {
if (recorder != null) recorder.smooth();
g.smooth();
}
/**
*
* @param level either 2, 4, or 8
*/
public void smooth(int level) {
if (recorder != null) recorder.smooth(level);
g.smooth(level);
}
/**
* ( begin auto-generated from noSmooth.xml )
*
* Draws all geometry with jagged (aliased) edges.
*
* ( end auto-generated )
* @webref shape:attributes
* @see PGraphics#smooth()
*/
public void noSmooth() {
if (recorder != null) recorder.noSmooth();
g.noSmooth();
}
/**
* ( begin auto-generated from imageMode.xml )
*
* Modifies the location from which images draw. The default mode is
* <b>imageMode(CORNER)</b>, which specifies the location to be the upper
* left corner and uses the fourth and fifth parameters of <b>image()</b>
* to set the image's width and height. The syntax
* <b>imageMode(CORNERS)</b> uses the second and third parameters of
* <b>image()</b> to set the location of one corner of the image and uses
* the fourth and fifth parameters to set the opposite corner. Use
* <b>imageMode(CENTER)</b> to draw images centered at the given x and y
* position.<br />
* <br />
* The parameter to <b>imageMode()</b> must be written in ALL CAPS because
* Processing is a case-sensitive language.
*
* ( end auto-generated )
*
* @webref image:loading_displaying
* @param mode either CORNER, CORNERS, or CENTER
* @see PApplet#loadImage(String, String)
* @see PImage
* @see PGraphics#image(PImage, float, float, float, float)
* @see PGraphics#background(float, float, float, float)
*/
public void imageMode(int mode) {
if (recorder != null) recorder.imageMode(mode);
g.imageMode(mode);
}
/**
* ( begin auto-generated from image.xml )
*
* Displays images to the screen. The images must be in the sketch's "data"
* directory to load correctly. Select "Add file..." from the "Sketch" menu
* to add the image. Processing currently works with GIF, JPEG, and Targa
* images. The <b>img</b> parameter specifies the image to display and the
* <b>x</b> and <b>y</b> parameters define the location of the image from
* its upper-left corner. The image is displayed at its original size
* unless the <b>width</b> and <b>height</b> parameters specify a different
* size.<br />
* <br />
* The <b>imageMode()</b> function changes the way the parameters work. For
* example, a call to <b>imageMode(CORNERS)</b> will change the
* <b>width</b> and <b>height</b> parameters to define the x and y values
* of the opposite corner of the image.<br />
* <br />
* The color of an image may be modified with the <b>tint()</b> function.
* This function will maintain transparency for GIF and PNG images.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Starting with release 0124, when using the default (JAVA2D) renderer,
* smooth() will also improve image quality of resized images.
*
* @webref image:loading_displaying
* @param img the image to display
* @param a x-coordinate of the image
* @param b y-coordinate of the image
* @see PApplet#loadImage(String, String)
* @see PImage
* @see PGraphics#imageMode(int)
* @see PGraphics#tint(float)
* @see PGraphics#background(float, float, float, float)
* @see PGraphics#alpha(int)
*/
public void image(PImage img, float a, float b) {
if (recorder != null) recorder.image(img, a, b);
g.image(img, a, b);
}
/**
* @param c width to display the image
* @param d height to display the image
*/
public void image(PImage img, float a, float b, float c, float d) {
if (recorder != null) recorder.image(img, a, b, c, d);
g.image(img, a, b, c, d);
}
/**
* Draw an image(), also specifying u/v coordinates.
* In this method, the u, v coordinates are always based on image space
* location, regardless of the current textureMode().
*
* @nowebref
*/
public void image(PImage img,
float a, float b, float c, float d,
int u1, int v1, int u2, int v2) {
if (recorder != null) recorder.image(img, a, b, c, d, u1, v1, u2, v2);
g.image(img, a, b, c, d, u1, v1, u2, v2);
}
/**
* ( begin auto-generated from shapeMode.xml )
*
* Modifies the location from which shapes draw. The default mode is
* <b>shapeMode(CORNER)</b>, which specifies the location to be the upper
* left corner of the shape and uses the third and fourth parameters of
* <b>shape()</b> to specify the width and height. The syntax
* <b>shapeMode(CORNERS)</b> uses the first and second parameters of
* <b>shape()</b> to set the location of one corner and uses the third and
* fourth parameters to set the opposite corner. The syntax
* <b>shapeMode(CENTER)</b> draws the shape from its center point and uses
* the third and forth parameters of <b>shape()</b> to specify the width
* and height. The parameter must be written in "ALL CAPS" because
* Processing is a case sensitive language.
*
* ( end auto-generated )
*
* @webref shape:loading_displaying
* @param mode either CORNER, CORNERS, CENTER
* @see PGraphics#shape(PShape)
* @see PGraphics#rectMode(int)
*/
public void shapeMode(int mode) {
if (recorder != null) recorder.shapeMode(mode);
g.shapeMode(mode);
}
public void shape(PShape shape) {
if (recorder != null) recorder.shape(shape);
g.shape(shape);
}
/**
* ( begin auto-generated from shape.xml )
*
* Displays shapes to the screen. The shapes must be in the sketch's "data"
* directory to load correctly. Select "Add file..." from the "Sketch" menu
* to add the shape. Processing currently works with SVG shapes only. The
* <b>sh</b> parameter specifies the shape to display and the <b>x</b> and
* <b>y</b> parameters define the location of the shape from its upper-left
* corner. The shape is displayed at its original size unless the
* <b>width</b> and <b>height</b> parameters specify a different size. The
* <b>shapeMode()</b> function changes the way the parameters work. A call
* to <b>shapeMode(CORNERS)</b>, for example, will change the width and
* height parameters to define the x and y values of the opposite corner of
* the shape.
* <br /><br />
* Note complex shapes may draw awkwardly with P3D. This renderer does not
* yet support shapes that have holes or complicated breaks.
*
* ( end auto-generated )
*
* @webref shape:loading_displaying
* @param shape the shape to display
* @param x x-coordinate of the shape
* @param y y-coordinate of the shape
* @see PShape
* @see PApplet#loadShape(String)
* @see PGraphics#shapeMode(int)
*
* Convenience method to draw at a particular location.
*/
public void shape(PShape shape, float x, float y) {
if (recorder != null) recorder.shape(shape, x, y);
g.shape(shape, x, y);
}
/**
* @param a x-coordinate of the shape
* @param b y-coordinate of the shape
* @param c width to display the shape
* @param d height to display the shape
*/
public void shape(PShape shape, float a, float b, float c, float d) {
if (recorder != null) recorder.shape(shape, a, b, c, d);
g.shape(shape, a, b, c, d);
}
public void textAlign(int alignX) {
if (recorder != null) recorder.textAlign(alignX);
g.textAlign(alignX);
}
/**
* ( begin auto-generated from textAlign.xml )
*
* Sets the current alignment for drawing text. The parameters LEFT,
* CENTER, and RIGHT set the display characteristics of the letters in
* relation to the values for the <b>x</b> and <b>y</b> parameters of the
* <b>text()</b> function.
* <br/> <br/>
* In Processing 0125 and later, an optional second parameter can be used
* to vertically align the text. BASELINE is the default, and the vertical
* alignment will be reset to BASELINE if the second parameter is not used.
* The TOP and CENTER parameters are straightforward. The BOTTOM parameter
* offsets the line based on the current <b>textDescent()</b>. For multiple
* lines, the final line will be aligned to the bottom, with the previous
* lines appearing above it.
* <br/> <br/>
* When using <b>text()</b> with width and height parameters, BASELINE is
* ignored, and treated as TOP. (Otherwise, text would by default draw
* outside the box, since BASELINE is the default setting. BASELINE is not
* a useful drawing mode for text drawn in a rectangle.)
* <br/> <br/>
* The vertical alignment is based on the value of <b>textAscent()</b>,
* which many fonts do not specify correctly. It may be necessary to use a
* hack and offset by a few pixels by hand so that the offset looks
* correct. To do this as less of a hack, use some percentage of
* <b>textAscent()</b> or <b>textDescent()</b> so that the hack works even
* if you change the size of the font.
*
* ( end auto-generated )
*
* @webref typography:attributes
* @param alignX horizontal alignment, either LEFT, CENTER, or RIGHT
* @param alignY vertical alignment, either TOP, BOTTOM, CENTER, or BASELINE
* @see PApplet#loadFont(String)
* @see PFont
* @see PGraphics#text(String, float, float)
*/
public void textAlign(int alignX, int alignY) {
if (recorder != null) recorder.textAlign(alignX, alignY);
g.textAlign(alignX, alignY);
}
/**
* ( begin auto-generated from textAscent.xml )
*
* Returns ascent of the current font at its current size. This information
* is useful for determining the height of the font above the baseline. For
* example, adding the <b>textAscent()</b> and <b>textDescent()</b> values
* will give you the total height of the line.
*
* ( end auto-generated )
*
* @webref typography:metrics
* @see PGraphics#textDescent()
*/
public float textAscent() {
return g.textAscent();
}
/**
* ( begin auto-generated from textDescent.xml )
*
* Returns descent of the current font at its current size. This
* information is useful for determining the height of the font below the
* baseline. For example, adding the <b>textAscent()</b> and
* <b>textDescent()</b> values will give you the total height of the line.
*
* ( end auto-generated )
*
* @webref typography:metrics
* @see PGraphics#textAscent()
*/
public float textDescent() {
return g.textDescent();
}
/**
* ( begin auto-generated from textFont.xml )
*
* Sets the current font that will be drawn with the <b>text()</b>
* function. Fonts must be loaded with <b>loadFont()</b> before it can be
* used. This font will be used in all subsequent calls to the
* <b>text()</b> function. If no <b>size</b> parameter is input, the font
* will appear at its original size (the size it was created at with the
* "Create Font..." tool) until it is changed with <b>textSize()</b>. <br
* /> <br /> Because fonts are usually bitmaped, you should create fonts at
* the sizes that will be used most commonly. Using <b>textFont()</b>
* without the size parameter will result in the cleanest-looking text. <br
* /><br /> With the default (JAVA2D) and PDF renderers, it's also possible
* to enable the use of native fonts via the command
* <b>hint(ENABLE_NATIVE_FONTS)</b>. This will produce vector text in
* JAVA2D sketches and PDF output in cases where the vector data is
* available: when the font is still installed, or the font is created via
* the <b>createFont()</b> function (rather than the Create Font tool).
*
* ( end auto-generated )
*
* @webref typography:loading_displaying
* @param which any variable of the type PFont
* @see PApplet#createFont(String, float, boolean)
* @see PApplet#loadFont(String)
* @see PFont#PFont
* @see PGraphics#text(String, float, float)
*/
public void textFont(PFont which) {
if (recorder != null) recorder.textFont(which);
g.textFont(which);
}
/**
* @param size the size of the letters in units of pixels
*/
public void textFont(PFont which, float size) {
if (recorder != null) recorder.textFont(which, size);
g.textFont(which, size);
}
/**
* ( begin auto-generated from textLeading.xml )
*
* Sets the spacing between lines of text in units of pixels. This setting
* will be used in all subsequent calls to the <b>text()</b> function.
*
* ( end auto-generated )
*
* @webref typography:attributes
* @param leading the size in pixels for spacing between lines
* @see PApplet#loadFont(String)
* @see PFont#PFont
* @see PGraphics#text(String, float, float)
* @see PGraphics#textFont(PFont)
*/
public void textLeading(float leading) {
if (recorder != null) recorder.textLeading(leading);
g.textLeading(leading);
}
/**
* ( begin auto-generated from textMode.xml )
*
* Sets the way text draws to the screen. In the default configuration, the
* <b>MODEL</b> mode, it's possible to rotate, scale, and place letters in
* two and three dimensional space.<br />
* <br />
* The <b>SHAPE</b> mode draws text using the the glyph outlines of
* individual characters rather than as textures. This mode is only
* supported with the <b>PDF</b> and <b>P3D</b> renderer settings. With the
* <b>PDF</b> renderer, you must call <b>textMode(SHAPE)</b> before any
* other drawing occurs. If the outlines are not available, then
* <b>textMode(SHAPE)</b> will be ignored and <b>textMode(MODEL)</b> will
* be used instead.<br />
* <br />
* The <b>textMode(SHAPE)</b> option in <b>P3D</b> can be combined with
* <b>beginRaw()</b> to write vector-accurate text to 2D and 3D output
* files, for instance <b>DXF</b> or <b>PDF</b>. The <b>SHAPE</b> mode is
* not currently optimized for <b>P3D</b>, so if recording shape data, use
* <b>textMode(MODEL)</b> until you're ready to capture the geometry with <b>beginRaw()</b>.
*
* ( end auto-generated )
*
* @webref typography:attributes
* @param mode either MODEL or SHAPE
* @see PApplet#loadFont(String)
* @see PFont#PFont
* @see PGraphics#text(String, float, float)
* @see PGraphics#textFont(PFont)
* @see PGraphics#beginRaw(PGraphics)
* @see PApplet#createFont(String, float, boolean)
*/
public void textMode(int mode) {
if (recorder != null) recorder.textMode(mode);
g.textMode(mode);
}
/**
* ( begin auto-generated from textSize.xml )
*
* Sets the current font size. This size will be used in all subsequent
* calls to the <b>text()</b> function. Font size is measured in units of pixels.
*
* ( end auto-generated )
*
* @webref typography:attributes
* @param size the size of the letters in units of pixels
* @see PApplet#loadFont(String)
* @see PFont#PFont
* @see PGraphics#text(String, float, float)
* @see PGraphics#textFont(PFont)
*/
public void textSize(float size) {
if (recorder != null) recorder.textSize(size);
g.textSize(size);
}
/**
* @param c the character to measure
*/
public float textWidth(char c) {
return g.textWidth(c);
}
/**
* ( begin auto-generated from textWidth.xml )
*
* Calculates and returns the width of any character or text string.
*
* ( end auto-generated )
*
* @webref typography:attributes
* @param str the String of characters to measure
* @see PApplet#loadFont(String)
* @see PFont#PFont
* @see PGraphics#text(String, float, float)
* @see PGraphics#textFont(PFont)
*/
public float textWidth(String str) {
return g.textWidth(str);
}
/**
* @nowebref
*/
public float textWidth(char[] chars, int start, int length) {
return g.textWidth(chars, start, length);
}
/**
* ( begin auto-generated from text.xml )
*
* Draws text to the screen. Displays the information specified in the
* <b>data</b> or <b>stringdata</b> parameters on the screen in the
* position specified by the <b>x</b> and <b>y</b> parameters and the
* optional <b>z</b> parameter. A default font will be used unless a font
* is set with the <b>textFont()</b> function. Change the color of the text
* with the <b>fill()</b> function. The text displays in relation to the
* <b>textAlign()</b> function, which gives the option to draw to the left,
* right, and center of the coordinates.
* <br /><br />
* The <b>x2</b> and <b>y2</b> parameters define a rectangular area to
* display within and may only be used with string data. For text drawn
* inside a rectangle, the coordinates are interpreted based on the current
* <b>rectMode()</b> setting.
*
* ( end auto-generated )
*
* @webref typography:loading_displaying
* @param c the alphanumeric character to be displayed
* @param x x-coordinate of text
* @param y y-coordinate of text
* @see PGraphics#textAlign(int, int)
* @see PGraphics#textMode(int)
* @see PApplet#loadFont(String)
* @see PGraphics#textFont(PFont)
* @see PGraphics#rectMode(int)
* @see PGraphics#fill(int, float)
* @see_external String
*/
public void text(char c, float x, float y) {
if (recorder != null) recorder.text(c, x, y);
g.text(c, x, y);
}
/**
* @param z z-coordinate of text
*/
public void text(char c, float x, float y, float z) {
if (recorder != null) recorder.text(c, x, y, z);
g.text(c, x, y, z);
}
/**
* <h3>Advanced</h3>
* Draw a chunk of text.
* Newlines that are \n (Unix newline or linefeed char, ascii 10)
* are honored, but \r (carriage return, Windows and Mac OS) are
* ignored.
*/
public void text(String str, float x, float y) {
if (recorder != null) recorder.text(str, x, y);
g.text(str, x, y);
}
/**
* <h3>Advanced</h3>
* Method to draw text from an array of chars. This method will usually be
* more efficient than drawing from a String object, because the String will
* not be converted to a char array before drawing.
* @param chars the alphanumberic symbols to be displayed
* @param start array index at which to start writing characters
* @param stop array index at which to stop writing characters
*/
public void text(char[] chars, int start, int stop, float x, float y) {
if (recorder != null) recorder.text(chars, start, stop, x, y);
g.text(chars, start, stop, x, y);
}
/**
* Same as above but with a z coordinate.
*/
public void text(String str, float x, float y, float z) {
if (recorder != null) recorder.text(str, x, y, z);
g.text(str, x, y, z);
}
public void text(char[] chars, int start, int stop,
float x, float y, float z) {
if (recorder != null) recorder.text(chars, start, stop, x, y, z);
g.text(chars, start, stop, x, y, z);
}
/**
* <h3>Advanced</h3>
* Draw text in a box that is constrained to a particular size.
* The current rectMode() determines what the coordinates mean
* (whether x1/y1/x2/y2 or x/y/w/h).
* <P/>
* Note that the x,y coords of the start of the box
* will align with the *ascent* of the text, not the baseline,
* as is the case for the other text() functions.
* <P/>
* Newlines that are \n (Unix newline or linefeed char, ascii 10)
* are honored, and \r (carriage return, Windows and Mac OS) are
* ignored.
*
* @param x1 by default, the x-coordinate of text, see rectMode() for more info
* @param y1 by default, the x-coordinate of text, see rectMode() for more info
* @param x2 by default, the width of the text box, see rectMode() for more info
* @param y2 by default, the height of the text box, see rectMode() for more info
*/
public void text(String str, float x1, float y1, float x2, float y2) {
if (recorder != null) recorder.text(str, x1, y1, x2, y2);
g.text(str, x1, y1, x2, y2);
}
public void text(int num, float x, float y) {
if (recorder != null) recorder.text(num, x, y);
g.text(num, x, y);
}
public void text(int num, float x, float y, float z) {
if (recorder != null) recorder.text(num, x, y, z);
g.text(num, x, y, z);
}
/**
* This does a basic number formatting, to avoid the
* generally ugly appearance of printing floats.
* Users who want more control should use their own nf() cmmand,
* or if they want the long, ugly version of float,
* use String.valueOf() to convert the float to a String first.
*
* @param num the numeric value to be displayed
*/
public void text(float num, float x, float y) {
if (recorder != null) recorder.text(num, x, y);
g.text(num, x, y);
}
public void text(float num, float x, float y, float z) {
if (recorder != null) recorder.text(num, x, y, z);
g.text(num, x, y, z);
}
/**
* ( begin auto-generated from pushMatrix.xml )
*
* Pushes the current transformation matrix onto the matrix stack.
* Understanding <b>pushMatrix()</b> and <b>popMatrix()</b> requires
* understanding the concept of a matrix stack. The <b>pushMatrix()</b>
* function saves the current coordinate system to the stack and
* <b>popMatrix()</b> restores the prior coordinate system.
* <b>pushMatrix()</b> and <b>popMatrix()</b> are used in conjuction with
* the other transformation functions and may be embedded to control the
* scope of the transformations.
*
* ( end auto-generated )
*
* @webref transform
* @see PGraphics#popMatrix()
* @see PGraphics#translate(float, float, float)
* @see PGraphics#rotate(float)
* @see PGraphics#rotateX(float)
* @see PGraphics#rotateY(float)
* @see PGraphics#rotateZ(float)
*/
public void pushMatrix() {
if (recorder != null) recorder.pushMatrix();
g.pushMatrix();
}
/**
* ( begin auto-generated from popMatrix.xml )
*
* Pops the current transformation matrix off the matrix stack.
* Understanding pushing and popping requires understanding the concept of
* a matrix stack. The <b>pushMatrix()</b> function saves the current
* coordinate system to the stack and <b>popMatrix()</b> restores the prior
* coordinate system. <b>pushMatrix()</b> and <b>popMatrix()</b> are used
* in conjuction with the other transformation functions and may be
* embedded to control the scope of the transformations.
*
* ( end auto-generated )
*
* @webref transform
* @see PGraphics#pushMatrix()
*/
public void popMatrix() {
if (recorder != null) recorder.popMatrix();
g.popMatrix();
}
/**
* ( begin auto-generated from translate.xml )
*
* Specifies an amount to displace objects within the display window. The
* <b>x</b> parameter specifies left/right translation, the <b>y</b>
* parameter specifies up/down translation, and the <b>z</b> parameter
* specifies translations toward/away from the screen. Using this function
* with the <b>z</b> parameter requires using P3D as a parameter in
* combination with size as shown in the above example. Transformations
* apply to everything that happens after and subsequent calls to the
* function accumulates the effect. For example, calling <b>translate(50,
* 0)</b> and then <b>translate(20, 0)</b> is the same as <b>translate(70,
* 0)</b>. If <b>translate()</b> is called within <b>draw()</b>, the
* transformation is reset when the loop begins again. This function can be
* further controlled by the <b>pushMatrix()</b> and <b>popMatrix()</b>.
*
* ( end auto-generated )
*
* @webref transform
* @param x left/right translation
* @param y up/down translation
* @see PGraphics#popMatrix()
* @see PGraphics#pushMatrix()
* @see PGraphics#rotate(float)
* @see PGraphics#rotateX(float)
* @see PGraphics#rotateY(float)
* @see PGraphics#rotateZ(float)
* @see PGraphics#scale(float, float, float)
*/
public void translate(float x, float y) {
if (recorder != null) recorder.translate(x, y);
g.translate(x, y);
}
/**
* @param z forward/backward translation
*/
public void translate(float x, float y, float z) {
if (recorder != null) recorder.translate(x, y, z);
g.translate(x, y, z);
}
/**
* ( begin auto-generated from rotate.xml )
*
* Rotates a shape the amount specified by the <b>angle</b> parameter.
* Angles should be specified in radians (values from 0 to TWO_PI) or
* converted to radians with the <b>radians()</b> function.
* <br/> <br/>
* Objects are always rotated around their relative position to the origin
* and positive numbers rotate objects in a clockwise direction.
* Transformations apply to everything that happens after and subsequent
* calls to the function accumulates the effect. For example, calling
* <b>rotate(HALF_PI)</b> and then <b>rotate(HALF_PI)</b> is the same as
* <b>rotate(PI)</b>. All tranformations are reset when <b>draw()</b>
* begins again.
* <br/> <br/>
* Technically, <b>rotate()</b> multiplies the current transformation
* matrix by a rotation matrix. This function can be further controlled by
* the <b>pushMatrix()</b> and <b>popMatrix()</b>.
*
* ( end auto-generated )
*
* @webref transform
* @param angle angle of rotation specified in radians
* @see PGraphics#popMatrix()
* @see PGraphics#pushMatrix()
* @see PGraphics#rotateX(float)
* @see PGraphics#rotateY(float)
* @see PGraphics#rotateZ(float)
* @see PGraphics#scale(float, float, float)
* @see PApplet#radians(float)
*/
public void rotate(float angle) {
if (recorder != null) recorder.rotate(angle);
g.rotate(angle);
}
/**
* ( begin auto-generated from rotateX.xml )
*
* Rotates a shape around the x-axis the amount specified by the
* <b>angle</b> parameter. Angles should be specified in radians (values
* from 0 to PI*2) or converted to radians with the <b>radians()</b>
* function. Objects are always rotated around their relative position to
* the origin and positive numbers rotate objects in a counterclockwise
* direction. Transformations apply to everything that happens after and
* subsequent calls to the function accumulates the effect. For example,
* calling <b>rotateX(PI/2)</b> and then <b>rotateX(PI/2)</b> is the same
* as <b>rotateX(PI)</b>. If <b>rotateX()</b> is called within the
* <b>draw()</b>, the transformation is reset when the loop begins again.
* This function requires using P3D as a third parameter to <b>size()</b>
* as shown in the example above.
*
* ( end auto-generated )
*
* @webref transform
* @param angle angle of rotation specified in radians
* @see PGraphics#popMatrix()
* @see PGraphics#pushMatrix()
* @see PGraphics#rotate(float)
* @see PGraphics#rotateY(float)
* @see PGraphics#rotateZ(float)
* @see PGraphics#scale(float, float, float)
* @see PGraphics#translate(float, float, float)
*/
public void rotateX(float angle) {
if (recorder != null) recorder.rotateX(angle);
g.rotateX(angle);
}
/**
* ( begin auto-generated from rotateY.xml )
*
* Rotates a shape around the y-axis the amount specified by the
* <b>angle</b> parameter. Angles should be specified in radians (values
* from 0 to PI*2) or converted to radians with the <b>radians()</b>
* function. Objects are always rotated around their relative position to
* the origin and positive numbers rotate objects in a counterclockwise
* direction. Transformations apply to everything that happens after and
* subsequent calls to the function accumulates the effect. For example,
* calling <b>rotateY(PI/2)</b> and then <b>rotateY(PI/2)</b> is the same
* as <b>rotateY(PI)</b>. If <b>rotateY()</b> is called within the
* <b>draw()</b>, the transformation is reset when the loop begins again.
* This function requires using P3D as a third parameter to <b>size()</b>
* as shown in the examples above.
*
* ( end auto-generated )
*
* @webref transform
* @param angle angle of rotation specified in radians
* @see PGraphics#popMatrix()
* @see PGraphics#pushMatrix()
* @see PGraphics#rotate(float)
* @see PGraphics#rotateX(float)
* @see PGraphics#rotateZ(float)
* @see PGraphics#scale(float, float, float)
* @see PGraphics#translate(float, float, float)
*/
public void rotateY(float angle) {
if (recorder != null) recorder.rotateY(angle);
g.rotateY(angle);
}
/**
* ( begin auto-generated from rotateZ.xml )
*
* Rotates a shape around the z-axis the amount specified by the
* <b>angle</b> parameter. Angles should be specified in radians (values
* from 0 to PI*2) or converted to radians with the <b>radians()</b>
* function. Objects are always rotated around their relative position to
* the origin and positive numbers rotate objects in a counterclockwise
* direction. Transformations apply to everything that happens after and
* subsequent calls to the function accumulates the effect. For example,
* calling <b>rotateZ(PI/2)</b> and then <b>rotateZ(PI/2)</b> is the same
* as <b>rotateZ(PI)</b>. If <b>rotateZ()</b> is called within the
* <b>draw()</b>, the transformation is reset when the loop begins again.
* This function requires using P3D as a third parameter to <b>size()</b>
* as shown in the examples above.
*
* ( end auto-generated )
*
* @webref transform
* @param angle angle of rotation specified in radians
* @see PGraphics#popMatrix()
* @see PGraphics#pushMatrix()
* @see PGraphics#rotate(float)
* @see PGraphics#rotateX(float)
* @see PGraphics#rotateY(float)
* @see PGraphics#scale(float, float, float)
* @see PGraphics#translate(float, float, float)
*/
public void rotateZ(float angle) {
if (recorder != null) recorder.rotateZ(angle);
g.rotateZ(angle);
}
/**
* <h3>Advanced</h3>
* Rotate about a vector in space. Same as the glRotatef() function.
* @param x
* @param y
* @param z
*/
public void rotate(float angle, float x, float y, float z) {
if (recorder != null) recorder.rotate(angle, x, y, z);
g.rotate(angle, x, y, z);
}
/**
* ( begin auto-generated from scale.xml )
*
* Increases or decreases the size of a shape by expanding and contracting
* vertices. Objects always scale from their relative origin to the
* coordinate system. Scale values are specified as decimal percentages.
* For example, the function call <b>scale(2.0)</b> increases the dimension
* of a shape by 200%. Transformations apply to everything that happens
* after and subsequent calls to the function multiply the effect. For
* example, calling <b>scale(2.0)</b> and then <b>scale(1.5)</b> is the
* same as <b>scale(3.0)</b>. If <b>scale()</b> is called within
* <b>draw()</b>, the transformation is reset when the loop begins again.
* Using this fuction with the <b>z</b> parameter requires using P3D as a
* parameter for <b>size()</b> as shown in the example above. This function
* can be further controlled by <b>pushMatrix()</b> and <b>popMatrix()</b>.
*
* ( end auto-generated )
*
* @webref transform
* @param s percentage to scale the object
* @see PGraphics#pushMatrix()
* @see PGraphics#popMatrix()
* @see PGraphics#translate(float, float, float)
* @see PGraphics#rotate(float)
* @see PGraphics#rotateX(float)
* @see PGraphics#rotateY(float)
* @see PGraphics#rotateZ(float)
*/
public void scale(float s) {
if (recorder != null) recorder.scale(s);
g.scale(s);
}
/**
* <h3>Advanced</h3>
* Scale in X and Y. Equivalent to scale(sx, sy, 1).
*
* Not recommended for use in 3D, because the z-dimension is just
* scaled by 1, since there's no way to know what else to scale it by.
*
* @param x percentage to scale the object in the x-axis
* @param y percentage to scale the object in the y-axis
*/
public void scale(float x, float y) {
if (recorder != null) recorder.scale(x, y);
g.scale(x, y);
}
/**
* @param z percentage to scale the object in the z-axis
*/
public void scale(float x, float y, float z) {
if (recorder != null) recorder.scale(x, y, z);
g.scale(x, y, z);
}
/**
* ( begin auto-generated from shearX.xml )
*
* Shears a shape around the x-axis the amount specified by the
* <b>angle</b> parameter. Angles should be specified in radians (values
* from 0 to PI*2) or converted to radians with the <b>radians()</b>
* function. Objects are always sheared around their relative position to
* the origin and positive numbers shear objects in a clockwise direction.
* Transformations apply to everything that happens after and subsequent
* calls to the function accumulates the effect. For example, calling
* <b>shearX(PI/2)</b> and then <b>shearX(PI/2)</b> is the same as
* <b>shearX(PI)</b>. If <b>shearX()</b> is called within the
* <b>draw()</b>, the transformation is reset when the loop begins again.
* <br/> <br/>
* Technically, <b>shearX()</b> multiplies the current transformation
* matrix by a rotation matrix. This function can be further controlled by
* the <b>pushMatrix()</b> and <b>popMatrix()</b> functions.
*
* ( end auto-generated )
*
* @webref transform
* @param angle angle of shear specified in radians
* @see PGraphics#popMatrix()
* @see PGraphics#pushMatrix()
* @see PGraphics#shearY(float)
* @see PGraphics#scale(float, float, float)
* @see PGraphics#translate(float, float, float)
* @see PApplet#radians(float)
*/
public void shearX(float angle) {
if (recorder != null) recorder.shearX(angle);
g.shearX(angle);
}
/**
* ( begin auto-generated from shearY.xml )
*
* Shears a shape around the y-axis the amount specified by the
* <b>angle</b> parameter. Angles should be specified in radians (values
* from 0 to PI*2) or converted to radians with the <b>radians()</b>
* function. Objects are always sheared around their relative position to
* the origin and positive numbers shear objects in a clockwise direction.
* Transformations apply to everything that happens after and subsequent
* calls to the function accumulates the effect. For example, calling
* <b>shearY(PI/2)</b> and then <b>shearY(PI/2)</b> is the same as
* <b>shearY(PI)</b>. If <b>shearY()</b> is called within the
* <b>draw()</b>, the transformation is reset when the loop begins again.
* <br/> <br/>
* Technically, <b>shearY()</b> multiplies the current transformation
* matrix by a rotation matrix. This function can be further controlled by
* the <b>pushMatrix()</b> and <b>popMatrix()</b> functions.
*
* ( end auto-generated )
*
* @webref transform
* @param angle angle of shear specified in radians
* @see PGraphics#popMatrix()
* @see PGraphics#pushMatrix()
* @see PGraphics#shearX(float)
* @see PGraphics#scale(float, float, float)
* @see PGraphics#translate(float, float, float)
* @see PApplet#radians(float)
*/
public void shearY(float angle) {
if (recorder != null) recorder.shearY(angle);
g.shearY(angle);
}
/**
* ( begin auto-generated from resetMatrix.xml )
*
* Replaces the current matrix with the identity matrix. The equivalent
* function in OpenGL is glLoadIdentity().
*
* ( end auto-generated )
*
* @webref transform
* @see PGraphics#pushMatrix()
* @see PGraphics#popMatrix()
* @see PGraphics#applyMatrix(PMatrix)
* @see PGraphics#printMatrix()
*/
public void resetMatrix() {
if (recorder != null) recorder.resetMatrix();
g.resetMatrix();
}
/**
* ( begin auto-generated from applyMatrix.xml )
*
* Multiplies the current matrix by the one specified through the
* parameters. This is very slow because it will try to calculate the
* inverse of the transform, so avoid it whenever possible. The equivalent
* function in OpenGL is glMultMatrix().
*
* ( end auto-generated )
*
* @webref transform
* @source
* @see PGraphics#pushMatrix()
* @see PGraphics#popMatrix()
* @see PGraphics#resetMatrix()
* @see PGraphics#printMatrix()
*/
public void applyMatrix(PMatrix source) {
if (recorder != null) recorder.applyMatrix(source);
g.applyMatrix(source);
}
public void applyMatrix(PMatrix2D source) {
if (recorder != null) recorder.applyMatrix(source);
g.applyMatrix(source);
}
/**
* @param n00 numbers which define the 4x4 matrix to be multiplied
* @param n01 numbers which define the 4x4 matrix to be multiplied
* @param n02 numbers which define the 4x4 matrix to be multiplied
* @param n10 numbers which define the 4x4 matrix to be multiplied
* @param n11 numbers which define the 4x4 matrix to be multiplied
* @param n12 numbers which define the 4x4 matrix to be multiplied
*/
public void applyMatrix(float n00, float n01, float n02,
float n10, float n11, float n12) {
if (recorder != null) recorder.applyMatrix(n00, n01, n02, n10, n11, n12);
g.applyMatrix(n00, n01, n02, n10, n11, n12);
}
public void applyMatrix(PMatrix3D source) {
if (recorder != null) recorder.applyMatrix(source);
g.applyMatrix(source);
}
/**
* @param n03 numbers which define the 4x4 matrix to be multiplied
* @param n13 numbers which define the 4x4 matrix to be multiplied
* @param n20 numbers which define the 4x4 matrix to be multiplied
* @param n21 numbers which define the 4x4 matrix to be multiplied
* @param n22 numbers which define the 4x4 matrix to be multiplied
* @param n23 numbers which define the 4x4 matrix to be multiplied
* @param n30 numbers which define the 4x4 matrix to be multiplied
* @param n31 numbers which define the 4x4 matrix to be multiplied
* @param n32 numbers which define the 4x4 matrix to be multiplied
* @param n33 numbers which define the 4x4 matrix to be multiplied
*/
public void applyMatrix(float n00, float n01, float n02, float n03,
float n10, float n11, float n12, float n13,
float n20, float n21, float n22, float n23,
float n30, float n31, float n32, float n33) {
if (recorder != null) recorder.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33);
g.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33);
}
public PMatrix getMatrix() {
return g.getMatrix();
}
/**
* Copy the current transformation matrix into the specified target.
* Pass in null to create a new matrix.
*/
public PMatrix2D getMatrix(PMatrix2D target) {
return g.getMatrix(target);
}
/**
* Copy the current transformation matrix into the specified target.
* Pass in null to create a new matrix.
*/
public PMatrix3D getMatrix(PMatrix3D target) {
return g.getMatrix(target);
}
/**
* Set the current transformation matrix to the contents of another.
*/
public void setMatrix(PMatrix source) {
if (recorder != null) recorder.setMatrix(source);
g.setMatrix(source);
}
/**
* Set the current transformation to the contents of the specified source.
*/
public void setMatrix(PMatrix2D source) {
if (recorder != null) recorder.setMatrix(source);
g.setMatrix(source);
}
/**
* Set the current transformation to the contents of the specified source.
*/
public void setMatrix(PMatrix3D source) {
if (recorder != null) recorder.setMatrix(source);
g.setMatrix(source);
}
/**
* ( begin auto-generated from printMatrix.xml )
*
* Prints the current matrix to the Console (the text window at the bottom
* of Processing).
*
* ( end auto-generated )
*
* @webref transform
* @see PGraphics#pushMatrix()
* @see PGraphics#popMatrix()
* @see PGraphics#resetMatrix()
* @see PGraphics#applyMatrix(PMatrix)
*/
public void printMatrix() {
if (recorder != null) recorder.printMatrix();
g.printMatrix();
}
/**
* ( begin auto-generated from beginCamera.xml )
*
* The <b>beginCamera()</b> and <b>endCamera()</b> functions enable
* advanced customization of the camera space. The functions are useful if
* you want to more control over camera movement, however for most users,
* the <b>camera()</b> function will be sufficient.<br /><br />The camera
* functions will replace any transformations (such as <b>rotate()</b> or
* <b>translate()</b>) that occur before them in <b>draw()</b>, but they
* will not automatically replace the camera transform itself. For this
* reason, camera functions should be placed at the beginning of
* <b>draw()</b> (so that transformations happen afterwards), and the
* <b>camera()</b> function can be used after <b>beginCamera()</b> if you
* want to reset the camera before applying transformations.<br /><br
* />This function sets the matrix mode to the camera matrix so calls such
* as <b>translate()</b>, <b>rotate()</b>, applyMatrix() and resetMatrix()
* affect the camera. <b>beginCamera()</b> should always be used with a
* following <b>endCamera()</b> and pairs of <b>beginCamera()</b> and
* <b>endCamera()</b> cannot be nested.
*
* ( end auto-generated )
*
* @webref lights_camera:camera
* @see PGraphics#camera()
* @see PGraphics#endCamera()
* @see PGraphics#applyMatrix(PMatrix)
* @see PGraphics#resetMatrix()
* @see PGraphics#translate(float, float, float)
* @see PGraphics#scale(float, float, float)
*/
public void beginCamera() {
if (recorder != null) recorder.beginCamera();
g.beginCamera();
}
/**
* ( begin auto-generated from endCamera.xml )
*
* The <b>beginCamera()</b> and <b>endCamera()</b> functions enable
* advanced customization of the camera space. Please see the reference for
* <b>beginCamera()</b> for a description of how the functions are used.
*
* ( end auto-generated )
*
* @webref lights_camera:camera
* @see PGraphics#camera(float, float, float, float, float, float, float, float, float)
*/
public void endCamera() {
if (recorder != null) recorder.endCamera();
g.endCamera();
}
/**
* ( begin auto-generated from camera.xml )
*
* Sets the position of the camera through setting the eye position, the
* center of the scene, and which axis is facing upward. Moving the eye
* position and the direction it is pointing (the center of the scene)
* allows the images to be seen from different angles. The version without
* any parameters sets the camera to the default position, pointing to the
* center of the display window with the Y axis as up. The default values
* are <b>camera(width/2.0, height/2.0, (height/2.0) / tan(PI*30.0 /
* 180.0), width/2.0, height/2.0, 0, 0, 1, 0)</b>. This function is similar
* to <b>gluLookAt()</b> in OpenGL, but it first clears the current camera settings.
*
* ( end auto-generated )
*
* @webref lights_camera:camera
* @see PGraphics#endCamera()
* @see PGraphics#frustum(float, float, float, float, float, float)
*/
public void camera() {
if (recorder != null) recorder.camera();
g.camera();
}
/**
* @param eyeX x-coordinate for the eye
* @param eyeY y-coordinate for the eye
* @param eyeZ z-coordinate for the eye
* @param centerX x-coordinate for the center of the scene
* @param centerY y-coordinate for the center of the scene
* @param centerZ z-coordinate for the center of the scene
* @param upX usually 0.0, 1.0, or -1.0
* @param upY usually 0.0, 1.0, or -1.0
* @param upZ usually 0.0, 1.0, or -1.0
*/
public void camera(float eyeX, float eyeY, float eyeZ,
float centerX, float centerY, float centerZ,
float upX, float upY, float upZ) {
if (recorder != null) recorder.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ);
g.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ);
}
/**
* ( begin auto-generated from printCamera.xml )
*
* Prints the current camera matrix to the Console (the text window at the
* bottom of Processing).
*
* ( end auto-generated )
* @webref lights_camera:camera
* @see PGraphics#camera(float, float, float, float, float, float, float, float, float)
*/
public void printCamera() {
if (recorder != null) recorder.printCamera();
g.printCamera();
}
/**
* ( begin auto-generated from ortho.xml )
*
* Sets an orthographic projection and defines a parallel clipping volume.
* All objects with the same dimension appear the same size, regardless of
* whether they are near or far from the camera. The parameters to this
* function specify the clipping volume where left and right are the
* minimum and maximum x values, top and bottom are the minimum and maximum
* y values, and near and far are the minimum and maximum z values. If no
* parameters are given, the default is used: ortho(0, width, 0, height,
* -10, 10).
*
* ( end auto-generated )
*
* @webref lights_camera:camera
*/
public void ortho() {
if (recorder != null) recorder.ortho();
g.ortho();
}
/**
* @param left left plane of the clipping volume
* @param right right plane of the clipping volume
* @param bottom bottom plane of the clipping volume
* @param top top plane of the clipping volume
*/
public void ortho(float left, float right,
float bottom, float top) {
if (recorder != null) recorder.ortho(left, right, bottom, top);
g.ortho(left, right, bottom, top);
}
/**
* @param near maximum distance from the origin to the viewer
* @param far maximum distance from the origin away from the viewer
*/
public void ortho(float left, float right,
float bottom, float top,
float near, float far) {
if (recorder != null) recorder.ortho(left, right, bottom, top, near, far);
g.ortho(left, right, bottom, top, near, far);
}
/**
* ( begin auto-generated from perspective.xml )
*
* Sets a perspective projection applying foreshortening, making distant
* objects appear smaller than closer ones. The parameters define a viewing
* volume with the shape of truncated pyramid. Objects near to the front of
* the volume appear their actual size, while farther objects appear
* smaller. This projection simulates the perspective of the world more
* accurately than orthographic projection. The version of perspective
* without parameters sets the default perspective and the version with
* four parameters allows the programmer to set the area precisely. The
* default values are: perspective(PI/3.0, width/height, cameraZ/10.0,
* cameraZ*10.0) where cameraZ is ((height/2.0) / tan(PI*60.0/360.0));
*
* ( end auto-generated )
*
* @webref lights_camera:camera
*/
public void perspective() {
if (recorder != null) recorder.perspective();
g.perspective();
}
/**
* @param fovy field-of-view angle (in radians) for vertical direction
* @param aspect ratio of width to height
* @param zNear z-position of nearest clipping plane
* @param zFar z-position of farthest clipping plane
*/
public void perspective(float fovy, float aspect, float zNear, float zFar) {
if (recorder != null) recorder.perspective(fovy, aspect, zNear, zFar);
g.perspective(fovy, aspect, zNear, zFar);
}
/**
* ( begin auto-generated from frustum.xml )
*
* Sets a perspective matrix defined through the parameters. Works like
* glFrustum, except it wipes out the current perspective matrix rather
* than muliplying itself with it.
*
* ( end auto-generated )
*
* @webref lights_camera:camera
* @param left left coordinate of the clipping plane
* @param right right coordinate of the clipping plane
* @param bottom bottom coordinate of the clipping plane
* @param top top coordinate of the clipping plane
* @param near near component of the clipping plane; must be greater than zero
* @param far far component of the clipping plane; must be greater than the near value
* @see PGraphics#camera(float, float, float, float, float, float, float, float, float)
* @see PGraphics#endCamera()
* @see PGraphics#perspective(float, float, float, float)
*/
public void frustum(float left, float right,
float bottom, float top,
float near, float far) {
if (recorder != null) recorder.frustum(left, right, bottom, top, near, far);
g.frustum(left, right, bottom, top, near, far);
}
/**
* ( begin auto-generated from printProjection.xml )
*
* Prints the current projection matrix to the Console (the text window at
* the bottom of Processing).
*
* ( end auto-generated )
*
* @webref lights_camera:camera
* @see PGraphics#camera(float, float, float, float, float, float, float, float, float)
*/
public void printProjection() {
if (recorder != null) recorder.printProjection();
g.printProjection();
}
/**
* ( begin auto-generated from screenX.xml )
*
* Takes a three-dimensional X, Y, Z position and returns the X value for
* where it will appear on a (two-dimensional) screen.
*
* ( end auto-generated )
*
* @webref lights_camera:coordinates
* @param x 3D x-coordinate to be mapped
* @param y 3D y-coordinate to be mapped
* @see PGraphics#screenY(float, float, float)
* @see PGraphics#screenZ(float, float, float)
*/
public float screenX(float x, float y) {
return g.screenX(x, y);
}
/**
* ( begin auto-generated from screenY.xml )
*
* Takes a three-dimensional X, Y, Z position and returns the Y value for
* where it will appear on a (two-dimensional) screen.
*
* ( end auto-generated )
*
* @webref lights_camera:coordinates
* @param x 3D x-coordinate to be mapped
* @param y 3D y-coordinate to be mapped
* @see PGraphics#screenX(float, float, float)
* @see PGraphics#screenZ(float, float, float)
*/
public float screenY(float x, float y) {
return g.screenY(x, y);
}
/**
* @param z 3D z-coordinate to be mapped
*/
public float screenX(float x, float y, float z) {
return g.screenX(x, y, z);
}
/**
* @param z 3D z-coordinate to be mapped
*/
public float screenY(float x, float y, float z) {
return g.screenY(x, y, z);
}
/**
* ( begin auto-generated from screenZ.xml )
*
* Takes a three-dimensional X, Y, Z position and returns the Z value for
* where it will appear on a (two-dimensional) screen.
*
* ( end auto-generated )
*
* @webref lights_camera:coordinates
* @param x 3D x-coordinate to be mapped
* @param y 3D y-coordinate to be mapped
* @param z 3D z-coordinate to be mapped
* @see PGraphics#screenX(float, float, float)
* @see PGraphics#screenY(float, float, float)
*/
public float screenZ(float x, float y, float z) {
return g.screenZ(x, y, z);
}
/**
* ( begin auto-generated from modelX.xml )
*
* Returns the three-dimensional X, Y, Z position in model space. This
* returns the X value for a given coordinate based on the current set of
* transformations (scale, rotate, translate, etc.) The X value can be used
* to place an object in space relative to the location of the original
* point once the transformations are no longer in use.
* <br/> <br/>
* In the example, the <b>modelX()</b>, <b>modelY()</b>, and
* <b>modelZ()</b> functions record the location of a box in space after
* being placed using a series of translate and rotate commands. After
* popMatrix() is called, those transformations no longer apply, but the
* (x, y, z) coordinate returned by the model functions is used to place
* another box in the same location.
*
* ( end auto-generated )
*
* @webref lights_camera:coordinates
* @param x 3D x-coordinate to be mapped
* @param y 3D y-coordinate to be mapped
* @param z 3D z-coordinate to be mapped
* @see PGraphics#modelY(float, float, float)
* @see PGraphics#modelZ(float, float, float)
*/
public float modelX(float x, float y, float z) {
return g.modelX(x, y, z);
}
/**
* ( begin auto-generated from modelY.xml )
*
* Returns the three-dimensional X, Y, Z position in model space. This
* returns the Y value for a given coordinate based on the current set of
* transformations (scale, rotate, translate, etc.) The Y value can be used
* to place an object in space relative to the location of the original
* point once the transformations are no longer in use.<br />
* <br />
* In the example, the <b>modelX()</b>, <b>modelY()</b>, and
* <b>modelZ()</b> functions record the location of a box in space after
* being placed using a series of translate and rotate commands. After
* popMatrix() is called, those transformations no longer apply, but the
* (x, y, z) coordinate returned by the model functions is used to place
* another box in the same location.
*
* ( end auto-generated )
*
* @webref lights_camera:coordinates
* @param x 3D x-coordinate to be mapped
* @param y 3D y-coordinate to be mapped
* @param z 3D z-coordinate to be mapped
* @see PGraphics#modelX(float, float, float)
* @see PGraphics#modelZ(float, float, float)
*/
public float modelY(float x, float y, float z) {
return g.modelY(x, y, z);
}
/**
* ( begin auto-generated from modelZ.xml )
*
* Returns the three-dimensional X, Y, Z position in model space. This
* returns the Z value for a given coordinate based on the current set of
* transformations (scale, rotate, translate, etc.) The Z value can be used
* to place an object in space relative to the location of the original
* point once the transformations are no longer in use.<br />
* <br />
* In the example, the <b>modelX()</b>, <b>modelY()</b>, and
* <b>modelZ()</b> functions record the location of a box in space after
* being placed using a series of translate and rotate commands. After
* popMatrix() is called, those transformations no longer apply, but the
* (x, y, z) coordinate returned by the model functions is used to place
* another box in the same location.
*
* ( end auto-generated )
*
* @webref lights_camera:coordinates
* @param x 3D x-coordinate to be mapped
* @param y 3D y-coordinate to be mapped
* @param z 3D z-coordinate to be mapped
* @see PGraphics#modelX(float, float, float)
* @see PGraphics#modelY(float, float, float)
*/
public float modelZ(float x, float y, float z) {
return g.modelZ(x, y, z);
}
/**
* ( begin auto-generated from pushStyle.xml )
*
* The <b>pushStyle()</b> function saves the current style settings and
* <b>popStyle()</b> restores the prior settings. Note that these functions
* are always used together. They allow you to change the style settings
* and later return to what you had. When a new style is started with
* <b>pushStyle()</b>, it builds on the current style information. The
* <b>pushStyle()</b> and <b>popStyle()</b> functions can be embedded to
* provide more control (see the second example above for a demonstration.)
* <br /><br />
* The style information controlled by the following functions are included
* in the style:
* fill(), stroke(), tint(), strokeWeight(), strokeCap(), strokeJoin(),
* imageMode(), rectMode(), ellipseMode(), shapeMode(), colorMode(),
* textAlign(), textFont(), textMode(), textSize(), textLeading(),
* emissive(), specular(), shininess(), ambient()
*
* ( end auto-generated )
*
* @webref structure
* @see PGraphics#popStyle()
*/
public void pushStyle() {
if (recorder != null) recorder.pushStyle();
g.pushStyle();
}
/**
* ( begin auto-generated from popStyle.xml )
*
* The <b>pushStyle()</b> function saves the current style settings and
* <b>popStyle()</b> restores the prior settings; these functions are
* always used together. They allow you to change the style settings and
* later return to what you had. When a new style is started with
* <b>pushStyle()</b>, it builds on the current style information. The
* <b>pushStyle()</b> and <b>popStyle()</b> functions can be embedded to
* provide more control (see the second example above for a demonstration.)
*
* ( end auto-generated )
*
* @webref structure
* @see PGraphics#pushStyle()
*/
public void popStyle() {
if (recorder != null) recorder.popStyle();
g.popStyle();
}
public void style(PStyle s) {
if (recorder != null) recorder.style(s);
g.style(s);
}
/**
* ( begin auto-generated from strokeWeight.xml )
*
* Sets the width of the stroke used for lines, points, and the border
* around shapes. All widths are set in units of pixels.
* <br/> <br/>
* When drawing with P3D, series of connected lines (such as the stroke
* around a polygon, triangle, or ellipse) produce unattractive results
* when a thick stroke weight is set (<a
* href="http://code.google.com/p/processing/issues/detail?id=123">see
* Issue 123</a>). With P3D, the minimum and maximum values for
* <b>strokeWeight()</b> are controlled by the graphics card and the
* operating system's OpenGL implementation. For instance, the thickness
* may not go higher than 10 pixels.
*
* ( end auto-generated )
*
* @webref shape:attributes
* @param weight the weight (in pixels) of the stroke
* @see PGraphics#stroke(int, float)
* @see PGraphics#strokeJoin(int)
* @see PGraphics#strokeCap(int)
*/
public void strokeWeight(float weight) {
if (recorder != null) recorder.strokeWeight(weight);
g.strokeWeight(weight);
}
/**
* ( begin auto-generated from strokeJoin.xml )
*
* Sets the style of the joints which connect line segments. These joints
* are either mitered, beveled, or rounded and specified with the
* corresponding parameters MITER, BEVEL, and ROUND. The default joint is
* MITER.
* <br/> <br/>
* This function is not available with the P3D renderer, (<a
* href="http://code.google.com/p/processing/issues/detail?id=123">see
* Issue 123</a>). More information about the renderers can be found in the
* <b>size()</b> reference.
*
* ( end auto-generated )
*
* @webref shape:attributes
* @param join either MITER, BEVEL, ROUND
* @see PGraphics#stroke(int, float)
* @see PGraphics#strokeWeight(float)
* @see PGraphics#strokeCap(int)
*/
public void strokeJoin(int join) {
if (recorder != null) recorder.strokeJoin(join);
g.strokeJoin(join);
}
/**
* ( begin auto-generated from strokeCap.xml )
*
* Sets the style for rendering line endings. These ends are either
* squared, extended, or rounded and specified with the corresponding
* parameters SQUARE, PROJECT, and ROUND. The default cap is ROUND.
* <br/> <br/>
* This function is not available with the P3D renderer (<a
* href="http://code.google.com/p/processing/issues/detail?id=123">see
* Issue 123</a>). More information about the renderers can be found in the
* <b>size()</b> reference.
*
* ( end auto-generated )
*
* @webref shape:attributes
* @param cap either SQUARE, PROJECT, or ROUND
* @see PGraphics#stroke(int, float)
* @see PGraphics#strokeWeight(float)
* @see PGraphics#strokeJoin(int)
* @see PApplet#size(int, int, String, String)
*/
public void strokeCap(int cap) {
if (recorder != null) recorder.strokeCap(cap);
g.strokeCap(cap);
}
/**
* ( begin auto-generated from noStroke.xml )
*
* Disables drawing the stroke (outline). If both <b>noStroke()</b> and
* <b>noFill()</b> are called, nothing will be drawn to the screen.
*
* ( end auto-generated )
*
* @webref color:setting
* @see PGraphics#stroke(float, float, float, float)
*/
public void noStroke() {
if (recorder != null) recorder.noStroke();
g.noStroke();
}
/**
* ( begin auto-generated from stroke.xml )
*
* Sets the color used to draw lines and borders around shapes. This color
* is either specified in terms of the RGB or HSB color depending on the
* current <b>colorMode()</b> (the default color space is RGB, with each
* value in the range from 0 to 255).
* <br/> <br/>
* When using hexadecimal notation to specify a color, use "#" or "0x"
* before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six
* digits to specify a color (the way colors are specified in HTML and
* CSS). When using the hexadecimal notation starting with "0x", the
* hexadecimal value must be specified with eight characters; the first two
* characters define the alpha component and the remainder the red, green,
* and blue components.
* <br/> <br/>
* The value for the parameter "gray" must be less than or equal to the
* current maximum value as specified by <b>colorMode()</b>. The default
* maximum value is 255.
*
* ( end auto-generated )
*
* @param rgb color value in hexadecimal notation
* @see PGraphics#noStroke()
* @see PGraphics#fill(int, float)
* @see PGraphics#tint(int, float)
* @see PGraphics#background(float, float, float, float)
* @see PGraphics#colorMode(int, float, float, float, float)
*/
public void stroke(int rgb) {
if (recorder != null) recorder.stroke(rgb);
g.stroke(rgb);
}
/**
* @param alpha opacity of the stroke
*/
public void stroke(int rgb, float alpha) {
if (recorder != null) recorder.stroke(rgb, alpha);
g.stroke(rgb, alpha);
}
/**
* @param gray specifies a value between white and black
*/
public void stroke(float gray) {
if (recorder != null) recorder.stroke(gray);
g.stroke(gray);
}
public void stroke(float gray, float alpha) {
if (recorder != null) recorder.stroke(gray, alpha);
g.stroke(gray, alpha);
}
/**
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
* @webref color:setting
*/
public void stroke(float v1, float v2, float v3) {
if (recorder != null) recorder.stroke(v1, v2, v3);
g.stroke(v1, v2, v3);
}
public void stroke(float v1, float v2, float v3, float alpha) {
if (recorder != null) recorder.stroke(v1, v2, v3, alpha);
g.stroke(v1, v2, v3, alpha);
}
/**
* ( begin auto-generated from noTint.xml )
*
* Removes the current fill value for displaying images and reverts to
* displaying images with their original hues.
*
* ( end auto-generated )
*
* @webref image:loading_displaying
* @usage web_application
* @see PGraphics#tint(float, float, float, float)
* @see PGraphics#image(PImage, float, float, float, float)
*/
public void noTint() {
if (recorder != null) recorder.noTint();
g.noTint();
}
/**
* ( begin auto-generated from tint.xml )
*
* Sets the fill value for displaying images. Images can be tinted to
* specified colors or made transparent by setting the alpha.<br />
* <br />
* To make an image transparent, but not change it's color, use white as
* the tint color and specify an alpha value. For instance, tint(255, 128)
* will make an image 50% transparent (unless <b>colorMode()</b> has been
* used).<br />
* <br />
* When using hexadecimal notation to specify a color, use "#" or "0x"
* before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six
* digits to specify a color (the way colors are specified in HTML and
* CSS). When using the hexadecimal notation starting with "0x", the
* hexadecimal value must be specified with eight characters; the first two
* characters define the alpha component and the remainder the red, green,
* and blue components.<br />
* <br />
* The value for the parameter "gray" must be less than or equal to the
* current maximum value as specified by <b>colorMode()</b>. The default
* maximum value is 255.<br />
* <br />
* The <b>tint()</b> function is also used to control the coloring of
* textures in 3D.
*
* ( end auto-generated )
*
* @webref image:loading_displaying
* @usage web_application
* @param rgb color value in hexadecimal notation
* @see PGraphics#noTint()
* @see PGraphics#image(PImage, float, float, float, float)
*/
public void tint(int rgb) {
if (recorder != null) recorder.tint(rgb);
g.tint(rgb);
}
/**
* @param alpha opacity of the image
*/
public void tint(int rgb, float alpha) {
if (recorder != null) recorder.tint(rgb, alpha);
g.tint(rgb, alpha);
}
/**
* @param gray specifies a value between white and black
*/
public void tint(float gray) {
if (recorder != null) recorder.tint(gray);
g.tint(gray);
}
public void tint(float gray, float alpha) {
if (recorder != null) recorder.tint(gray, alpha);
g.tint(gray, alpha);
}
/**
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
*/
public void tint(float v1, float v2, float v3) {
if (recorder != null) recorder.tint(v1, v2, v3);
g.tint(v1, v2, v3);
}
public void tint(float v1, float v2, float v3, float alpha) {
if (recorder != null) recorder.tint(v1, v2, v3, alpha);
g.tint(v1, v2, v3, alpha);
}
/**
* ( begin auto-generated from noFill.xml )
*
* Disables filling geometry. If both <b>noStroke()</b> and <b>noFill()</b>
* are called, nothing will be drawn to the screen.
*
* ( end auto-generated )
*
* @webref color:setting
* @usage web_application
* @see PGraphics#fill(float, float, float, float)
*/
public void noFill() {
if (recorder != null) recorder.noFill();
g.noFill();
}
/**
* ( begin auto-generated from fill.xml )
*
* Sets the color used to fill shapes. For example, if you run <b>fill(204,
* 102, 0)</b>, all subsequent shapes will be filled with orange. This
* color is either specified in terms of the RGB or HSB color depending on
* the current <b>colorMode()</b> (the default color space is RGB, with
* each value in the range from 0 to 255).
* <br/> <br/>
* When using hexadecimal notation to specify a color, use "#" or "0x"
* before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six
* digits to specify a color (the way colors are specified in HTML and
* CSS). When using the hexadecimal notation starting with "0x", the
* hexadecimal value must be specified with eight characters; the first two
* characters define the alpha component and the remainder the red, green,
* and blue components.
* <br/> <br/>
* The value for the parameter "gray" must be less than or equal to the
* current maximum value as specified by <b>colorMode()</b>. The default
* maximum value is 255.
* <br/> <br/>
* To change the color of an image (or a texture), use tint().
*
* ( end auto-generated )
*
* @webref color:setting
* @usage web_application
* @param rgb color variable or hex value
* @see PGraphics#noFill()
* @see PGraphics#stroke(int, float)
* @see PGraphics#tint(int, float)
* @see PGraphics#background(float, float, float, float)
* @see PGraphics#colorMode(int, float, float, float, float)
*/
public void fill(int rgb) {
if (recorder != null) recorder.fill(rgb);
g.fill(rgb);
}
/**
* @param alpha opacity of the fill
*/
public void fill(int rgb, float alpha) {
if (recorder != null) recorder.fill(rgb, alpha);
g.fill(rgb, alpha);
}
/**
* @param gray number specifying value between white and black
*/
public void fill(float gray) {
if (recorder != null) recorder.fill(gray);
g.fill(gray);
}
public void fill(float gray, float alpha) {
if (recorder != null) recorder.fill(gray, alpha);
g.fill(gray, alpha);
}
/**
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
*/
public void fill(float v1, float v2, float v3) {
if (recorder != null) recorder.fill(v1, v2, v3);
g.fill(v1, v2, v3);
}
public void fill(float v1, float v2, float v3, float alpha) {
if (recorder != null) recorder.fill(v1, v2, v3, alpha);
g.fill(v1, v2, v3, alpha);
}
/**
* ( begin auto-generated from ambient.xml )
*
* Sets the ambient reflectance for shapes drawn to the screen. This is
* combined with the ambient light component of environment. The color
* components set through the parameters define the reflectance. For
* example in the default color mode, setting v1=255, v2=126, v3=0, would
* cause all the red light to reflect and half of the green light to
* reflect. Used in combination with <b>emissive()</b>, <b>specular()</b>,
* and <b>shininess()</b> in setting the material properties of shapes.
*
* ( end auto-generated )
*
* @webref lights_camera:material_properties
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#emissive(float, float, float)
* @see PGraphics#specular(float, float, float)
* @see PGraphics#shininess(float)
*/
public void ambient(int rgb) {
if (recorder != null) recorder.ambient(rgb);
g.ambient(rgb);
}
/**
* @param gray number specifying value between white and black
*/
public void ambient(float gray) {
if (recorder != null) recorder.ambient(gray);
g.ambient(gray);
}
/**
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
*/
public void ambient(float v1, float v2, float v3) {
if (recorder != null) recorder.ambient(v1, v2, v3);
g.ambient(v1, v2, v3);
}
/**
* ( begin auto-generated from specular.xml )
*
* Sets the specular color of the materials used for shapes drawn to the
* screen, which sets the color of hightlights. Specular refers to light
* which bounces off a surface in a perferred direction (rather than
* bouncing in all directions like a diffuse light). Used in combination
* with <b>emissive()</b>, <b>ambient()</b>, and <b>shininess()</b> in
* setting the material properties of shapes.
*
* ( end auto-generated )
*
* @webref lights_camera:material_properties
* @usage web_application
* @param rgb color to set
* @see PGraphics#lightSpecular(float, float, float)
* @see PGraphics#ambient(float, float, float)
* @see PGraphics#emissive(float, float, float)
* @see PGraphics#shininess(float)
*/
public void specular(int rgb) {
if (recorder != null) recorder.specular(rgb);
g.specular(rgb);
}
/**
* gray number specifying value between white and black
*/
public void specular(float gray) {
if (recorder != null) recorder.specular(gray);
g.specular(gray);
}
/**
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
*/
public void specular(float v1, float v2, float v3) {
if (recorder != null) recorder.specular(v1, v2, v3);
g.specular(v1, v2, v3);
}
/**
* ( begin auto-generated from shininess.xml )
*
* Sets the amount of gloss in the surface of shapes. Used in combination
* with <b>ambient()</b>, <b>specular()</b>, and <b>emissive()</b> in
* setting the material properties of shapes.
*
* ( end auto-generated )
*
* @webref lights_camera:material_properties
* @usage web_application
* @param shine degree of shininess
* @see PGraphics#emissive(float, float, float)
* @see PGraphics#ambient(float, float, float)
* @see PGraphics#specular(float, float, float)
*/
public void shininess(float shine) {
if (recorder != null) recorder.shininess(shine);
g.shininess(shine);
}
/**
* ( begin auto-generated from emissive.xml )
*
* Sets the emissive color of the material used for drawing shapes drawn to
* the screen. Used in combination with <b>ambient()</b>,
* <b>specular()</b>, and <b>shininess()</b> in setting the material
* properties of shapes.
*
* ( end auto-generated )
*
* @webref lights_camera:material_properties
* @usage web_application
* @param rgb color to set
* @see PGraphics#ambient(float, float, float)
* @see PGraphics#specular(float, float, float)
* @see PGraphics#shininess(float)
*/
public void emissive(int rgb) {
if (recorder != null) recorder.emissive(rgb);
g.emissive(rgb);
}
/**
* gray number specifying value between white and black
*/
public void emissive(float gray) {
if (recorder != null) recorder.emissive(gray);
g.emissive(gray);
}
/**
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
*/
public void emissive(float v1, float v2, float v3) {
if (recorder != null) recorder.emissive(v1, v2, v3);
g.emissive(v1, v2, v3);
}
/**
* ( begin auto-generated from lights.xml )
*
* Sets the default ambient light, directional light, falloff, and specular
* values. The defaults are ambientLight(128, 128, 128) and
* directionalLight(128, 128, 128, 0, 0, -1), lightFalloff(1, 0, 0), and
* lightSpecular(0, 0, 0). Lights need to be included in the draw() to
* remain persistent in a looping program. Placing them in the setup() of a
* looping program will cause them to only have an effect the first time
* through the loop.
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @see PGraphics#ambientLight(float, float, float, float, float, float)
* @see PGraphics#directionalLight(float, float, float, float, float, float)
* @see PGraphics#pointLight(float, float, float, float, float, float)
* @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#noLights()
*/
public void lights() {
if (recorder != null) recorder.lights();
g.lights();
}
/**
* ( begin auto-generated from noLights.xml )
*
* Disable all lighting. Lighting is turned off by default and enabled with
* the <b>lights()</b> function. This function can be used to disable
* lighting so that 2D geometry (which does not require lighting) can be
* drawn after a set of lighted 3D geometry.
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @see PGraphics#lights()
*/
public void noLights() {
if (recorder != null) recorder.noLights();
g.noLights();
}
/**
* ( begin auto-generated from ambientLight.xml )
*
* Adds an ambient light. Ambient light doesn't come from a specific
* direction, the rays have light have bounced around so much that objects
* are evenly lit from all sides. Ambient lights are almost always used in
* combination with other types of lights. Lights need to be included in
* the <b>draw()</b> to remain persistent in a looping program. Placing
* them in the <b>setup()</b> of a looping program will cause them to only
* have an effect the first time through the loop. The effect of the
* parameters is determined by the current color mode.
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
* @see PGraphics#lights()
* @see PGraphics#directionalLight(float, float, float, float, float, float)
* @see PGraphics#pointLight(float, float, float, float, float, float)
* @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float)
*/
public void ambientLight(float v1, float v2, float v3) {
if (recorder != null) recorder.ambientLight(v1, v2, v3);
g.ambientLight(v1, v2, v3);
}
/**
* @param x x-coordinate of the light
* @param y y-coordinate of the light
* @param z z-coordinate of the light
*/
public void ambientLight(float v1, float v2, float v3,
float x, float y, float z) {
if (recorder != null) recorder.ambientLight(v1, v2, v3, x, y, z);
g.ambientLight(v1, v2, v3, x, y, z);
}
/**
* ( begin auto-generated from directionalLight.xml )
*
* Adds a directional light. Directional light comes from one direction and
* is stronger when hitting a surface squarely and weaker if it hits at a a
* gentle angle. After hitting a surface, a directional lights scatters in
* all directions. Lights need to be included in the <b>draw()</b> to
* remain persistent in a looping program. Placing them in the
* <b>setup()</b> of a looping program will cause them to only have an
* effect the first time through the loop. The affect of the <b>v1</b>,
* <b>v2</b>, and <b>v3</b> parameters is determined by the current color
* mode. The <b>nx</b>, <b>ny</b>, and <b>nz</b> parameters specify the
* direction the light is facing. For example, setting <b>ny</b> to -1 will
* cause the geometry to be lit from below (the light is facing directly upward).
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
* @param nx direction along the x-axis
* @param ny direction along the y-axis
* @param nz direction along the z-axis
* @see PGraphics#lights()
* @see PGraphics#ambientLight(float, float, float, float, float, float)
* @see PGraphics#pointLight(float, float, float, float, float, float)
* @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float)
*/
public void directionalLight(float v1, float v2, float v3,
float nx, float ny, float nz) {
if (recorder != null) recorder.directionalLight(v1, v2, v3, nx, ny, nz);
g.directionalLight(v1, v2, v3, nx, ny, nz);
}
/**
* ( begin auto-generated from pointLight.xml )
*
* Adds a point light. Lights need to be included in the <b>draw()</b> to
* remain persistent in a looping program. Placing them in the
* <b>setup()</b> of a looping program will cause them to only have an
* effect the first time through the loop. The affect of the <b>v1</b>,
* <b>v2</b>, and <b>v3</b> parameters is determined by the current color
* mode. The <b>x</b>, <b>y</b>, and <b>z</b> parameters set the position
* of the light.
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
* @param x x-coordinate of the light
* @param y y-coordinate of the light
* @param z z-coordinate of the light
* @see PGraphics#lights()
* @see PGraphics#directionalLight(float, float, float, float, float, float)
* @see PGraphics#ambientLight(float, float, float, float, float, float)
* @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float)
*/
public void pointLight(float v1, float v2, float v3,
float x, float y, float z) {
if (recorder != null) recorder.pointLight(v1, v2, v3, x, y, z);
g.pointLight(v1, v2, v3, x, y, z);
}
/**
* ( begin auto-generated from spotLight.xml )
*
* Adds a spot light. Lights need to be included in the <b>draw()</b> to
* remain persistent in a looping program. Placing them in the
* <b>setup()</b> of a looping program will cause them to only have an
* effect the first time through the loop. The affect of the <b>v1</b>,
* <b>v2</b>, and <b>v3</b> parameters is determined by the current color
* mode. The <b>x</b>, <b>y</b>, and <b>z</b> parameters specify the
* position of the light and <b>nx</b>, <b>ny</b>, <b>nz</b> specify the
* direction or light. The <b>angle</b> parameter affects angle of the
* spotlight cone.
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
* @param x x-coordinate of the light
* @param y y-coordinate of the light
* @param z z-coordinate of the light
* @param nx direction along the x axis
* @param ny direction along the y axis
* @param nz direction along the z axis
* @param angle angle of the spotlight cone
* @param concentration exponent determining the center bias of the cone
* @see PGraphics#lights()
* @see PGraphics#directionalLight(float, float, float, float, float, float)
* @see PGraphics#pointLight(float, float, float, float, float, float)
* @see PGraphics#ambientLight(float, float, float, float, float, float)
*/
public void spotLight(float v1, float v2, float v3,
float x, float y, float z,
float nx, float ny, float nz,
float angle, float concentration) {
if (recorder != null) recorder.spotLight(v1, v2, v3, x, y, z, nx, ny, nz, angle, concentration);
g.spotLight(v1, v2, v3, x, y, z, nx, ny, nz, angle, concentration);
}
/**
* ( begin auto-generated from lightFalloff.xml )
*
* Sets the falloff rates for point lights, spot lights, and ambient
* lights. The parameters are used to determine the falloff with the
* following equation:<br /><br />d = distance from light position to
* vertex position<br />falloff = 1 / (CONSTANT + d * LINEAR + (d*d) *
* QUADRATIC)<br /><br />Like <b>fill()</b>, it affects only the elements
* which are created after it in the code. The default value if
* <b>LightFalloff(1.0, 0.0, 0.0)</b>. Thinking about an ambient light with
* a falloff can be tricky. It is used, for example, if you wanted a region
* of your scene to be lit ambiently one color and another region to be lit
* ambiently by another color, you would use an ambient light with location
* and falloff. You can think of it as a point light that doesn't care
* which direction a surface is facing.
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @param constant constant value or determining falloff
* @param linear linear value for determining falloff
* @param quadratic quadratic value for determining falloff
* @see PGraphics#lights()
* @see PGraphics#ambientLight(float, float, float, float, float, float)
* @see PGraphics#pointLight(float, float, float, float, float, float)
* @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#lightSpecular(float, float, float)
*/
public void lightFalloff(float constant, float linear, float quadratic) {
if (recorder != null) recorder.lightFalloff(constant, linear, quadratic);
g.lightFalloff(constant, linear, quadratic);
}
/**
* ( begin auto-generated from lightSpecular.xml )
*
* Sets the specular color for lights. Like <b>fill()</b>, it affects only
* the elements which are created after it in the code. Specular refers to
* light which bounces off a surface in a perferred direction (rather than
* bouncing in all directions like a diffuse light) and is used for
* creating highlights. The specular quality of a light interacts with the
* specular material qualities set through the <b>specular()</b> and
* <b>shininess()</b> functions.
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
* @see PGraphics#specular(float, float, float)
* @see PGraphics#lights()
* @see PGraphics#ambientLight(float, float, float, float, float, float)
* @see PGraphics#pointLight(float, float, float, float, float, float)
* @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float)
*/
public void lightSpecular(float v1, float v2, float v3) {
if (recorder != null) recorder.lightSpecular(v1, v2, v3);
g.lightSpecular(v1, v2, v3);
}
/**
* ( begin auto-generated from background.xml )
*
* The <b>background()</b> function sets the color used for the background
* of the Processing window. The default background is light gray. In the
* <b>draw()</b> function, the background color is used to clear the
* display window at the beginning of each frame.
* <br/> <br/>
* An image can also be used as the background for a sketch, however its
* width and height must be the same size as the sketch window. To resize
* an image 'b' to the size of the sketch window, use b.resize(width, height).
* <br/> <br/>
* Images used as background will ignore the current <b>tint()</b> setting.
* <br/> <br/>
* It is not possible to use transparency (alpha) in background colors with
* the main drawing surface, however they will work properly with <b>createGraphics()</b>.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* <p>Clear the background with a color that includes an alpha value. This can
* only be used with objects created by createGraphics(), because the main
* drawing surface cannot be set transparent.</p>
* <p>It might be tempting to use this function to partially clear the screen
* on each frame, however that's not how this function works. When calling
* background(), the pixels will be replaced with pixels that have that level
* of transparency. To do a semi-transparent overlay, use fill() with alpha
* and draw a rectangle.</p>
*
* @webref color:setting
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#stroke(float)
* @see PGraphics#fill(float)
* @see PGraphics#tint(float)
* @see PGraphics#colorMode(int)
*/
public void background(int rgb) {
if (recorder != null) recorder.background(rgb);
g.background(rgb);
}
/**
* @param alpha opacity of the background
*/
public void background(int rgb, float alpha) {
if (recorder != null) recorder.background(rgb, alpha);
g.background(rgb, alpha);
}
/**
* @param gray specifies a value between white and black
*/
public void background(float gray) {
if (recorder != null) recorder.background(gray);
g.background(gray);
}
public void background(float gray, float alpha) {
if (recorder != null) recorder.background(gray, alpha);
g.background(gray, alpha);
}
/**
* @param v1 red or hue value (depending on the current color mode)
* @param v2 green or saturation value (depending on the current color mode)
* @param v3 blue or brightness value (depending on the current color mode)
*/
public void background(float v1, float v2, float v3) {
if (recorder != null) recorder.background(v1, v2, v3);
g.background(v1, v2, v3);
}
public void background(float v1, float v2, float v3, float alpha) {
if (recorder != null) recorder.background(v1, v2, v3, alpha);
g.background(v1, v2, v3, alpha);
}
/**
* @webref color:setting
*/
public void clear() {
if (recorder != null) recorder.clear();
g.clear();
}
/**
* Takes an RGB or ARGB image and sets it as the background.
* The width and height of the image must be the same size as the sketch.
* Use image.resize(width, height) to make short work of such a task.<br/>
* <br/>
* Note that even if the image is set as RGB, the high 8 bits of each pixel
* should be set opaque (0xFF000000) because the image data will be copied
* directly to the screen, and non-opaque background images may have strange
* behavior. Use image.filter(OPAQUE) to handle this easily.<br/>
* <br/>
* When using 3D, this will also clear the zbuffer (if it exists).
*
* @param image PImage to set as background (must be same size as the sketch window)
*/
public void background(PImage image) {
if (recorder != null) recorder.background(image);
g.background(image);
}
/**
* ( begin auto-generated from colorMode.xml )
*
* Changes the way Processing interprets color data. By default, the
* parameters for <b>fill()</b>, <b>stroke()</b>, <b>background()</b>, and
* <b>color()</b> are defined by values between 0 and 255 using the RGB
* color model. The <b>colorMode()</b> function is used to change the
* numerical range used for specifying colors and to switch color systems.
* For example, calling <b>colorMode(RGB, 1.0)</b> will specify that values
* are specified between 0 and 1. The limits for defining colors are
* altered by setting the parameters range1, range2, range3, and range 4.
*
* ( end auto-generated )
*
* @webref color:setting
* @usage web_application
* @param mode Either RGB or HSB, corresponding to Red/Green/Blue and Hue/Saturation/Brightness
* @see PGraphics#background(float)
* @see PGraphics#fill(float)
* @see PGraphics#stroke(float)
*/
public void colorMode(int mode) {
if (recorder != null) recorder.colorMode(mode);
g.colorMode(mode);
}
/**
* @param max range for all color elements
*/
public void colorMode(int mode, float max) {
if (recorder != null) recorder.colorMode(mode, max);
g.colorMode(mode, max);
}
/**
* @param max1 range for the red or hue depending on the current color mode
* @param max2 range for the green or saturation depending on the current color mode
* @param max3 range for the blue or brightness depending on the current color mode
*/
public void colorMode(int mode, float max1, float max2, float max3) {
if (recorder != null) recorder.colorMode(mode, max1, max2, max3);
g.colorMode(mode, max1, max2, max3);
}
/**
* @param maxA range for the alpha
*/
public void colorMode(int mode,
float max1, float max2, float max3, float maxA) {
if (recorder != null) recorder.colorMode(mode, max1, max2, max3, maxA);
g.colorMode(mode, max1, max2, max3, maxA);
}
/**
* ( begin auto-generated from alpha.xml )
*
* Extracts the alpha value from a color.
*
* ( end auto-generated )
* @webref color:creating_reading
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#red(int)
* @see PGraphics#green(int)
* @see PGraphics#blue(int)
* @see PGraphics#hue(int)
* @see PGraphics#saturation(int)
* @see PGraphics#brightness(int)
*/
public final float alpha(int rgb) {
return g.alpha(rgb);
}
/**
* ( begin auto-generated from red.xml )
*
* Extracts the red value from a color, scaled to match current
* <b>colorMode()</b>. This value is always returned as a float so be
* careful not to assign it to an int value.<br /><br />The red() function
* is easy to use and undestand, but is slower than another technique. To
* achieve the same results when working in <b>colorMode(RGB, 255)</b>, but
* with greater speed, use the >> (right shift) operator with a bit
* mask. For example, the following two lines of code are equivalent:<br
* /><pre>float r1 = red(myColor);<br />float r2 = myColor >> 16
* & 0xFF;</pre>
*
* ( end auto-generated )
*
* @webref color:creating_reading
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#green(int)
* @see PGraphics#blue(int)
* @see PGraphics#alpha(int)
* @see PGraphics#hue(int)
* @see PGraphics#saturation(int)
* @see PGraphics#brightness(int)
* @see_external rightshift
*/
public final float red(int rgb) {
return g.red(rgb);
}
/**
* ( begin auto-generated from green.xml )
*
* Extracts the green value from a color, scaled to match current
* <b>colorMode()</b>. This value is always returned as a float so be
* careful not to assign it to an int value.<br /><br />The <b>green()</b>
* function is easy to use and undestand, but is slower than another
* technique. To achieve the same results when working in <b>colorMode(RGB,
* 255)</b>, but with greater speed, use the >> (right shift)
* operator with a bit mask. For example, the following two lines of code
* are equivalent:<br /><pre>float r1 = green(myColor);<br />float r2 =
* myColor >> 8 & 0xFF;</pre>
*
* ( end auto-generated )
*
* @webref color:creating_reading
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#red(int)
* @see PGraphics#blue(int)
* @see PGraphics#alpha(int)
* @see PGraphics#hue(int)
* @see PGraphics#saturation(int)
* @see PGraphics#brightness(int)
* @see_external rightshift
*/
public final float green(int rgb) {
return g.green(rgb);
}
/**
* ( begin auto-generated from blue.xml )
*
* Extracts the blue value from a color, scaled to match current
* <b>colorMode()</b>. This value is always returned as a float so be
* careful not to assign it to an int value.<br /><br />The <b>blue()</b>
* function is easy to use and undestand, but is slower than another
* technique. To achieve the same results when working in <b>colorMode(RGB,
* 255)</b>, but with greater speed, use a bit mask to remove the other
* color components. For example, the following two lines of code are
* equivalent:<br /><pre>float r1 = blue(myColor);<br />float r2 = myColor
* & 0xFF;</pre>
*
* ( end auto-generated )
*
* @webref color:creating_reading
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#red(int)
* @see PGraphics#green(int)
* @see PGraphics#alpha(int)
* @see PGraphics#hue(int)
* @see PGraphics#saturation(int)
* @see PGraphics#brightness(int)
* @see_external rightshift
*/
public final float blue(int rgb) {
return g.blue(rgb);
}
/**
* ( begin auto-generated from hue.xml )
*
* Extracts the hue value from a color.
*
* ( end auto-generated )
* @webref color:creating_reading
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#red(int)
* @see PGraphics#green(int)
* @see PGraphics#blue(int)
* @see PGraphics#alpha(int)
* @see PGraphics#saturation(int)
* @see PGraphics#brightness(int)
*/
public final float hue(int rgb) {
return g.hue(rgb);
}
/**
* ( begin auto-generated from saturation.xml )
*
* Extracts the saturation value from a color.
*
* ( end auto-generated )
* @webref color:creating_reading
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#red(int)
* @see PGraphics#green(int)
* @see PGraphics#blue(int)
* @see PGraphics#alpha(int)
* @see PGraphics#hue(int)
* @see PGraphics#brightness(int)
*/
public final float saturation(int rgb) {
return g.saturation(rgb);
}
/**
* ( begin auto-generated from brightness.xml )
*
* Extracts the brightness value from a color.
*
* ( end auto-generated )
*
* @webref color:creating_reading
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#red(int)
* @see PGraphics#green(int)
* @see PGraphics#blue(int)
* @see PGraphics#alpha(int)
* @see PGraphics#hue(int)
* @see PGraphics#saturation(int)
*/
public final float brightness(int rgb) {
return g.brightness(rgb);
}
/**
* ( begin auto-generated from lerpColor.xml )
*
* Calculates a color or colors between two color at a specific increment.
* The <b>amt</b> parameter is the amount to interpolate between the two
* values where 0.0 equal to the first point, 0.1 is very near the first
* point, 0.5 is half-way in between, etc.
*
* ( end auto-generated )
*
* @webref color:creating_reading
* @usage web_application
* @param c1 interpolate from this color
* @param c2 interpolate to this color
* @param amt between 0.0 and 1.0
* @see PImage#blendColor(int, int, int)
* @see PGraphics#color(float, float, float, float)
*/
public int lerpColor(int c1, int c2, float amt) {
return g.lerpColor(c1, c2, amt);
}
/**
* @nowebref
* Interpolate between two colors. Like lerp(), but for the
* individual color components of a color supplied as an int value.
*/
static public int lerpColor(int c1, int c2, float amt, int mode) {
return PGraphics.lerpColor(c1, c2, amt, mode);
}
/**
* Display a warning that the specified method is only available with 3D.
* @param method The method name (no parentheses)
*/
static public void showDepthWarning(String method) {
PGraphics.showDepthWarning(method);
}
/**
* Display a warning that the specified method that takes x, y, z parameters
* can only be used with x and y parameters in this renderer.
* @param method The method name (no parentheses)
*/
static public void showDepthWarningXYZ(String method) {
PGraphics.showDepthWarningXYZ(method);
}
/**
* Display a warning that the specified method is simply unavailable.
*/
static public void showMethodWarning(String method) {
PGraphics.showMethodWarning(method);
}
/**
* Error that a particular variation of a method is unavailable (even though
* other variations are). For instance, if vertex(x, y, u, v) is not
* available, but vertex(x, y) is just fine.
*/
static public void showVariationWarning(String str) {
PGraphics.showVariationWarning(str);
}
/**
* Display a warning that the specified method is not implemented, meaning
* that it could be either a completely missing function, although other
* variations of it may still work properly.
*/
static public void showMissingWarning(String method) {
PGraphics.showMissingWarning(method);
}
/**
* Return true if this renderer should be drawn to the screen. Defaults to
* returning true, since nearly all renderers are on-screen beasts. But can
* be overridden for subclasses like PDF so that a window doesn't open up.
* <br/> <br/>
* A better name? showFrame, displayable, isVisible, visible, shouldDisplay,
* what to call this?
*/
public boolean displayable() {
return g.displayable();
}
/**
* Return true if this renderer does rendering through OpenGL. Defaults to false.
*/
public boolean isGL() {
return g.isGL();
}
/**
* ( begin auto-generated from PImage_get.xml )
*
* Reads the color of any pixel or grabs a section of an image. If no
* parameters are specified, the entire image is returned. Use the <b>x</b>
* and <b>y</b> parameters to get the value of one pixel. Get a section of
* the display window by specifying an additional <b>width</b> and
* <b>height</b> parameter. When getting an image, the <b>x</b> and
* <b>y</b> parameters define the coordinates for the upper-left corner of
* the image, regardless of the current <b>imageMode()</b>.<br />
* <br />
* If the pixel requested is outside of the image window, black is
* returned. The numbers returned are scaled according to the current color
* ranges, but only RGB values are returned by this function. For example,
* even though you may have drawn a shape with <b>colorMode(HSB)</b>, the
* numbers returned will be in RGB format.<br />
* <br />
* Getting the color of a single pixel with <b>get(x, y)</b> is easy, but
* not as fast as grabbing the data directly from <b>pixels[]</b>. The
* equivalent statement to <b>get(x, y)</b> using <b>pixels[]</b> is
* <b>pixels[y*width+x]</b>. See the reference for <b>pixels[]</b> for more information.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Returns an ARGB "color" type (a packed 32 bit int with the color.
* If the coordinate is outside the image, zero is returned
* (black, but completely transparent).
* <P>
* If the image is in RGB format (i.e. on a PVideo object),
* the value will get its high bits set, just to avoid cases where
* they haven't been set already.
* <P>
* If the image is in ALPHA format, this returns a white with its
* alpha value set.
* <P>
* This function is included primarily for beginners. It is quite
* slow because it has to check to see if the x, y that was provided
* is inside the bounds, and then has to check to see what image
* type it is. If you want things to be more efficient, access the
* pixels[] array directly.
*
* @webref image:pixels
* @brief Reads the color of any pixel or grabs a rectangle of pixels
* @usage web_application
* @param x x-coordinate of the pixel
* @param y y-coordinate of the pixel
* @see PApplet#set(int, int, int)
* @see PApplet#pixels
* @see PApplet#copy(PImage, int, int, int, int, int, int, int, int)
*/
public int get(int x, int y) {
return g.get(x, y);
}
/**
* @param w width of pixel rectangle to get
* @param h height of pixel rectangle to get
*/
public PImage get(int x, int y, int w, int h) {
return g.get(x, y, w, h);
}
/**
* Returns a copy of this PImage. Equivalent to get(0, 0, width, height).
*/
public PImage get() {
return g.get();
}
/**
* ( begin auto-generated from PImage_set.xml )
*
* Changes the color of any pixel or writes an image directly into the
* display window.<br />
* <br />
* The <b>x</b> and <b>y</b> parameters specify the pixel to change and the
* <b>color</b> parameter specifies the color value. The color parameter is
* affected by the current color mode (the default is RGB values from 0 to
* 255). When setting an image, the <b>x</b> and <b>y</b> parameters define
* the coordinates for the upper-left corner of the image, regardless of
* the current <b>imageMode()</b>.
* <br /><br />
* Setting the color of a single pixel with <b>set(x, y)</b> is easy, but
* not as fast as putting the data directly into <b>pixels[]</b>. The
* equivalent statement to <b>set(x, y, #000000)</b> using <b>pixels[]</b>
* is <b>pixels[y*width+x] = #000000</b>. See the reference for
* <b>pixels[]</b> for more information.
*
* ( end auto-generated )
*
* @webref image:pixels
* @brief writes a color to any pixel or writes an image into another
* @usage web_application
* @param x x-coordinate of the pixel
* @param y y-coordinate of the pixel
* @param c any value of the color datatype
* @see PImage#get(int, int, int, int)
* @see PImage#pixels
* @see PImage#copy(PImage, int, int, int, int, int, int, int, int)
*/
public void set(int x, int y, int c) {
if (recorder != null) recorder.set(x, y, c);
g.set(x, y, c);
}
/**
* <h3>Advanced</h3>
* Efficient method of drawing an image's pixels directly to this surface.
* No variations are employed, meaning that any scale, tint, or imageMode
* settings will be ignored.
*
* @param img image to draw on screen
*/
public void set(int x, int y, PImage img) {
if (recorder != null) recorder.set(x, y, img);
g.set(x, y, img);
}
/**
* ( begin auto-generated from PImage_mask.xml )
*
* Masks part of an image from displaying by loading another image and
* using it as an alpha channel. This mask image should only contain
* grayscale data, but only the blue color channel is used. The mask image
* needs to be the same size as the image to which it is applied.<br />
* <br />
* In addition to using a mask image, an integer array containing the alpha
* channel data can be specified directly. This method is useful for
* creating dynamically generated alpha masks. This array must be of the
* same length as the target image's pixels array and should contain only
* grayscale data of values between 0-255.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
*
* Set alpha channel for an image. Black colors in the source
* image will make the destination image completely transparent,
* and white will make things fully opaque. Gray values will
* be in-between steps.
* <P>
* Strictly speaking the "blue" value from the source image is
* used as the alpha color. For a fully grayscale image, this
* is correct, but for a color image it's not 100% accurate.
* For a more accurate conversion, first use filter(GRAY)
* which will make the image into a "correct" grayscale by
* performing a proper luminance-based conversion.
*
* @webref pimage:method
* @usage web_application
* @brief Masks part of an image with another image as an alpha channel
* @param maskArray array of integers used as the alpha channel, needs to be the same length as the image's pixel array
*/
public void mask(PImage img) {
if (recorder != null) recorder.mask(img);
g.mask(img);
}
public void filter(int kind) {
if (recorder != null) recorder.filter(kind);
g.filter(kind);
}
/**
* ( begin auto-generated from PImage_filter.xml )
*
* Filters an image as defined by one of the following modes:<br /><br
* />THRESHOLD - converts the image to black and white pixels depending if
* they are above or below the threshold defined by the level parameter.
* The level must be between 0.0 (black) and 1.0(white). If no level is
* specified, 0.5 is used.<br />
* <br />
* GRAY - converts any colors in the image to grayscale equivalents<br />
* <br />
* INVERT - sets each pixel to its inverse value<br />
* <br />
* POSTERIZE - limits each channel of the image to the number of colors
* specified as the level parameter<br />
* <br />
* BLUR - executes a Guassian blur with the level parameter specifying the
* extent of the blurring. If no level parameter is used, the blur is
* equivalent to Guassian blur of radius 1<br />
* <br />
* OPAQUE - sets the alpha channel to entirely opaque<br />
* <br />
* ERODE - reduces the light areas with the amount defined by the level
* parameter<br />
* <br />
* DILATE - increases the light areas with the amount defined by the level parameter
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Method to apply a variety of basic filters to this image.
* <P>
* <UL>
* <LI>filter(BLUR) provides a basic blur.
* <LI>filter(GRAY) converts the image to grayscale based on luminance.
* <LI>filter(INVERT) will invert the color components in the image.
* <LI>filter(OPAQUE) set all the high bits in the image to opaque
* <LI>filter(THRESHOLD) converts the image to black and white.
* <LI>filter(DILATE) grow white/light areas
* <LI>filter(ERODE) shrink white/light areas
* </UL>
* Luminance conversion code contributed by
* <A HREF="http://www.toxi.co.uk">toxi</A>
* <P/>
* Gaussian blur code contributed by
* <A HREF="http://incubator.quasimondo.com">Mario Klingemann</A>
*
* @webref image:pixels
* @brief Converts the image to grayscale or black and white
* @usage web_application
* @param kind Either THRESHOLD, GRAY, OPAQUE, INVERT, POSTERIZE, BLUR, ERODE, or DILATE
* @param param unique for each, see above
*/
public void filter(int kind, float param) {
if (recorder != null) recorder.filter(kind, param);
g.filter(kind, param);
}
/**
* ( begin auto-generated from PImage_copy.xml )
*
* Copies a region of pixels from one image into another. If the source and
* destination regions aren't the same size, it will automatically resize
* source pixels to fit the specified target region. No alpha information
* is used in the process, however if the source image has an alpha channel
* set, it will be copied as well.
* <br /><br />
* As of release 0149, this function ignores <b>imageMode()</b>.
*
* ( end auto-generated )
*
* @webref image:pixels
* @brief Copies the entire image
* @usage web_application
* @param sx X coordinate of the source's upper left corner
* @param sy Y coordinate of the source's upper left corner
* @param sw source image width
* @param sh source image height
* @param dx X coordinate of the destination's upper left corner
* @param dy Y coordinate of the destination's upper left corner
* @param dw destination image width
* @param dh destination image height
* @see PGraphics#alpha(int)
* @see PImage#blend(PImage, int, int, int, int, int, int, int, int, int)
*/
public void copy(int sx, int sy, int sw, int sh,
int dx, int dy, int dw, int dh) {
if (recorder != null) recorder.copy(sx, sy, sw, sh, dx, dy, dw, dh);
g.copy(sx, sy, sw, sh, dx, dy, dw, dh);
}
/**
* @param src an image variable referring to the source image.
*/
public void copy(PImage src,
int sx, int sy, int sw, int sh,
int dx, int dy, int dw, int dh) {
if (recorder != null) recorder.copy(src, sx, sy, sw, sh, dx, dy, dw, dh);
g.copy(src, sx, sy, sw, sh, dx, dy, dw, dh);
}
public void blend(int sx, int sy, int sw, int sh,
int dx, int dy, int dw, int dh, int mode) {
if (recorder != null) recorder.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode);
g.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode);
}
/**
* ( begin auto-generated from PImage_blend.xml )
*
* Blends a region of pixels into the image specified by the <b>img</b>
* parameter. These copies utilize full alpha channel support and a choice
* of the following modes to blend the colors of source pixels (A) with the
* ones of pixels in the destination image (B):<br />
* <br />
* BLEND - linear interpolation of colours: C = A*factor + B<br />
* <br />
* ADD - additive blending with white clip: C = min(A*factor + B, 255)<br />
* <br />
* SUBTRACT - subtractive blending with black clip: C = max(B - A*factor,
* 0)<br />
* <br />
* DARKEST - only the darkest colour succeeds: C = min(A*factor, B)<br />
* <br />
* LIGHTEST - only the lightest colour succeeds: C = max(A*factor, B)<br />
* <br />
* DIFFERENCE - subtract colors from underlying image.<br />
* <br />
* EXCLUSION - similar to DIFFERENCE, but less extreme.<br />
* <br />
* MULTIPLY - Multiply the colors, result will always be darker.<br />
* <br />
* SCREEN - Opposite multiply, uses inverse values of the colors.<br />
* <br />
* OVERLAY - A mix of MULTIPLY and SCREEN. Multiplies dark values,
* and screens light values.<br />
* <br />
* HARD_LIGHT - SCREEN when greater than 50% gray, MULTIPLY when lower.<br />
* <br />
* SOFT_LIGHT - Mix of DARKEST and LIGHTEST.
* Works like OVERLAY, but not as harsh.<br />
* <br />
* DODGE - Lightens light tones and increases contrast, ignores darks.
* Called "Color Dodge" in Illustrator and Photoshop.<br />
* <br />
* BURN - Darker areas are applied, increasing contrast, ignores lights.
* Called "Color Burn" in Illustrator and Photoshop.<br />
* <br />
* All modes use the alpha information (highest byte) of source image
* pixels as the blending factor. If the source and destination regions are
* different sizes, the image will be automatically resized to match the
* destination size. If the <b>srcImg</b> parameter is not used, the
* display window is used as the source image.<br />
* <br />
* As of release 0149, this function ignores <b>imageMode()</b>.
*
* ( end auto-generated )
*
* @webref image:pixels
* @brief Copies a pixel or rectangle of pixels using different blending modes
* @param src an image variable referring to the source image
* @param sx X coordinate of the source's upper left corner
* @param sy Y coordinate of the source's upper left corner
* @param sw source image width
* @param sh source image height
* @param dx X coordinate of the destinations's upper left corner
* @param dy Y coordinate of the destinations's upper left corner
* @param dw destination image width
* @param dh destination image height
* @param mode Either BLEND, ADD, SUBTRACT, LIGHTEST, DARKEST, DIFFERENCE, EXCLUSION, MULTIPLY, SCREEN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, BURN
*
* @see PApplet#alpha(int)
* @see PImage#copy(PImage, int, int, int, int, int, int, int, int)
* @see PImage#blendColor(int,int,int)
*/
public void blend(PImage src,
int sx, int sy, int sw, int sh,
int dx, int dy, int dw, int dh, int mode) {
if (recorder != null) recorder.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode);
g.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode);
}
}
| public PImage loadImage(String filename, String extension) { //, Object params) {
if (extension == null) {
String lower = filename.toLowerCase();
int dot = filename.lastIndexOf('.');
if (dot == -1) {
extension = "unknown"; // no extension found
}
extension = lower.substring(dot + 1);
// check for, and strip any parameters on the url, i.e.
// filename.jpg?blah=blah&something=that
int question = extension.indexOf('?');
if (question != -1) {
extension = extension.substring(0, question);
}
}
// just in case. them users will try anything!
extension = extension.toLowerCase();
if (extension.equals("tga")) {
try {
PImage image = loadImageTGA(filename);
// if (params != null) {
// image.setParams(g, params);
// }
return image;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
if (extension.equals("tif") || extension.equals("tiff")) {
byte bytes[] = loadBytes(filename);
PImage image = (bytes == null) ? null : PImage.loadTIFF(bytes);
// if (params != null) {
// image.setParams(g, params);
// }
return image;
}
// For jpeg, gif, and png, load them using createImage(),
// because the javax.imageio code was found to be much slower.
// http://dev.processing.org/bugs/show_bug.cgi?id=392
try {
if (extension.equals("jpg") || extension.equals("jpeg") ||
extension.equals("gif") || extension.equals("png") ||
extension.equals("unknown")) {
byte bytes[] = loadBytes(filename);
if (bytes == null) {
return null;
} else {
Image awtImage = Toolkit.getDefaultToolkit().createImage(bytes);
PImage image = loadImageMT(awtImage);
if (image.width == -1) {
System.err.println("The file " + filename +
" contains bad image data, or may not be an image.");
}
// if it's a .gif image, test to see if it has transparency
if (extension.equals("gif") || extension.equals("png")) {
image.checkAlpha();
}
// if (params != null) {
// image.setParams(g, params);
// }
return image;
}
}
} catch (Exception e) {
// show error, but move on to the stuff below, see if it'll work
e.printStackTrace();
}
if (loadImageFormats == null) {
loadImageFormats = ImageIO.getReaderFormatNames();
}
if (loadImageFormats != null) {
for (int i = 0; i < loadImageFormats.length; i++) {
if (extension.equals(loadImageFormats[i])) {
return loadImageIO(filename);
// PImage image = loadImageIO(filename);
// if (params != null) {
// image.setParams(g, params);
// }
// return image;
}
}
}
// failed, could not load image after all those attempts
System.err.println("Could not find a method to load " + filename);
return null;
}
public PImage requestImage(String filename) {
// return requestImage(filename, null, null);
return requestImage(filename, null);
}
/**
* ( begin auto-generated from requestImage.xml )
*
* This function load images on a separate thread so that your sketch does
* not freeze while images load during <b>setup()</b>. While the image is
* loading, its width and height will be 0. If an error occurs while
* loading the image, its width and height will be set to -1. You'll know
* when the image has loaded properly because its width and height will be
* greater than 0. Asynchronous image loading (particularly when
* downloading from a server) can dramatically improve performance.<br />
* <br/> <b>extension</b> parameter is used to determine the image type in
* cases where the image filename does not end with a proper extension.
* Specify the extension as the second parameter to <b>requestImage()</b>.
*
* ( end auto-generated )
*
* @webref image:loading_displaying
* @param filename name of the file to load, can be .gif, .jpg, .tga, or a handful of other image types depending on your platform
* @param extension the type of image to load, for example "png", "gif", "jpg"
* @see PApplet#loadImage(String, String)
* @see PImage#PImage
*/
public PImage requestImage(String filename, String extension) {
PImage vessel = createImage(0, 0, ARGB);
AsyncImageLoader ail =
new AsyncImageLoader(filename, extension, vessel);
ail.start();
return vessel;
}
// /**
// * @nowebref
// */
// public PImage requestImage(String filename, String extension, Object params) {
// PImage vessel = createImage(0, 0, ARGB, params);
// AsyncImageLoader ail =
// new AsyncImageLoader(filename, extension, vessel);
// ail.start();
// return vessel;
// }
/**
* By trial and error, four image loading threads seem to work best when
* loading images from online. This is consistent with the number of open
* connections that web browsers will maintain. The variable is made public
* (however no accessor has been added since it's esoteric) if you really
* want to have control over the value used. For instance, when loading local
* files, it might be better to only have a single thread (or two) loading
* images so that you're disk isn't simply jumping around.
*/
public int requestImageMax = 4;
volatile int requestImageCount;
class AsyncImageLoader extends Thread {
String filename;
String extension;
PImage vessel;
public AsyncImageLoader(String filename, String extension, PImage vessel) {
this.filename = filename;
this.extension = extension;
this.vessel = vessel;
}
@Override
public void run() {
while (requestImageCount == requestImageMax) {
try {
Thread.sleep(10);
} catch (InterruptedException e) { }
}
requestImageCount++;
PImage actual = loadImage(filename, extension);
// An error message should have already printed
if (actual == null) {
vessel.width = -1;
vessel.height = -1;
} else {
vessel.width = actual.width;
vessel.height = actual.height;
vessel.format = actual.format;
vessel.pixels = actual.pixels;
}
requestImageCount--;
}
}
/**
* Load an AWT image synchronously by setting up a MediaTracker for
* a single image, and blocking until it has loaded.
*/
protected PImage loadImageMT(Image awtImage) {
MediaTracker tracker = new MediaTracker(this);
tracker.addImage(awtImage, 0);
try {
tracker.waitForAll();
} catch (InterruptedException e) {
//e.printStackTrace(); // non-fatal, right?
}
PImage image = new PImage(awtImage);
image.parent = this;
return image;
}
/**
* Use Java 1.4 ImageIO methods to load an image.
*/
protected PImage loadImageIO(String filename) {
InputStream stream = createInput(filename);
if (stream == null) {
System.err.println("The image " + filename + " could not be found.");
return null;
}
try {
BufferedImage bi = ImageIO.read(stream);
PImage outgoing = new PImage(bi.getWidth(), bi.getHeight());
outgoing.parent = this;
bi.getRGB(0, 0, outgoing.width, outgoing.height,
outgoing.pixels, 0, outgoing.width);
// check the alpha for this image
// was gonna call getType() on the image to see if RGB or ARGB,
// but it's not actually useful, since gif images will come through
// as TYPE_BYTE_INDEXED, which means it'll still have to check for
// the transparency. also, would have to iterate through all the other
// types and guess whether alpha was in there, so.. just gonna stick
// with the old method.
outgoing.checkAlpha();
// return the image
return outgoing;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Targa image loader for RLE-compressed TGA files.
* <p>
* Rewritten for 0115 to read/write RLE-encoded targa images.
* For 0125, non-RLE encoded images are now supported, along with
* images whose y-order is reversed (which is standard for TGA files).
*/
protected PImage loadImageTGA(String filename) throws IOException {
InputStream is = createInput(filename);
if (is == null) return null;
byte header[] = new byte[18];
int offset = 0;
do {
int count = is.read(header, offset, header.length - offset);
if (count == -1) return null;
offset += count;
} while (offset < 18);
/*
header[2] image type code
2 (0x02) - Uncompressed, RGB images.
3 (0x03) - Uncompressed, black and white images.
10 (0x0A) - Runlength encoded RGB images.
11 (0x0B) - Compressed, black and white images. (grayscale?)
header[16] is the bit depth (8, 24, 32)
header[17] image descriptor (packed bits)
0x20 is 32 = origin upper-left
0x28 is 32 + 8 = origin upper-left + 32 bits
7 6 5 4 3 2 1 0
128 64 32 16 8 4 2 1
*/
int format = 0;
if (((header[2] == 3) || (header[2] == 11)) && // B&W, plus RLE or not
(header[16] == 8) && // 8 bits
((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32 bit
format = ALPHA;
} else if (((header[2] == 2) || (header[2] == 10)) && // RGB, RLE or not
(header[16] == 24) && // 24 bits
((header[17] == 0x20) || (header[17] == 0))) { // origin
format = RGB;
} else if (((header[2] == 2) || (header[2] == 10)) &&
(header[16] == 32) &&
((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32
format = ARGB;
}
if (format == 0) {
System.err.println("Unknown .tga file format for " + filename);
//" (" + header[2] + " " +
//(header[16] & 0xff) + " " +
//hex(header[17], 2) + ")");
return null;
}
int w = ((header[13] & 0xff) << 8) + (header[12] & 0xff);
int h = ((header[15] & 0xff) << 8) + (header[14] & 0xff);
PImage outgoing = createImage(w, h, format);
// where "reversed" means upper-left corner (normal for most of
// the modernized world, but "reversed" for the tga spec)
boolean reversed = (header[17] & 0x20) != 0;
if ((header[2] == 2) || (header[2] == 3)) { // not RLE encoded
if (reversed) {
int index = (h-1) * w;
switch (format) {
case ALPHA:
for (int y = h-1; y >= 0; y--) {
for (int x = 0; x < w; x++) {
outgoing.pixels[index + x] = is.read();
}
index -= w;
}
break;
case RGB:
for (int y = h-1; y >= 0; y--) {
for (int x = 0; x < w; x++) {
outgoing.pixels[index + x] =
is.read() | (is.read() << 8) | (is.read() << 16) |
0xff000000;
}
index -= w;
}
break;
case ARGB:
for (int y = h-1; y >= 0; y--) {
for (int x = 0; x < w; x++) {
outgoing.pixels[index + x] =
is.read() | (is.read() << 8) | (is.read() << 16) |
(is.read() << 24);
}
index -= w;
}
}
} else { // not reversed
int count = w * h;
switch (format) {
case ALPHA:
for (int i = 0; i < count; i++) {
outgoing.pixels[i] = is.read();
}
break;
case RGB:
for (int i = 0; i < count; i++) {
outgoing.pixels[i] =
is.read() | (is.read() << 8) | (is.read() << 16) |
0xff000000;
}
break;
case ARGB:
for (int i = 0; i < count; i++) {
outgoing.pixels[i] =
is.read() | (is.read() << 8) | (is.read() << 16) |
(is.read() << 24);
}
break;
}
}
} else { // header[2] is 10 or 11
int index = 0;
int px[] = outgoing.pixels;
while (index < px.length) {
int num = is.read();
boolean isRLE = (num & 0x80) != 0;
if (isRLE) {
num -= 127; // (num & 0x7F) + 1
int pixel = 0;
switch (format) {
case ALPHA:
pixel = is.read();
break;
case RGB:
pixel = 0xFF000000 |
is.read() | (is.read() << 8) | (is.read() << 16);
//(is.read() << 16) | (is.read() << 8) | is.read();
break;
case ARGB:
pixel = is.read() |
(is.read() << 8) | (is.read() << 16) | (is.read() << 24);
break;
}
for (int i = 0; i < num; i++) {
px[index++] = pixel;
if (index == px.length) break;
}
} else { // write up to 127 bytes as uncompressed
num += 1;
switch (format) {
case ALPHA:
for (int i = 0; i < num; i++) {
px[index++] = is.read();
}
break;
case RGB:
for (int i = 0; i < num; i++) {
px[index++] = 0xFF000000 |
is.read() | (is.read() << 8) | (is.read() << 16);
//(is.read() << 16) | (is.read() << 8) | is.read();
}
break;
case ARGB:
for (int i = 0; i < num; i++) {
px[index++] = is.read() | //(is.read() << 24) |
(is.read() << 8) | (is.read() << 16) | (is.read() << 24);
//(is.read() << 16) | (is.read() << 8) | is.read();
}
break;
}
}
}
if (!reversed) {
int[] temp = new int[w];
for (int y = 0; y < h/2; y++) {
int z = (h-1) - y;
System.arraycopy(px, y*w, temp, 0, w);
System.arraycopy(px, z*w, px, y*w, w);
System.arraycopy(temp, 0, px, z*w, w);
}
}
}
return outgoing;
}
//////////////////////////////////////////////////////////////
// DATA I/O
/**
* @webref input:files
* @brief Creates a new XML object
* @param name the name to be given to the root element of the new XML object
* @return an XML object, or null
* @see PApplet#loadXML(String)
* @see PApplet#parseXML(String)
*/
public XML createXML(String name) {
try {
return new XML(name);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* @webref input:files
* @param filename name of a file in the data folder or a URL.
* @see PApplet#createXML(String)
* @see PApplet#parseXML(String)
* @see PApplet#saveXML(String)
* @see PApplet#loadBytes(String)
* @see PApplet#loadStrings(String)
* @see PApplet#loadTable(String)
*/
public XML loadXML(String filename) {
return loadXML(filename, null);
}
// version that uses 'options' though there are currently no supported options
public XML loadXML(String filename, String options) {
try {
return new XML(createInput(filename), options);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* @webref input:files
* @brief Converts String content to an XML object
* @param data the content to be parsed as XML
* @return an XML object, or null
* @see PApplet#createXML(String)
* @see PApplet#loadXML(String)
* @see PApplet#saveXML(String)
*/
public XML parseXML(String xmlString) {
return parseXML(xmlString, null);
}
public XML parseXML(String xmlString, String options) {
try {
return XML.parse(xmlString, options);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* @webref output:files
* @param xml the XML object to save to disk
* @param filename name of the file to write to
* @see PApplet#createXML(String)
* @see PApplet#loadXML(String)
* @see PApplet#parseXML(String)
*/
public boolean saveXML(XML xml, String filename) {
return saveXML(xml, filename, null);
}
public boolean saveXML(XML xml, String filename, String options) {
return xml.save(saveFile(filename), options);
}
/**
* @webref input:files
* @see PApplet#loadTable(String)
* @see PApplet#saveTable(Table, String)
*/
public Table createTable() {
return new Table();
}
/**
* @webref input:files
* @param filename name of a file in the data folder or a URL.
* @see PApplet#createTable()
* @see PApplet#saveTable(Table, String)
* @see PApplet#loadBytes(String)
* @see PApplet#loadStrings(String)
* @see PApplet#loadXML(String)
*/
public Table loadTable(String filename) {
return loadTable(filename, null);
}
/**
* @param options may contain "header", "tsv", or "csv" separated by commas
*/
public Table loadTable(String filename, String options) {
try {
String ext = checkExtension(filename);
if (ext != null) {
if (ext.equals("csv") || ext.equals("tsv") || ext.equals("bin")) {
if (options == null) {
options = ext;
} else {
options = ext + "," + options;
}
}
}
return new Table(createInput(filename), options);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* @webref input:files
* @param table the Table object to save to a file
* @param filename the filename to which the Table should be saved
* @see PApplet#createTable()
* @see PApplet#loadTable(String)
*/
public boolean saveTable(Table table, String filename) {
return saveTable(table, filename, null);
}
/**
* @param options may contain "header", "tsv", or "csv" separated by commas
*/
public boolean saveTable(Table table, String filename, String options) {
try {
table.save(saveFile(filename), options);
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
protected String checkExtension(String filename) {
int index = filename.lastIndexOf('.');
if (index == -1) {
return null;
}
return filename.substring(index + 1).toLowerCase();
}
//////////////////////////////////////////////////////////////
// FONT I/O
/**
* ( begin auto-generated from loadFont.xml )
*
* Loads a font into a variable of type <b>PFont</b>. To load correctly,
* fonts must be located in the data directory of the current sketch. To
* create a font to use with Processing, select "Create Font..." from the
* Tools menu. This will create a font in the format Processing requires
* and also adds it to the current sketch's data directory.<br />
* <br />
* Like <b>loadImage()</b> and other functions that load data, the
* <b>loadFont()</b> function should not be used inside <b>draw()</b>,
* because it will slow down the sketch considerably, as the font will be
* re-loaded from the disk (or network) on each frame.<br />
* <br />
* For most renderers, Processing displays fonts using the .vlw font
* format, which uses images for each letter, rather than defining them
* through vector data. When <b>hint(ENABLE_NATIVE_FONTS)</b> is used with
* the JAVA2D renderer, the native version of a font will be used if it is
* installed on the user's machine.<br />
* <br />
* Using <b>createFont()</b> (instead of loadFont) enables vector data to
* be used with the JAVA2D (default) renderer setting. This can be helpful
* when many font sizes are needed, or when using any renderer based on
* JAVA2D, such as the PDF library.
*
* ( end auto-generated )
* @webref typography:loading_displaying
* @param filename name of the font to load
* @see PFont#PFont(Font, boolean)
* @see PGraphics#textFont(PFont, float)
* @see PApplet#createFont(String, float, boolean, char[])
*/
public PFont loadFont(String filename) {
try {
InputStream input = createInput(filename);
return new PFont(input);
} catch (Exception e) {
die("Could not load font " + filename + ". " +
"Make sure that the font has been copied " +
"to the data folder of your sketch.", e);
}
return null;
}
/**
* Used by PGraphics to remove the requirement for loading a font!
*/
protected PFont createDefaultFont(float size) {
// Font f = new Font("SansSerif", Font.PLAIN, 12);
// println("n: " + f.getName());
// println("fn: " + f.getFontName());
// println("ps: " + f.getPSName());
return createFont("Lucida Sans", size, true, null);
}
public PFont createFont(String name, float size) {
return createFont(name, size, true, null);
}
public PFont createFont(String name, float size, boolean smooth) {
return createFont(name, size, smooth, null);
}
/**
* ( begin auto-generated from createFont.xml )
*
* Dynamically converts a font to the format used by Processing from either
* a font name that's installed on the computer, or from a .ttf or .otf
* file inside the sketches "data" folder. This function is an advanced
* feature for precise control. On most occasions you should create fonts
* through selecting "Create Font..." from the Tools menu.
* <br /><br />
* Use the <b>PFont.list()</b> method to first determine the names for the
* fonts recognized by the computer and are compatible with this function.
* Because of limitations in Java, not all fonts can be used and some might
* work with one operating system and not others. When sharing a sketch
* with other people or posting it on the web, you may need to include a
* .ttf or .otf version of your font in the data directory of the sketch
* because other people might not have the font installed on their
* computer. Only fonts that can legally be distributed should be included
* with a sketch.
* <br /><br />
* The <b>size</b> parameter states the font size you want to generate. The
* <b>smooth</b> parameter specifies if the font should be antialiased or
* not, and the <b>charset</b> parameter is an array of chars that
* specifies the characters to generate.
* <br /><br />
* This function creates a bitmapped version of a font in the same manner
* as the Create Font tool. It loads a font by name, and converts it to a
* series of images based on the size of the font. When possible, the
* <b>text()</b> function will use a native font rather than the bitmapped
* version created behind the scenes with <b>createFont()</b>. For
* instance, when using P2D, the actual native version of the font will be
* employed by the sketch, improving drawing quality and performance. With
* the P3D renderer, the bitmapped version will be used. While this can
* drastically improve speed and appearance, results are poor when
* exporting if the sketch does not include the .otf or .ttf file, and the
* requested font is not available on the machine running the sketch.
*
* ( end auto-generated )
* @webref typography:loading_displaying
* @param name name of the font to load
* @param size point size of the font
* @param smooth true for an antialiased font, false for aliased
* @param charset array containing characters to be generated
* @see PFont#PFont
* @see PGraphics#textFont(PFont, float)
* @see PGraphics#text(String, float, float, float, float, float)
* @see PApplet#loadFont(String)
*/
public PFont createFont(String name, float size,
boolean smooth, char charset[]) {
String lowerName = name.toLowerCase();
Font baseFont = null;
try {
InputStream stream = null;
if (lowerName.endsWith(".otf") || lowerName.endsWith(".ttf")) {
stream = createInput(name);
if (stream == null) {
System.err.println("The font \"" + name + "\" " +
"is missing or inaccessible, make sure " +
"the URL is valid or that the file has been " +
"added to your sketch and is readable.");
return null;
}
baseFont = Font.createFont(Font.TRUETYPE_FONT, createInput(name));
} else {
baseFont = PFont.findFont(name);
}
return new PFont(baseFont.deriveFont(size), smooth, charset,
stream != null);
} catch (Exception e) {
System.err.println("Problem createFont(" + name + ")");
e.printStackTrace();
return null;
}
}
//////////////////////////////////////////////////////////////
// FILE/FOLDER SELECTION
private Frame selectFrame;
private Frame selectFrame() {
if (frame != null) {
selectFrame = frame;
} else if (selectFrame == null) {
Component comp = getParent();
while (comp != null) {
if (comp instanceof Frame) {
selectFrame = (Frame) comp;
break;
}
comp = comp.getParent();
}
// Who you callin' a hack?
if (selectFrame == null) {
selectFrame = new Frame();
}
}
return selectFrame;
}
/**
* Open a platform-specific file chooser dialog to select a file for input.
* After the selection is made, the selected File will be passed to the
* 'callback' function. If the dialog is closed or canceled, null will be
* sent to the function, so that the program is not waiting for additional
* input. The callback is necessary because of how threading works.
*
* <pre>
* void setup() {
* selectInput("Select a file to process:", "fileSelected");
* }
*
* void fileSelected(File selection) {
* if (selection == null) {
* println("Window was closed or the user hit cancel.");
* } else {
* println("User selected " + fileSeleted.getAbsolutePath());
* }
* }
* </pre>
*
* For advanced users, the method must be 'public', which is true for all
* methods inside a sketch when run from the PDE, but must explicitly be
* set when using Eclipse or other development environments.
*
* @webref input:files
* @param prompt message to the user
* @param callback name of the method to be called when the selection is made
*/
public void selectInput(String prompt, String callback) {
selectInput(prompt, callback, null);
}
public void selectInput(String prompt, String callback, File file) {
selectInput(prompt, callback, file, this);
}
public void selectInput(String prompt, String callback,
File file, Object callbackObject) {
selectInput(prompt, callback, file, callbackObject, selectFrame());
}
static public void selectInput(String prompt, String callbackMethod,
File file, Object callbackObject, Frame parent) {
selectImpl(prompt, callbackMethod, file, callbackObject, parent, FileDialog.LOAD);
}
/**
* See selectInput() for details.
*
* @webref output:files
* @param prompt message to the user
* @param callback name of the method to be called when the selection is made
*/
public void selectOutput(String prompt, String callback) {
selectOutput(prompt, callback, null);
}
public void selectOutput(String prompt, String callback, File file) {
selectOutput(prompt, callback, file, this);
}
public void selectOutput(String prompt, String callback,
File file, Object callbackObject) {
selectOutput(prompt, callback, file, callbackObject, selectFrame());
}
static public void selectOutput(String prompt, String callbackMethod,
File file, Object callbackObject, Frame parent) {
selectImpl(prompt, callbackMethod, file, callbackObject, parent, FileDialog.SAVE);
}
static protected void selectImpl(final String prompt,
final String callbackMethod,
final File defaultSelection,
final Object callbackObject,
final Frame parentFrame,
final int mode) {
EventQueue.invokeLater(new Runnable() {
public void run() {
File selectedFile = null;
if (useNativeSelect) {
FileDialog dialog = new FileDialog(parentFrame, prompt, mode);
if (defaultSelection != null) {
dialog.setDirectory(defaultSelection.getParent());
dialog.setFile(defaultSelection.getName());
}
dialog.setVisible(true);
String directory = dialog.getDirectory();
String filename = dialog.getFile();
if (filename != null) {
selectedFile = new File(directory, filename);
}
} else {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle(prompt);
if (defaultSelection != null) {
chooser.setSelectedFile(defaultSelection);
}
int result = -1;
if (mode == FileDialog.SAVE) {
result = chooser.showSaveDialog(parentFrame);
} else if (mode == FileDialog.LOAD) {
result = chooser.showOpenDialog(parentFrame);
}
if (result == JFileChooser.APPROVE_OPTION) {
selectedFile = chooser.getSelectedFile();
}
}
selectCallback(selectedFile, callbackMethod, callbackObject);
}
});
}
/**
* See selectInput() for details.
*
* @webref input:files
* @param prompt message to the user
* @param callback name of the method to be called when the selection is made
*/
public void selectFolder(String prompt, String callback) {
selectFolder(prompt, callback, null);
}
public void selectFolder(String prompt, String callback, File file) {
selectFolder(prompt, callback, file, this);
}
public void selectFolder(String prompt, String callback,
File file, Object callbackObject) {
selectFolder(prompt, callback, file, callbackObject, selectFrame());
}
static public void selectFolder(final String prompt,
final String callbackMethod,
final File defaultSelection,
final Object callbackObject,
final Frame parentFrame) {
EventQueue.invokeLater(new Runnable() {
public void run() {
File selectedFile = null;
if (platform == MACOSX && useNativeSelect != false) {
FileDialog fileDialog =
new FileDialog(parentFrame, prompt, FileDialog.LOAD);
System.setProperty("apple.awt.fileDialogForDirectories", "true");
fileDialog.setVisible(true);
System.setProperty("apple.awt.fileDialogForDirectories", "false");
String filename = fileDialog.getFile();
if (filename != null) {
selectedFile = new File(fileDialog.getDirectory(), fileDialog.getFile());
}
} else {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle(prompt);
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (defaultSelection != null) {
fileChooser.setSelectedFile(defaultSelection);
}
int result = fileChooser.showOpenDialog(parentFrame);
if (result == JFileChooser.APPROVE_OPTION) {
selectedFile = fileChooser.getSelectedFile();
}
}
selectCallback(selectedFile, callbackMethod, callbackObject);
}
});
}
static private void selectCallback(File selectedFile,
String callbackMethod,
Object callbackObject) {
try {
Class<?> callbackClass = callbackObject.getClass();
Method selectMethod =
callbackClass.getMethod(callbackMethod, new Class[] { File.class });
selectMethod.invoke(callbackObject, new Object[] { selectedFile });
} catch (IllegalAccessException iae) {
System.err.println(callbackMethod + "() must be public");
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (NoSuchMethodException nsme) {
System.err.println(callbackMethod + "() could not be found");
}
}
//////////////////////////////////////////////////////////////
// READERS AND WRITERS
/**
* ( begin auto-generated from createReader.xml )
*
* Creates a <b>BufferedReader</b> object that can be used to read files
* line-by-line as individual <b>String</b> objects. This is the complement
* to the <b>createWriter()</b> function.
* <br/> <br/>
* Starting with Processing release 0134, all files loaded and saved by the
* Processing API use UTF-8 encoding. In previous releases, the default
* encoding for your platform was used, which causes problems when files
* are moved to other platforms.
*
* ( end auto-generated )
* @webref input:files
* @param filename name of the file to be opened
* @see BufferedReader
* @see PApplet#createWriter(String)
* @see PrintWriter
*/
public BufferedReader createReader(String filename) {
try {
InputStream is = createInput(filename);
if (is == null) {
System.err.println(filename + " does not exist or could not be read");
return null;
}
return createReader(is);
} catch (Exception e) {
if (filename == null) {
System.err.println("Filename passed to reader() was null");
} else {
System.err.println("Couldn't create a reader for " + filename);
}
}
return null;
}
/**
* @nowebref
*/
static public BufferedReader createReader(File file) {
try {
InputStream is = new FileInputStream(file);
if (file.getName().toLowerCase().endsWith(".gz")) {
is = new GZIPInputStream(is);
}
return createReader(is);
} catch (Exception e) {
if (file == null) {
throw new RuntimeException("File passed to createReader() was null");
} else {
e.printStackTrace();
throw new RuntimeException("Couldn't create a reader for " +
file.getAbsolutePath());
}
}
//return null;
}
/**
* @nowebref
* I want to read lines from a stream. If I have to type the
* following lines any more I'm gonna send Sun my medical bills.
*/
static public BufferedReader createReader(InputStream input) {
InputStreamReader isr = null;
try {
isr = new InputStreamReader(input, "UTF-8");
} catch (UnsupportedEncodingException e) { } // not gonna happen
return new BufferedReader(isr);
}
/**
* ( begin auto-generated from createWriter.xml )
*
* Creates a new file in the sketch folder, and a <b>PrintWriter</b> object
* to write to it. For the file to be made correctly, it should be flushed
* and must be closed with its <b>flush()</b> and <b>close()</b> methods
* (see above example).
* <br/> <br/>
* Starting with Processing release 0134, all files loaded and saved by the
* Processing API use UTF-8 encoding. In previous releases, the default
* encoding for your platform was used, which causes problems when files
* are moved to other platforms.
*
* ( end auto-generated )
*
* @webref output:files
* @param filename name of the file to be created
* @see PrintWriter
* @see PApplet#createReader
* @see BufferedReader
*/
public PrintWriter createWriter(String filename) {
return createWriter(saveFile(filename));
}
/**
* @nowebref
* I want to print lines to a file. I have RSI from typing these
* eight lines of code so many times.
*/
static public PrintWriter createWriter(File file) {
try {
createPath(file); // make sure in-between folders exist
OutputStream output = new FileOutputStream(file);
if (file.getName().toLowerCase().endsWith(".gz")) {
output = new GZIPOutputStream(output);
}
return createWriter(output);
} catch (Exception e) {
if (file == null) {
throw new RuntimeException("File passed to createWriter() was null");
} else {
e.printStackTrace();
throw new RuntimeException("Couldn't create a writer for " +
file.getAbsolutePath());
}
}
//return null;
}
/**
* @nowebref
* I want to print lines to a file. Why am I always explaining myself?
* It's the JavaSoft API engineers who need to explain themselves.
*/
static public PrintWriter createWriter(OutputStream output) {
try {
BufferedOutputStream bos = new BufferedOutputStream(output, 8192);
OutputStreamWriter osw = new OutputStreamWriter(bos, "UTF-8");
return new PrintWriter(osw);
} catch (UnsupportedEncodingException e) { } // not gonna happen
return null;
}
//////////////////////////////////////////////////////////////
// FILE INPUT
/**
* @deprecated As of release 0136, use createInput() instead.
*/
public InputStream openStream(String filename) {
return createInput(filename);
}
/**
* ( begin auto-generated from createInput.xml )
*
* This is a function for advanced programmers to open a Java InputStream.
* It's useful if you want to use the facilities provided by PApplet to
* easily open files from the data folder or from a URL, but want an
* InputStream object so that you can use other parts of Java to take more
* control of how the stream is read.<br />
* <br />
* The filename passed in can be:<br />
* - A URL, for instance <b>openStream("http://processing.org/")</b><br />
* - A file in the sketch's <b>data</b> folder<br />
* - The full path to a file to be opened locally (when running as an
* application)<br />
* <br />
* If the requested item doesn't exist, null is returned. If not online,
* this will also check to see if the user is asking for a file whose name
* isn't properly capitalized. If capitalization is different, an error
* will be printed to the console. This helps prevent issues that appear
* when a sketch is exported to the web, where case sensitivity matters, as
* opposed to running from inside the Processing Development Environment on
* Windows or Mac OS, where case sensitivity is preserved but ignored.<br />
* <br />
* If the file ends with <b>.gz</b>, the stream will automatically be gzip
* decompressed. If you don't want the automatic decompression, use the
* related function <b>createInputRaw()</b>.
* <br />
* In earlier releases, this function was called <b>openStream()</b>.<br />
* <br />
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Simplified method to open a Java InputStream.
* <p>
* This method is useful if you want to use the facilities provided
* by PApplet to easily open things from the data folder or from a URL,
* but want an InputStream object so that you can use other Java
* methods to take more control of how the stream is read.
* <p>
* If the requested item doesn't exist, null is returned.
* (Prior to 0096, die() would be called, killing the applet)
* <p>
* For 0096+, the "data" folder is exported intact with subfolders,
* and openStream() properly handles subdirectories from the data folder
* <p>
* If not online, this will also check to see if the user is asking
* for a file whose name isn't properly capitalized. This helps prevent
* issues when a sketch is exported to the web, where case sensitivity
* matters, as opposed to Windows and the Mac OS default where
* case sensitivity is preserved but ignored.
* <p>
* It is strongly recommended that libraries use this method to open
* data files, so that the loading sequence is handled in the same way
* as functions like loadBytes(), loadImage(), etc.
* <p>
* The filename passed in can be:
* <UL>
* <LI>A URL, for instance openStream("http://processing.org/");
* <LI>A file in the sketch's data folder
* <LI>Another file to be opened locally (when running as an application)
* </UL>
*
* @webref input:files
* @param filename the name of the file to use as input
* @see PApplet#createOutput(String)
* @see PApplet#selectOutput(String)
* @see PApplet#selectInput(String)
*
*/
public InputStream createInput(String filename) {
InputStream input = createInputRaw(filename);
if ((input != null) && filename.toLowerCase().endsWith(".gz")) {
try {
return new GZIPInputStream(input);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
return input;
}
/**
* Call openStream() without automatic gzip decompression.
*/
public InputStream createInputRaw(String filename) {
InputStream stream = null;
if (filename == null) return null;
if (filename.length() == 0) {
// an error will be called by the parent function
//System.err.println("The filename passed to openStream() was empty.");
return null;
}
// safe to check for this as a url first. this will prevent online
// access logs from being spammed with GET /sketchfolder/http://blahblah
if (filename.contains(":")) { // at least smells like URL
try {
URL url = new URL(filename);
stream = url.openStream();
return stream;
} catch (MalformedURLException mfue) {
// not a url, that's fine
} catch (FileNotFoundException fnfe) {
// Java 1.5 likes to throw this when URL not available. (fix for 0119)
// http://dev.processing.org/bugs/show_bug.cgi?id=403
} catch (IOException e) {
// changed for 0117, shouldn't be throwing exception
e.printStackTrace();
//System.err.println("Error downloading from URL " + filename);
return null;
//throw new RuntimeException("Error downloading from URL " + filename);
}
}
// Moved this earlier than the getResourceAsStream() checks, because
// calling getResourceAsStream() on a directory lists its contents.
// http://dev.processing.org/bugs/show_bug.cgi?id=716
try {
// First see if it's in a data folder. This may fail by throwing
// a SecurityException. If so, this whole block will be skipped.
File file = new File(dataPath(filename));
if (!file.exists()) {
// next see if it's just in the sketch folder
file = new File(sketchPath, filename);
}
if (file.isDirectory()) {
return null;
}
if (file.exists()) {
try {
// handle case sensitivity check
String filePath = file.getCanonicalPath();
String filenameActual = new File(filePath).getName();
// make sure there isn't a subfolder prepended to the name
String filenameShort = new File(filename).getName();
// if the actual filename is the same, but capitalized
// differently, warn the user.
//if (filenameActual.equalsIgnoreCase(filenameShort) &&
//!filenameActual.equals(filenameShort)) {
if (!filenameActual.equals(filenameShort)) {
throw new RuntimeException("This file is named " +
filenameActual + " not " +
filename + ". Rename the file " +
"or change your code.");
}
} catch (IOException e) { }
}
// if this file is ok, may as well just load it
stream = new FileInputStream(file);
if (stream != null) return stream;
// have to break these out because a general Exception might
// catch the RuntimeException being thrown above
} catch (IOException ioe) {
} catch (SecurityException se) { }
// Using getClassLoader() prevents java from converting dots
// to slashes or requiring a slash at the beginning.
// (a slash as a prefix means that it'll load from the root of
// the jar, rather than trying to dig into the package location)
ClassLoader cl = getClass().getClassLoader();
// by default, data files are exported to the root path of the jar.
// (not the data folder) so check there first.
stream = cl.getResourceAsStream("data/" + filename);
if (stream != null) {
String cn = stream.getClass().getName();
// this is an irritation of sun's java plug-in, which will return
// a non-null stream for an object that doesn't exist. like all good
// things, this is probably introduced in java 1.5. awesome!
// http://dev.processing.org/bugs/show_bug.cgi?id=359
if (!cn.equals("sun.plugin.cache.EmptyInputStream")) {
return stream;
}
}
// When used with an online script, also need to check without the
// data folder, in case it's not in a subfolder called 'data'.
// http://dev.processing.org/bugs/show_bug.cgi?id=389
stream = cl.getResourceAsStream(filename);
if (stream != null) {
String cn = stream.getClass().getName();
if (!cn.equals("sun.plugin.cache.EmptyInputStream")) {
return stream;
}
}
// Finally, something special for the Internet Explorer users. Turns out
// that we can't get files that are part of the same folder using the
// methods above when using IE, so we have to resort to the old skool
// getDocumentBase() from teh applet dayz. 1996, my brotha.
try {
URL base = getDocumentBase();
if (base != null) {
URL url = new URL(base, filename);
URLConnection conn = url.openConnection();
return conn.getInputStream();
// if (conn instanceof HttpURLConnection) {
// HttpURLConnection httpConnection = (HttpURLConnection) conn;
// // test for 401 result (HTTP only)
// int responseCode = httpConnection.getResponseCode();
// }
}
} catch (Exception e) { } // IO or NPE or...
// Now try it with a 'data' subfolder. getting kinda desperate for data...
try {
URL base = getDocumentBase();
if (base != null) {
URL url = new URL(base, "data/" + filename);
URLConnection conn = url.openConnection();
return conn.getInputStream();
}
} catch (Exception e) { }
try {
// attempt to load from a local file, used when running as
// an application, or as a signed applet
try { // first try to catch any security exceptions
try {
stream = new FileInputStream(dataPath(filename));
if (stream != null) return stream;
} catch (IOException e2) { }
try {
stream = new FileInputStream(sketchPath(filename));
if (stream != null) return stream;
} catch (Exception e) { } // ignored
try {
stream = new FileInputStream(filename);
if (stream != null) return stream;
} catch (IOException e1) { }
} catch (SecurityException se) { } // online, whups
} catch (Exception e) {
//die(e.getMessage(), e);
e.printStackTrace();
}
return null;
}
/**
* @nowebref
*/
static public InputStream createInput(File file) {
if (file == null) {
throw new IllegalArgumentException("File passed to createInput() was null");
}
try {
InputStream input = new FileInputStream(file);
if (file.getName().toLowerCase().endsWith(".gz")) {
return new GZIPInputStream(input);
}
return input;
} catch (IOException e) {
System.err.println("Could not createInput() for " + file);
e.printStackTrace();
return null;
}
}
/**
* ( begin auto-generated from loadBytes.xml )
*
* Reads the contents of a file or url and places it in a byte array. If a
* file is specified, it must be located in the sketch's "data"
* directory/folder.<br />
* <br />
* The filename parameter can also be a URL to a file found online. For
* security reasons, a Processing sketch found online can only download
* files from the same server from which it came. Getting around this
* restriction requires a <a
* href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</a>.
*
* ( end auto-generated )
* @webref input:files
* @param filename name of a file in the data folder or a URL.
* @see PApplet#loadStrings(String)
* @see PApplet#saveStrings(String, String[])
* @see PApplet#saveBytes(String, byte[])
*
*/
public byte[] loadBytes(String filename) {
InputStream is = createInput(filename);
if (is != null) {
byte[] outgoing = loadBytes(is);
try {
is.close();
} catch (IOException e) {
e.printStackTrace(); // shouldn't happen
}
return outgoing;
}
System.err.println("The file \"" + filename + "\" " +
"is missing or inaccessible, make sure " +
"the URL is valid or that the file has been " +
"added to your sketch and is readable.");
return null;
}
/**
* @nowebref
*/
static public byte[] loadBytes(InputStream input) {
try {
BufferedInputStream bis = new BufferedInputStream(input);
ByteArrayOutputStream out = new ByteArrayOutputStream();
int c = bis.read();
while (c != -1) {
out.write(c);
c = bis.read();
}
return out.toByteArray();
} catch (IOException e) {
e.printStackTrace();
//throw new RuntimeException("Couldn't load bytes from stream");
}
return null;
}
/**
* @nowebref
*/
static public byte[] loadBytes(File file) {
InputStream is = createInput(file);
return loadBytes(is);
}
/**
* @nowebref
*/
static public String[] loadStrings(File file) {
InputStream is = createInput(file);
if (is != null) {
String[] outgoing = loadStrings(is);
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return outgoing;
}
return null;
}
/**
* ( begin auto-generated from loadStrings.xml )
*
* Reads the contents of a file or url and creates a String array of its
* individual lines. If a file is specified, it must be located in the
* sketch's "data" directory/folder.<br />
* <br />
* The filename parameter can also be a URL to a file found online. For
* security reasons, a Processing sketch found online can only download
* files from the same server from which it came. Getting around this
* restriction requires a <a
* href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</a>.
* <br />
* If the file is not available or an error occurs, <b>null</b> will be
* returned and an error message will be printed to the console. The error
* message does not halt the program, however the null value may cause a
* NullPointerException if your code does not check whether the value
* returned is null.
* <br/> <br/>
* Starting with Processing release 0134, all files loaded and saved by the
* Processing API use UTF-8 encoding. In previous releases, the default
* encoding for your platform was used, which causes problems when files
* are moved to other platforms.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Load data from a file and shove it into a String array.
* <p>
* Exceptions are handled internally, when an error, occurs, an
* exception is printed to the console and 'null' is returned,
* but the program continues running. This is a tradeoff between
* 1) showing the user that there was a problem but 2) not requiring
* that all i/o code is contained in try/catch blocks, for the sake
* of new users (or people who are just trying to get things done
* in a "scripting" fashion. If you want to handle exceptions,
* use Java methods for I/O.
*
* @webref input:files
* @param filename name of the file or url to load
* @see PApplet#loadBytes(String)
* @see PApplet#saveStrings(String, String[])
* @see PApplet#saveBytes(String, byte[])
*/
public String[] loadStrings(String filename) {
InputStream is = createInput(filename);
if (is != null) return loadStrings(is);
System.err.println("The file \"" + filename + "\" " +
"is missing or inaccessible, make sure " +
"the URL is valid or that the file has been " +
"added to your sketch and is readable.");
return null;
}
/**
* @nowebref
*/
static public String[] loadStrings(InputStream input) {
try {
BufferedReader reader =
new BufferedReader(new InputStreamReader(input, "UTF-8"));
return loadStrings(reader);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
static public String[] loadStrings(BufferedReader reader) {
try {
String lines[] = new String[100];
int lineCount = 0;
String line = null;
while ((line = reader.readLine()) != null) {
if (lineCount == lines.length) {
String temp[] = new String[lineCount << 1];
System.arraycopy(lines, 0, temp, 0, lineCount);
lines = temp;
}
lines[lineCount++] = line;
}
reader.close();
if (lineCount == lines.length) {
return lines;
}
// resize array to appropriate amount for these lines
String output[] = new String[lineCount];
System.arraycopy(lines, 0, output, 0, lineCount);
return output;
} catch (IOException e) {
e.printStackTrace();
//throw new RuntimeException("Error inside loadStrings()");
}
return null;
}
//////////////////////////////////////////////////////////////
// FILE OUTPUT
/**
* ( begin auto-generated from createOutput.xml )
*
* Similar to <b>createInput()</b>, this creates a Java <b>OutputStream</b>
* for a given filename or path. The file will be created in the sketch
* folder, or in the same folder as an exported application.
* <br /><br />
* If the path does not exist, intermediate folders will be created. If an
* exception occurs, it will be printed to the console, and <b>null</b>
* will be returned.
* <br /><br />
* This function is a convenience over the Java approach that requires you
* to 1) create a FileOutputStream object, 2) determine the exact file
* location, and 3) handle exceptions. Exceptions are handled internally by
* the function, which is more appropriate for "sketch" projects.
* <br /><br />
* If the output filename ends with <b>.gz</b>, the output will be
* automatically GZIP compressed as it is written.
*
* ( end auto-generated )
* @webref output:files
* @param filename name of the file to open
* @see PApplet#createInput(String)
* @see PApplet#selectOutput()
*/
public OutputStream createOutput(String filename) {
return createOutput(saveFile(filename));
}
/**
* @nowebref
*/
static public OutputStream createOutput(File file) {
try {
createPath(file); // make sure the path exists
FileOutputStream fos = new FileOutputStream(file);
if (file.getName().toLowerCase().endsWith(".gz")) {
return new GZIPOutputStream(fos);
}
return fos;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* ( begin auto-generated from saveStream.xml )
*
* Save the contents of a stream to a file in the sketch folder. This is
* basically <b>saveBytes(blah, loadBytes())</b>, but done more efficiently
* (and with less confusing syntax).<br />
* <br />
* When using the <b>targetFile</b> parameter, it writes to a <b>File</b>
* object for greater control over the file location. (Note that unlike
* some other functions, this will not automatically compress or uncompress
* gzip files.)
*
* ( end auto-generated )
*
* @webref output:files
* @param target name of the file to write to
* @param source location to read from (a filename, path, or URL)
* @see PApplet#createOutput(String)
*/
public boolean saveStream(String target, String source) {
return saveStream(saveFile(target), source);
}
/**
* Identical to the other saveStream(), but writes to a File
* object, for greater control over the file location.
* <p/>
* Note that unlike other api methods, this will not automatically
* compress or uncompress gzip files.
*/
public boolean saveStream(File target, String source) {
return saveStream(target, createInputRaw(source));
}
/**
* @nowebref
*/
public boolean saveStream(String target, InputStream source) {
return saveStream(saveFile(target), source);
}
/**
* @nowebref
*/
static public boolean saveStream(File target, InputStream source) {
File tempFile = null;
try {
File parentDir = target.getParentFile();
// make sure that this path actually exists before writing
createPath(target);
tempFile = File.createTempFile(target.getName(), null, parentDir);
FileOutputStream targetStream = new FileOutputStream(tempFile);
saveStream(targetStream, source);
targetStream.close();
targetStream = null;
if (target.exists()) {
if (!target.delete()) {
System.err.println("Could not replace " +
target.getAbsolutePath() + ".");
}
}
if (!tempFile.renameTo(target)) {
System.err.println("Could not rename temporary file " +
tempFile.getAbsolutePath());
return false;
}
return true;
} catch (IOException e) {
if (tempFile != null) {
tempFile.delete();
}
e.printStackTrace();
return false;
}
}
/**
* @nowebref
*/
static public void saveStream(OutputStream target,
InputStream source) throws IOException {
BufferedInputStream bis = new BufferedInputStream(source, 16384);
BufferedOutputStream bos = new BufferedOutputStream(target);
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = bis.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.flush();
}
/**
* ( begin auto-generated from saveBytes.xml )
*
* Opposite of <b>loadBytes()</b>, will write an entire array of bytes to a
* file. The data is saved in binary format. This file is saved to the
* sketch's folder, which is opened by selecting "Show sketch folder" from
* the "Sketch" menu.<br />
* <br />
* It is not possible to use saveXxxxx() functions inside a web browser
* unless the sketch is <a
* href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</A>. To
* save a file back to a server, see the <a
* href="http://wiki.processing.org/w/Saving_files_to_a_web-server">save to
* web</A> code snippet on the Processing Wiki.
*
* ( end auto-generated )
*
* @webref output:files
* @param filename name of the file to write to
* @param data array of bytes to be written
* @see PApplet#loadStrings(String)
* @see PApplet#loadBytes(String)
* @see PApplet#saveStrings(String, String[])
*/
public void saveBytes(String filename, byte[] data) {
saveBytes(saveFile(filename), data);
}
/**
* @nowebref
* Saves bytes to a specific File location specified by the user.
*/
static public void saveBytes(File file, byte[] data) {
File tempFile = null;
try {
File parentDir = file.getParentFile();
tempFile = File.createTempFile(file.getName(), null, parentDir);
OutputStream output = createOutput(tempFile);
saveBytes(output, data);
output.close();
output = null;
if (file.exists()) {
if (!file.delete()) {
System.err.println("Could not replace " + file.getAbsolutePath());
}
}
if (!tempFile.renameTo(file)) {
System.err.println("Could not rename temporary file " +
tempFile.getAbsolutePath());
}
} catch (IOException e) {
System.err.println("error saving bytes to " + file);
if (tempFile != null) {
tempFile.delete();
}
e.printStackTrace();
}
}
/**
* @nowebref
* Spews a buffer of bytes to an OutputStream.
*/
static public void saveBytes(OutputStream output, byte[] data) {
try {
output.write(data);
output.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
//
/**
* ( begin auto-generated from saveStrings.xml )
*
* Writes an array of strings to a file, one line per string. This file is
* saved to the sketch's folder, which is opened by selecting "Show sketch
* folder" from the "Sketch" menu.<br />
* <br />
* It is not possible to use saveXxxxx() functions inside a web browser
* unless the sketch is <a
* href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</A>. To
* save a file back to a server, see the <a
* href="http://wiki.processing.org/w/Saving_files_to_a_web-server">save to
* web</A> code snippet on the Processing Wiki.<br/>
* <br/ >
* Starting with Processing 1.0, all files loaded and saved by the
* Processing API use UTF-8 encoding. In previous releases, the default
* encoding for your platform was used, which causes problems when files
* are moved to other platforms.
*
* ( end auto-generated )
* @webref output:files
* @param filename filename for output
* @param data string array to be written
* @see PApplet#loadStrings(String)
* @see PApplet#loadBytes(String)
* @see PApplet#saveBytes(String, byte[])
*/
public void saveStrings(String filename, String data[]) {
saveStrings(saveFile(filename), data);
}
/**
* @nowebref
*/
static public void saveStrings(File file, String data[]) {
saveStrings(createOutput(file), data);
}
/**
* @nowebref
*/
static public void saveStrings(OutputStream output, String[] data) {
PrintWriter writer = createWriter(output);
for (int i = 0; i < data.length; i++) {
writer.println(data[i]);
}
writer.flush();
writer.close();
}
//////////////////////////////////////////////////////////////
/**
* Prepend the sketch folder path to the filename (or path) that is
* passed in. External libraries should use this function to save to
* the sketch folder.
* <p/>
* Note that when running as an applet inside a web browser,
* the sketchPath will be set to null, because security restrictions
* prevent applets from accessing that information.
* <p/>
* This will also cause an error if the sketch is not inited properly,
* meaning that init() was never called on the PApplet when hosted
* my some other main() or by other code. For proper use of init(),
* see the examples in the main description text for PApplet.
*/
public String sketchPath(String where) {
if (sketchPath == null) {
return where;
// throw new RuntimeException("The applet was not inited properly, " +
// "or security restrictions prevented " +
// "it from determining its path.");
}
// isAbsolute() could throw an access exception, but so will writing
// to the local disk using the sketch path, so this is safe here.
// for 0120, added a try/catch anyways.
try {
if (new File(where).isAbsolute()) return where;
} catch (Exception e) { }
return sketchPath + File.separator + where;
}
public File sketchFile(String where) {
return new File(sketchPath(where));
}
/**
* Returns a path inside the applet folder to save to. Like sketchPath(),
* but creates any in-between folders so that things save properly.
* <p/>
* All saveXxxx() functions use the path to the sketch folder, rather than
* its data folder. Once exported, the data folder will be found inside the
* jar file of the exported application or applet. In this case, it's not
* possible to save data into the jar file, because it will often be running
* from a server, or marked in-use if running from a local file system.
* With this in mind, saving to the data path doesn't make sense anyway.
* If you know you're running locally, and want to save to the data folder,
* use <TT>saveXxxx("data/blah.dat")</TT>.
*/
public String savePath(String where) {
if (where == null) return null;
String filename = sketchPath(where);
createPath(filename);
return filename;
}
/**
* Identical to savePath(), but returns a File object.
*/
public File saveFile(String where) {
return new File(savePath(where));
}
/**
* Return a full path to an item in the data folder.
* <p>
* This is only available with applications, not applets or Android.
* On Windows and Linux, this is simply the data folder, which is located
* in the same directory as the EXE file and lib folders. On Mac OS X, this
* is a path to the data folder buried inside Contents/Resources/Java.
* For the latter point, that also means that the data folder should not be
* considered writable. Use sketchPath() for now, or inputPath() and
* outputPath() once they're available in the 2.0 release.
* <p>
* dataPath() is not supported with applets because applets have their data
* folder wrapped into the JAR file. To read data from the data folder that
* works with an applet, you should use other methods such as createInput(),
* createReader(), or loadStrings().
*/
public String dataPath(String where) {
return dataFile(where).getAbsolutePath();
}
/**
* Return a full path to an item in the data folder as a File object.
* See the dataPath() method for more information.
*/
public File dataFile(String where) {
// isAbsolute() could throw an access exception, but so will writing
// to the local disk using the sketch path, so this is safe here.
File why = new File(where);
if (why.isAbsolute()) return why;
String jarPath =
getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
if (jarPath.contains("Contents/Resources/Java/")) {
// The path will be URL encoded (%20 for spaces) coming from above
// http://code.google.com/p/processing/issues/detail?id=1073
File containingFolder = new File(urlDecode(jarPath)).getParentFile();
File dataFolder = new File(containingFolder, "data");
return new File(dataFolder, where);
}
// Windows, Linux, or when not using a Mac OS X .app file
return new File(sketchPath + File.separator + "data" + File.separator + where);
}
/**
* On Windows and Linux, this is simply the data folder. On Mac OS X, this is
* the path to the data folder buried inside Contents/Resources/Java
*/
// public File inputFile(String where) {
// }
// public String inputPath(String where) {
// }
/**
* Takes a path and creates any in-between folders if they don't
* already exist. Useful when trying to save to a subfolder that
* may not actually exist.
*/
static public void createPath(String path) {
createPath(new File(path));
}
static public void createPath(File file) {
try {
String parent = file.getParent();
if (parent != null) {
File unit = new File(parent);
if (!unit.exists()) unit.mkdirs();
}
} catch (SecurityException se) {
System.err.println("You don't have permissions to create " +
file.getAbsolutePath());
}
}
static public String getExtension(String filename) {
String extension;
String lower = filename.toLowerCase();
int dot = filename.lastIndexOf('.');
if (dot == -1) {
extension = "unknown"; // no extension found
}
extension = lower.substring(dot + 1);
// check for, and strip any parameters on the url, i.e.
// filename.jpg?blah=blah&something=that
int question = extension.indexOf('?');
if (question != -1) {
extension = extension.substring(0, question);
}
return extension;
}
//////////////////////////////////////////////////////////////
// URL ENCODING
static public String urlEncode(String str) {
try {
return URLEncoder.encode(str, "UTF-8");
} catch (UnsupportedEncodingException e) { // oh c'mon
return null;
}
}
static public String urlDecode(String str) {
try {
return URLDecoder.decode(str, "UTF-8");
} catch (UnsupportedEncodingException e) { // safe per the JDK source
return null;
}
}
//////////////////////////////////////////////////////////////
// SORT
/**
* ( begin auto-generated from sort.xml )
*
* Sorts an array of numbers from smallest to largest and puts an array of
* words in alphabetical order. The original array is not modified, a
* re-ordered array is returned. The <b>count</b> parameter states the
* number of elements to sort. For example if there are 12 elements in an
* array and if count is the value 5, only the first five elements on the
* array will be sorted. <!--As of release 0126, the alphabetical ordering
* is case insensitive.-->
*
* ( end auto-generated )
* @webref data:array_functions
* @param list array to sort
* @see PApplet#reverse(boolean[])
*/
static public byte[] sort(byte list[]) {
return sort(list, list.length);
}
/**
* @param count number of elements to sort, starting from 0
*/
static public byte[] sort(byte[] list, int count) {
byte[] outgoing = new byte[list.length];
System.arraycopy(list, 0, outgoing, 0, list.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public char[] sort(char list[]) {
return sort(list, list.length);
}
static public char[] sort(char[] list, int count) {
char[] outgoing = new char[list.length];
System.arraycopy(list, 0, outgoing, 0, list.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public int[] sort(int list[]) {
return sort(list, list.length);
}
static public int[] sort(int[] list, int count) {
int[] outgoing = new int[list.length];
System.arraycopy(list, 0, outgoing, 0, list.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public float[] sort(float list[]) {
return sort(list, list.length);
}
static public float[] sort(float[] list, int count) {
float[] outgoing = new float[list.length];
System.arraycopy(list, 0, outgoing, 0, list.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
static public String[] sort(String list[]) {
return sort(list, list.length);
}
static public String[] sort(String[] list, int count) {
String[] outgoing = new String[list.length];
System.arraycopy(list, 0, outgoing, 0, list.length);
Arrays.sort(outgoing, 0, count);
return outgoing;
}
//////////////////////////////////////////////////////////////
// ARRAY UTILITIES
/**
* ( begin auto-generated from arrayCopy.xml )
*
* Copies an array (or part of an array) to another array. The <b>src</b>
* array is copied to the <b>dst</b> array, beginning at the position
* specified by <b>srcPos</b> and into the position specified by
* <b>dstPos</b>. The number of elements to copy is determined by
* <b>length</b>. The simplified version with two arguments copies an
* entire array to another of the same size. It is equivalent to
* "arrayCopy(src, 0, dst, 0, src.length)". This function is far more
* efficient for copying array data than iterating through a <b>for</b> and
* copying each element.
*
* ( end auto-generated )
* @webref data:array_functions
* @param src the source array
* @param srcPosition starting position in the source array
* @param dst the destination array of the same data type as the source array
* @param dstPosition starting position in the destination array
* @param length number of array elements to be copied
* @see PApplet#concat(boolean[], boolean[])
*/
static public void arrayCopy(Object src, int srcPosition,
Object dst, int dstPosition,
int length) {
System.arraycopy(src, srcPosition, dst, dstPosition, length);
}
/**
* Convenience method for arraycopy().
* Identical to <CODE>arraycopy(src, 0, dst, 0, length);</CODE>
*/
static public void arrayCopy(Object src, Object dst, int length) {
System.arraycopy(src, 0, dst, 0, length);
}
/**
* Shortcut to copy the entire contents of
* the source into the destination array.
* Identical to <CODE>arraycopy(src, 0, dst, 0, src.length);</CODE>
*/
static public void arrayCopy(Object src, Object dst) {
System.arraycopy(src, 0, dst, 0, Array.getLength(src));
}
//
/**
* @deprecated Use arrayCopy() instead.
*/
static public void arraycopy(Object src, int srcPosition,
Object dst, int dstPosition,
int length) {
System.arraycopy(src, srcPosition, dst, dstPosition, length);
}
/**
* @deprecated Use arrayCopy() instead.
*/
static public void arraycopy(Object src, Object dst, int length) {
System.arraycopy(src, 0, dst, 0, length);
}
/**
* @deprecated Use arrayCopy() instead.
*/
static public void arraycopy(Object src, Object dst) {
System.arraycopy(src, 0, dst, 0, Array.getLength(src));
}
/**
* ( begin auto-generated from expand.xml )
*
* Increases the size of an array. By default, this function doubles the
* size of the array, but the optional <b>newSize</b> parameter provides
* precise control over the increase in size.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) expand(originalArray)</em>.
*
* ( end auto-generated )
*
* @webref data:array_functions
* @param list the array to expand
* @see PApplet#shorten(boolean[])
*/
static public boolean[] expand(boolean list[]) {
return expand(list, list.length << 1);
}
/**
* @param newSize new size for the array
*/
static public boolean[] expand(boolean list[], int newSize) {
boolean temp[] = new boolean[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public byte[] expand(byte list[]) {
return expand(list, list.length << 1);
}
static public byte[] expand(byte list[], int newSize) {
byte temp[] = new byte[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public char[] expand(char list[]) {
return expand(list, list.length << 1);
}
static public char[] expand(char list[], int newSize) {
char temp[] = new char[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public int[] expand(int list[]) {
return expand(list, list.length << 1);
}
static public int[] expand(int list[], int newSize) {
int temp[] = new int[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public long[] expand(long list[]) {
return expand(list, list.length << 1);
}
static public long[] expand(long list[], int newSize) {
long temp[] = new long[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public float[] expand(float list[]) {
return expand(list, list.length << 1);
}
static public float[] expand(float list[], int newSize) {
float temp[] = new float[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public double[] expand(double list[]) {
return expand(list, list.length << 1);
}
static public double[] expand(double list[], int newSize) {
double temp[] = new double[newSize];
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
static public String[] expand(String list[]) {
return expand(list, list.length << 1);
}
static public String[] expand(String list[], int newSize) {
String temp[] = new String[newSize];
// in case the new size is smaller than list.length
System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length));
return temp;
}
/**
* @nowebref
*/
static public Object expand(Object array) {
return expand(array, Array.getLength(array) << 1);
}
static public Object expand(Object list, int newSize) {
Class<?> type = list.getClass().getComponentType();
Object temp = Array.newInstance(type, newSize);
System.arraycopy(list, 0, temp, 0,
Math.min(Array.getLength(list), newSize));
return temp;
}
// contract() has been removed in revision 0124, use subset() instead.
// (expand() is also functionally equivalent)
/**
* ( begin auto-generated from append.xml )
*
* Expands an array by one element and adds data to the new position. The
* datatype of the <b>element</b> parameter must be the same as the
* datatype of the array.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) append(originalArray, element)</em>.
*
* ( end auto-generated )
*
* @webref data:array_functions
* @param array array to append
* @param value new data for the array
* @see PApplet#shorten(boolean[])
* @see PApplet#expand(boolean[])
*/
static public byte[] append(byte array[], byte value) {
array = expand(array, array.length + 1);
array[array.length-1] = value;
return array;
}
static public char[] append(char array[], char value) {
array = expand(array, array.length + 1);
array[array.length-1] = value;
return array;
}
static public int[] append(int array[], int value) {
array = expand(array, array.length + 1);
array[array.length-1] = value;
return array;
}
static public float[] append(float array[], float value) {
array = expand(array, array.length + 1);
array[array.length-1] = value;
return array;
}
static public String[] append(String array[], String value) {
array = expand(array, array.length + 1);
array[array.length-1] = value;
return array;
}
static public Object append(Object array, Object value) {
int length = Array.getLength(array);
array = expand(array, length + 1);
Array.set(array, length, value);
return array;
}
/**
* ( begin auto-generated from shorten.xml )
*
* Decreases an array by one element and returns the shortened array.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) shorten(originalArray)</em>.
*
* ( end auto-generated )
*
* @webref data:array_functions
* @param list array to shorten
* @see PApplet#append(byte[], byte)
* @see PApplet#expand(boolean[])
*/
static public boolean[] shorten(boolean list[]) {
return subset(list, 0, list.length-1);
}
static public byte[] shorten(byte list[]) {
return subset(list, 0, list.length-1);
}
static public char[] shorten(char list[]) {
return subset(list, 0, list.length-1);
}
static public int[] shorten(int list[]) {
return subset(list, 0, list.length-1);
}
static public float[] shorten(float list[]) {
return subset(list, 0, list.length-1);
}
static public String[] shorten(String list[]) {
return subset(list, 0, list.length-1);
}
static public Object shorten(Object list) {
int length = Array.getLength(list);
return subset(list, 0, length - 1);
}
/**
* ( begin auto-generated from splice.xml )
*
* Inserts a value or array of values into an existing array. The first two
* parameters must be of the same datatype. The <b>array</b> parameter
* defines the array which will be modified and the second parameter
* defines the data which will be inserted.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) splice(array1, array2, index)</em>.
*
* ( end auto-generated )
* @webref data:array_functions
* @param list array to splice into
* @param value value to be spliced in
* @param index position in the array from which to insert data
* @see PApplet#concat(boolean[], boolean[])
* @see PApplet#subset(boolean[], int, int)
*/
static final public boolean[] splice(boolean list[],
boolean value, int index) {
boolean outgoing[] = new boolean[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public boolean[] splice(boolean list[],
boolean value[], int index) {
boolean outgoing[] = new boolean[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public byte[] splice(byte list[],
byte value, int index) {
byte outgoing[] = new byte[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public byte[] splice(byte list[],
byte value[], int index) {
byte outgoing[] = new byte[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public char[] splice(char list[],
char value, int index) {
char outgoing[] = new char[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public char[] splice(char list[],
char value[], int index) {
char outgoing[] = new char[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public int[] splice(int list[],
int value, int index) {
int outgoing[] = new int[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public int[] splice(int list[],
int value[], int index) {
int outgoing[] = new int[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public float[] splice(float list[],
float value, int index) {
float outgoing[] = new float[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public float[] splice(float list[],
float value[], int index) {
float outgoing[] = new float[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public String[] splice(String list[],
String value, int index) {
String outgoing[] = new String[list.length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
outgoing[index] = value;
System.arraycopy(list, index, outgoing, index + 1,
list.length - index);
return outgoing;
}
static final public String[] splice(String list[],
String value[], int index) {
String outgoing[] = new String[list.length + value.length];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, value.length);
System.arraycopy(list, index, outgoing, index + value.length,
list.length - index);
return outgoing;
}
static final public Object splice(Object list, Object value, int index) {
Object[] outgoing = null;
int length = Array.getLength(list);
// check whether item being spliced in is an array
if (value.getClass().getName().charAt(0) == '[') {
int vlength = Array.getLength(value);
outgoing = new Object[length + vlength];
System.arraycopy(list, 0, outgoing, 0, index);
System.arraycopy(value, 0, outgoing, index, vlength);
System.arraycopy(list, index, outgoing, index + vlength, length - index);
} else {
outgoing = new Object[length + 1];
System.arraycopy(list, 0, outgoing, 0, index);
Array.set(outgoing, index, value);
System.arraycopy(list, index, outgoing, index + 1, length - index);
}
return outgoing;
}
static public boolean[] subset(boolean list[], int start) {
return subset(list, start, list.length - start);
}
/**
* ( begin auto-generated from subset.xml )
*
* Extracts an array of elements from an existing array. The <b>array</b>
* parameter defines the array from which the elements will be copied and
* the <b>offset</b> and <b>length</b> parameters determine which elements
* to extract. If no <b>length</b> is given, elements will be extracted
* from the <b>offset</b> to the end of the array. When specifying the
* <b>offset</b> remember the first array element is 0. This function does
* not change the source array.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) subset(originalArray, 0, 4)</em>.
*
* ( end auto-generated )
* @webref data:array_functions
* @param list array to extract from
* @param start position to begin
* @param count number of values to extract
* @see PApplet#splice(boolean[], boolean, int)
*/
static public boolean[] subset(boolean list[], int start, int count) {
boolean output[] = new boolean[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public byte[] subset(byte list[], int start) {
return subset(list, start, list.length - start);
}
static public byte[] subset(byte list[], int start, int count) {
byte output[] = new byte[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public char[] subset(char list[], int start) {
return subset(list, start, list.length - start);
}
static public char[] subset(char list[], int start, int count) {
char output[] = new char[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public int[] subset(int list[], int start) {
return subset(list, start, list.length - start);
}
static public int[] subset(int list[], int start, int count) {
int output[] = new int[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public float[] subset(float list[], int start) {
return subset(list, start, list.length - start);
}
static public float[] subset(float list[], int start, int count) {
float output[] = new float[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public String[] subset(String list[], int start) {
return subset(list, start, list.length - start);
}
static public String[] subset(String list[], int start, int count) {
String output[] = new String[count];
System.arraycopy(list, start, output, 0, count);
return output;
}
static public Object subset(Object list, int start) {
int length = Array.getLength(list);
return subset(list, start, length - start);
}
static public Object subset(Object list, int start, int count) {
Class<?> type = list.getClass().getComponentType();
Object outgoing = Array.newInstance(type, count);
System.arraycopy(list, start, outgoing, 0, count);
return outgoing;
}
/**
* ( begin auto-generated from concat.xml )
*
* Concatenates two arrays. For example, concatenating the array { 1, 2, 3
* } and the array { 4, 5, 6 } yields { 1, 2, 3, 4, 5, 6 }. Both parameters
* must be arrays of the same datatype.
* <br/> <br/>
* When using an array of objects, the data returned from the function must
* be cast to the object array's data type. For example: <em>SomeClass[]
* items = (SomeClass[]) concat(array1, array2)</em>.
*
* ( end auto-generated )
* @webref data:array_functions
* @param a first array to concatenate
* @param b second array to concatenate
* @see PApplet#splice(boolean[], boolean, int)
* @see PApplet#arrayCopy(Object, int, Object, int, int)
*/
static public boolean[] concat(boolean a[], boolean b[]) {
boolean c[] = new boolean[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public byte[] concat(byte a[], byte b[]) {
byte c[] = new byte[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public char[] concat(char a[], char b[]) {
char c[] = new char[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public int[] concat(int a[], int b[]) {
int c[] = new int[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public float[] concat(float a[], float b[]) {
float c[] = new float[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public String[] concat(String a[], String b[]) {
String c[] = new String[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
static public Object concat(Object a, Object b) {
Class<?> type = a.getClass().getComponentType();
int alength = Array.getLength(a);
int blength = Array.getLength(b);
Object outgoing = Array.newInstance(type, alength + blength);
System.arraycopy(a, 0, outgoing, 0, alength);
System.arraycopy(b, 0, outgoing, alength, blength);
return outgoing;
}
//
/**
* ( begin auto-generated from reverse.xml )
*
* Reverses the order of an array.
*
* ( end auto-generated )
* @webref data:array_functions
* @param list booleans[], bytes[], chars[], ints[], floats[], or Strings[]
* @see PApplet#sort(String[], int)
*/
static public boolean[] reverse(boolean list[]) {
boolean outgoing[] = new boolean[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public byte[] reverse(byte list[]) {
byte outgoing[] = new byte[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public char[] reverse(char list[]) {
char outgoing[] = new char[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public int[] reverse(int list[]) {
int outgoing[] = new int[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public float[] reverse(float list[]) {
float outgoing[] = new float[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public String[] reverse(String list[]) {
String outgoing[] = new String[list.length];
int length1 = list.length - 1;
for (int i = 0; i < list.length; i++) {
outgoing[i] = list[length1 - i];
}
return outgoing;
}
static public Object reverse(Object list) {
Class<?> type = list.getClass().getComponentType();
int length = Array.getLength(list);
Object outgoing = Array.newInstance(type, length);
for (int i = 0; i < length; i++) {
Array.set(outgoing, i, Array.get(list, (length - 1) - i));
}
return outgoing;
}
//////////////////////////////////////////////////////////////
// STRINGS
/**
* ( begin auto-generated from trim.xml )
*
* Removes whitespace characters from the beginning and end of a String. In
* addition to standard whitespace characters such as space, carriage
* return, and tab, this function also removes the Unicode "nbsp" character.
*
* ( end auto-generated )
* @webref data:string_functions
* @param str any string
* @see PApplet#split(String, String)
* @see PApplet#join(String[], char)
*/
static public String trim(String str) {
return str.replace('\u00A0', ' ').trim();
}
/**
* @param array a String array
*/
static public String[] trim(String[] array) {
String[] outgoing = new String[array.length];
for (int i = 0; i < array.length; i++) {
if (array[i] != null) {
outgoing[i] = array[i].replace('\u00A0', ' ').trim();
}
}
return outgoing;
}
/**
* ( begin auto-generated from join.xml )
*
* Combines an array of Strings into one String, each separated by the
* character(s) used for the <b>separator</b> parameter. To join arrays of
* ints or floats, it's necessary to first convert them to strings using
* <b>nf()</b> or <b>nfs()</b>.
*
* ( end auto-generated )
* @webref data:string_functions
* @param list array of Strings
* @param separator char or String to be placed between each item
* @see PApplet#split(String, String)
* @see PApplet#trim(String)
* @see PApplet#nf(float, int, int)
* @see PApplet#nfs(float, int, int)
*/
static public String join(String[] list, char separator) {
return join(list, String.valueOf(separator));
}
static public String join(String[] list, String separator) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < list.length; i++) {
if (i != 0) buffer.append(separator);
buffer.append(list[i]);
}
return buffer.toString();
}
static public String[] splitTokens(String value) {
return splitTokens(value, WHITESPACE);
}
/**
* ( begin auto-generated from splitTokens.xml )
*
* The splitTokens() function splits a String at one or many character
* "tokens." The <b>tokens</b> parameter specifies the character or
* characters to be used as a boundary.
* <br/> <br/>
* If no <b>tokens</b> character is specified, any whitespace character is
* used to split. Whitespace characters include tab (\\t), line feed (\\n),
* carriage return (\\r), form feed (\\f), and space. To convert a String
* to an array of integers or floats, use the datatype conversion functions
* <b>int()</b> and <b>float()</b> to convert the array of Strings.
*
* ( end auto-generated )
* @webref data:string_functions
* @param value the String to be split
* @param delim list of individual characters that will be used as separators
* @see PApplet#split(String, String)
* @see PApplet#join(String[], String)
* @see PApplet#trim(String)
*/
static public String[] splitTokens(String value, String delim) {
StringTokenizer toker = new StringTokenizer(value, delim);
String pieces[] = new String[toker.countTokens()];
int index = 0;
while (toker.hasMoreTokens()) {
pieces[index++] = toker.nextToken();
}
return pieces;
}
/**
* ( begin auto-generated from split.xml )
*
* The split() function breaks a string into pieces using a character or
* string as the divider. The <b>delim</b> parameter specifies the
* character or characters that mark the boundaries between each piece. A
* String[] array is returned that contains each of the pieces.
* <br/> <br/>
* If the result is a set of numbers, you can convert the String[] array to
* to a float[] or int[] array using the datatype conversion functions
* <b>int()</b> and <b>float()</b> (see example above).
* <br/> <br/>
* The <b>splitTokens()</b> function works in a similar fashion, except
* that it splits using a range of characters instead of a specific
* character or sequence.
* <!-- /><br />
* This function uses regular expressions to determine how the <b>delim</b>
* parameter divides the <b>str</b> parameter. Therefore, if you use
* characters such parentheses and brackets that are used with regular
* expressions as a part of the <b>delim</b> parameter, you'll need to put
* two blackslashes (\\\\) in front of the character (see example above).
* You can read more about <a
* href="http://en.wikipedia.org/wiki/Regular_expression">regular
* expressions</a> and <a
* href="http://en.wikipedia.org/wiki/Escape_character">escape
* characters</a> on Wikipedia.
* -->
*
* ( end auto-generated )
* @webref data:string_functions
* @usage web_application
* @param value the String to be split
* @param delim the character or String used to separate the data
*/
static public String[] split(String value, char delim) {
// do this so that the exception occurs inside the user's
// program, rather than appearing to be a bug inside split()
if (value == null) return null;
//return split(what, String.valueOf(delim)); // huh
char chars[] = value.toCharArray();
int splitCount = 0; //1;
for (int i = 0; i < chars.length; i++) {
if (chars[i] == delim) splitCount++;
}
// make sure that there is something in the input string
//if (chars.length > 0) {
// if the last char is a delimeter, get rid of it..
//if (chars[chars.length-1] == delim) splitCount--;
// on second thought, i don't agree with this, will disable
//}
if (splitCount == 0) {
String splits[] = new String[1];
splits[0] = new String(value);
return splits;
}
//int pieceCount = splitCount + 1;
String splits[] = new String[splitCount + 1];
int splitIndex = 0;
int startIndex = 0;
for (int i = 0; i < chars.length; i++) {
if (chars[i] == delim) {
splits[splitIndex++] =
new String(chars, startIndex, i-startIndex);
startIndex = i + 1;
}
}
//if (startIndex != chars.length) {
splits[splitIndex] =
new String(chars, startIndex, chars.length-startIndex);
//}
return splits;
}
static public String[] split(String value, String delim) {
ArrayList<String> items = new ArrayList<String>();
int index;
int offset = 0;
while ((index = value.indexOf(delim, offset)) != -1) {
items.add(value.substring(offset, index));
offset = index + delim.length();
}
items.add(value.substring(offset));
String[] outgoing = new String[items.size()];
items.toArray(outgoing);
return outgoing;
}
static protected HashMap<String, Pattern> matchPatterns;
static Pattern matchPattern(String regexp) {
Pattern p = null;
if (matchPatterns == null) {
matchPatterns = new HashMap<String, Pattern>();
} else {
p = matchPatterns.get(regexp);
}
if (p == null) {
if (matchPatterns.size() == 10) {
// Just clear out the match patterns here if more than 10 are being
// used. It's not terribly efficient, but changes that you have >10
// different match patterns are very slim, unless you're doing
// something really tricky (like custom match() methods), in which
// case match() won't be efficient anyway. (And you should just be
// using your own Java code.) The alternative is using a queue here,
// but that's a silly amount of work for negligible benefit.
matchPatterns.clear();
}
p = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL);
matchPatterns.put(regexp, p);
}
return p;
}
/**
* ( begin auto-generated from match.xml )
*
* The match() function is used to apply a regular expression to a piece of
* text, and return matching groups (elements found inside parentheses) as
* a String array. No match will return null. If no groups are specified in
* the regexp, but the sequence matches, an array of length one (with the
* matched text as the first element of the array) will be returned.<br />
* <br />
* To use the function, first check to see if the result is null. If the
* result is null, then the sequence did not match. If the sequence did
* match, an array is returned.
* If there are groups (specified by sets of parentheses) in the regexp,
* then the contents of each will be returned in the array.
* Element [0] of a regexp match returns the entire matching string, and
* the match groups start at element [1] (the first group is [1], the
* second [2], and so on).<br />
* <br />
* The syntax can be found in the reference for Java's <a
* href="http://download.oracle.com/javase/6/docs/api/">Pattern</a> class.
* For regular expression syntax, read the <a
* href="http://download.oracle.com/javase/tutorial/essential/regex/">Java
* Tutorial</a> on the topic.
*
* ( end auto-generated )
* @webref data:string_functions
* @param str the String to be searched
* @param regexp the regexp to be used for matching
* @see PApplet#matchAll(String, String)
* @see PApplet#split(String, String)
* @see PApplet#splitTokens(String, String)
* @see PApplet#join(String[], String)
* @see PApplet#trim(String)
*/
static public String[] match(String str, String regexp) {
Pattern p = matchPattern(regexp);
Matcher m = p.matcher(str);
if (m.find()) {
int count = m.groupCount() + 1;
String[] groups = new String[count];
for (int i = 0; i < count; i++) {
groups[i] = m.group(i);
}
return groups;
}
return null;
}
/**
* ( begin auto-generated from matchAll.xml )
*
* This function is used to apply a regular expression to a piece of text,
* and return a list of matching groups (elements found inside parentheses)
* as a two-dimensional String array. No matches will return null. If no
* groups are specified in the regexp, but the sequence matches, a two
* dimensional array is still returned, but the second dimension is only of
* length one.<br />
* <br />
* To use the function, first check to see if the result is null. If the
* result is null, then the sequence did not match at all. If the sequence
* did match, a 2D array is returned. If there are groups (specified by
* sets of parentheses) in the regexp, then the contents of each will be
* returned in the array.
* Assuming, a loop with counter variable i, element [i][0] of a regexp
* match returns the entire matching string, and the match groups start at
* element [i][1] (the first group is [i][1], the second [i][2], and so
* on).<br />
* <br />
* The syntax can be found in the reference for Java's <a
* href="http://download.oracle.com/javase/6/docs/api/">Pattern</a> class.
* For regular expression syntax, read the <a
* href="http://download.oracle.com/javase/tutorial/essential/regex/">Java
* Tutorial</a> on the topic.
*
* ( end auto-generated )
* @webref data:string_functions
* @param str the String to be searched
* @param regexp the regexp to be used for matching
* @see PApplet#match(String, String)
* @see PApplet#split(String, String)
* @see PApplet#splitTokens(String, String)
* @see PApplet#join(String[], String)
* @see PApplet#trim(String)
*/
static public String[][] matchAll(String str, String regexp) {
Pattern p = matchPattern(regexp);
Matcher m = p.matcher(str);
ArrayList<String[]> results = new ArrayList<String[]>();
int count = m.groupCount() + 1;
while (m.find()) {
String[] groups = new String[count];
for (int i = 0; i < count; i++) {
groups[i] = m.group(i);
}
results.add(groups);
}
if (results.isEmpty()) {
return null;
}
String[][] matches = new String[results.size()][count];
for (int i = 0; i < matches.length; i++) {
matches[i] = results.get(i);
}
return matches;
}
//////////////////////////////////////////////////////////////
// CASTING FUNCTIONS, INSERTED BY PREPROC
/**
* Convert a char to a boolean. 'T', 't', and '1' will become the
* boolean value true, while 'F', 'f', or '0' will become false.
*/
/*
static final public boolean parseBoolean(char what) {
return ((what == 't') || (what == 'T') || (what == '1'));
}
*/
/**
* <p>Convert an integer to a boolean. Because of how Java handles upgrading
* numbers, this will also cover byte and char (as they will upgrade to
* an int without any sort of explicit cast).</p>
* <p>The preprocessor will convert boolean(what) to parseBoolean(what).</p>
* @return false if 0, true if any other number
*/
static final public boolean parseBoolean(int what) {
return (what != 0);
}
/*
// removed because this makes no useful sense
static final public boolean parseBoolean(float what) {
return (what != 0);
}
*/
/**
* Convert the string "true" or "false" to a boolean.
* @return true if 'what' is "true" or "TRUE", false otherwise
*/
static final public boolean parseBoolean(String what) {
return new Boolean(what).booleanValue();
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
// removed, no need to introduce strange syntax from other languages
static final public boolean[] parseBoolean(char what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] =
((what[i] == 't') || (what[i] == 'T') || (what[i] == '1'));
}
return outgoing;
}
*/
/**
* Convert a byte array to a boolean array. Each element will be
* evaluated identical to the integer case, where a byte equal
* to zero will return false, and any other value will return true.
* @return array of boolean elements
*/
/*
static final public boolean[] parseBoolean(byte what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (what[i] != 0);
}
return outgoing;
}
*/
/**
* Convert an int array to a boolean array. An int equal
* to zero will return false, and any other value will return true.
* @return array of boolean elements
*/
static final public boolean[] parseBoolean(int what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (what[i] != 0);
}
return outgoing;
}
/*
// removed, not necessary... if necessary, convert to int array first
static final public boolean[] parseBoolean(float what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (what[i] != 0);
}
return outgoing;
}
*/
static final public boolean[] parseBoolean(String what[]) {
boolean outgoing[] = new boolean[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = new Boolean(what[i]).booleanValue();
}
return outgoing;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public byte parseByte(boolean what) {
return what ? (byte)1 : 0;
}
static final public byte parseByte(char what) {
return (byte) what;
}
static final public byte parseByte(int what) {
return (byte) what;
}
static final public byte parseByte(float what) {
return (byte) what;
}
/*
// nixed, no precedent
static final public byte[] parseByte(String what) { // note: array[]
return what.getBytes();
}
*/
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public byte[] parseByte(boolean what[]) {
byte outgoing[] = new byte[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = what[i] ? (byte)1 : 0;
}
return outgoing;
}
static final public byte[] parseByte(char what[]) {
byte outgoing[] = new byte[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (byte) what[i];
}
return outgoing;
}
static final public byte[] parseByte(int what[]) {
byte outgoing[] = new byte[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (byte) what[i];
}
return outgoing;
}
static final public byte[] parseByte(float what[]) {
byte outgoing[] = new byte[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (byte) what[i];
}
return outgoing;
}
/*
static final public byte[][] parseByte(String what[]) { // note: array[][]
byte outgoing[][] = new byte[what.length][];
for (int i = 0; i < what.length; i++) {
outgoing[i] = what[i].getBytes();
}
return outgoing;
}
*/
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
static final public char parseChar(boolean what) { // 0/1 or T/F ?
return what ? 't' : 'f';
}
*/
static final public char parseChar(byte what) {
return (char) (what & 0xff);
}
static final public char parseChar(int what) {
return (char) what;
}
/*
static final public char parseChar(float what) { // nonsensical
return (char) what;
}
static final public char[] parseChar(String what) { // note: array[]
return what.toCharArray();
}
*/
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
static final public char[] parseChar(boolean what[]) { // 0/1 or T/F ?
char outgoing[] = new char[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = what[i] ? 't' : 'f';
}
return outgoing;
}
*/
static final public char[] parseChar(byte what[]) {
char outgoing[] = new char[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (char) (what[i] & 0xff);
}
return outgoing;
}
static final public char[] parseChar(int what[]) {
char outgoing[] = new char[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (char) what[i];
}
return outgoing;
}
/*
static final public char[] parseChar(float what[]) { // nonsensical
char outgoing[] = new char[what.length];
for (int i = 0; i < what.length; i++) {
outgoing[i] = (char) what[i];
}
return outgoing;
}
static final public char[][] parseChar(String what[]) { // note: array[][]
char outgoing[][] = new char[what.length][];
for (int i = 0; i < what.length; i++) {
outgoing[i] = what[i].toCharArray();
}
return outgoing;
}
*/
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public int parseInt(boolean what) {
return what ? 1 : 0;
}
/**
* Note that parseInt() will un-sign a signed byte value.
*/
static final public int parseInt(byte what) {
return what & 0xff;
}
/**
* Note that parseInt('5') is unlike String in the sense that it
* won't return 5, but the ascii value. This is because ((int) someChar)
* returns the ascii value, and parseInt() is just longhand for the cast.
*/
static final public int parseInt(char what) {
return what;
}
/**
* Same as floor(), or an (int) cast.
*/
static final public int parseInt(float what) {
return (int) what;
}
/**
* Parse a String into an int value. Returns 0 if the value is bad.
*/
static final public int parseInt(String what) {
return parseInt(what, 0);
}
/**
* Parse a String to an int, and provide an alternate value that
* should be used when the number is invalid.
*/
static final public int parseInt(String what, int otherwise) {
try {
int offset = what.indexOf('.');
if (offset == -1) {
return Integer.parseInt(what);
} else {
return Integer.parseInt(what.substring(0, offset));
}
} catch (NumberFormatException e) { }
return otherwise;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public int[] parseInt(boolean what[]) {
int list[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
list[i] = what[i] ? 1 : 0;
}
return list;
}
static final public int[] parseInt(byte what[]) { // note this unsigns
int list[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
list[i] = (what[i] & 0xff);
}
return list;
}
static final public int[] parseInt(char what[]) {
int list[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
list[i] = what[i];
}
return list;
}
static public int[] parseInt(float what[]) {
int inties[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
inties[i] = (int)what[i];
}
return inties;
}
/**
* Make an array of int elements from an array of String objects.
* If the String can't be parsed as a number, it will be set to zero.
*
* String s[] = { "1", "300", "44" };
* int numbers[] = parseInt(s);
*
* numbers will contain { 1, 300, 44 }
*/
static public int[] parseInt(String what[]) {
return parseInt(what, 0);
}
/**
* Make an array of int elements from an array of String objects.
* If the String can't be parsed as a number, its entry in the
* array will be set to the value of the "missing" parameter.
*
* String s[] = { "1", "300", "apple", "44" };
* int numbers[] = parseInt(s, 9999);
*
* numbers will contain { 1, 300, 9999, 44 }
*/
static public int[] parseInt(String what[], int missing) {
int output[] = new int[what.length];
for (int i = 0; i < what.length; i++) {
try {
output[i] = Integer.parseInt(what[i]);
} catch (NumberFormatException e) {
output[i] = missing;
}
}
return output;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
static final public float parseFloat(boolean what) {
return what ? 1 : 0;
}
*/
/**
* Convert an int to a float value. Also handles bytes because of
* Java's rules for upgrading values.
*/
static final public float parseFloat(int what) { // also handles byte
return what;
}
static final public float parseFloat(String what) {
return parseFloat(what, Float.NaN);
}
static final public float parseFloat(String what, float otherwise) {
try {
return new Float(what).floatValue();
} catch (NumberFormatException e) { }
return otherwise;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/*
static final public float[] parseFloat(boolean what[]) {
float floaties[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
floaties[i] = what[i] ? 1 : 0;
}
return floaties;
}
static final public float[] parseFloat(char what[]) {
float floaties[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
floaties[i] = (char) what[i];
}
return floaties;
}
*/
static final public float[] parseByte(byte what[]) {
float floaties[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
floaties[i] = what[i];
}
return floaties;
}
static final public float[] parseFloat(int what[]) {
float floaties[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
floaties[i] = what[i];
}
return floaties;
}
static final public float[] parseFloat(String what[]) {
return parseFloat(what, Float.NaN);
}
static final public float[] parseFloat(String what[], float missing) {
float output[] = new float[what.length];
for (int i = 0; i < what.length; i++) {
try {
output[i] = new Float(what[i]).floatValue();
} catch (NumberFormatException e) {
output[i] = missing;
}
}
return output;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public String str(boolean x) {
return String.valueOf(x);
}
static final public String str(byte x) {
return String.valueOf(x);
}
static final public String str(char x) {
return String.valueOf(x);
}
static final public String str(int x) {
return String.valueOf(x);
}
static final public String str(float x) {
return String.valueOf(x);
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static final public String[] str(boolean x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
static final public String[] str(byte x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
static final public String[] str(char x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
static final public String[] str(int x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
static final public String[] str(float x[]) {
String s[] = new String[x.length];
for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]);
return s;
}
//////////////////////////////////////////////////////////////
// INT NUMBER FORMATTING
/**
* Integer number formatter.
*/
static private NumberFormat int_nf;
static private int int_nf_digits;
static private boolean int_nf_commas;
static public String[] nf(int num[], int digits) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nf(num[i], digits);
}
return formatted;
}
/**
* ( begin auto-generated from nf.xml )
*
* Utility function for formatting numbers into strings. There are two
* versions, one for formatting floats and one for formatting ints. The
* values for the <b>digits</b>, <b>left</b>, and <b>right</b> parameters
* should always be positive integers.<br /><br />As shown in the above
* example, <b>nf()</b> is used to add zeros to the left and/or right of a
* number. This is typically for aligning a list of numbers. To
* <em>remove</em> digits from a floating-point number, use the
* <b>int()</b>, <b>ceil()</b>, <b>floor()</b>, or <b>round()</b>
* functions.
*
* ( end auto-generated )
* @webref data:string_functions
* @param num the number(s) to format
* @param digits number of digits to pad with zero
* @see PApplet#nfs(float, int, int)
* @see PApplet#nfp(float, int, int)
* @see PApplet#nfc(float, int)
* @see PApplet#int(float)
*/
static public String nf(int num, int digits) {
if ((int_nf != null) &&
(int_nf_digits == digits) &&
!int_nf_commas) {
return int_nf.format(num);
}
int_nf = NumberFormat.getInstance();
int_nf.setGroupingUsed(false); // no commas
int_nf_commas = false;
int_nf.setMinimumIntegerDigits(digits);
int_nf_digits = digits;
return int_nf.format(num);
}
/**
* ( begin auto-generated from nfc.xml )
*
* Utility function for formatting numbers into strings and placing
* appropriate commas to mark units of 1000. There are two versions, one
* for formatting ints and one for formatting an array of ints. The value
* for the <b>digits</b> parameter should always be a positive integer.
* <br/> <br/>
* For a non-US locale, this will insert periods instead of commas, or
* whatever is apprioriate for that region.
*
* ( end auto-generated )
* @webref data:string_functions
* @param num the number(s) to format
* @see PApplet#nf(float, int, int)
* @see PApplet#nfp(float, int, int)
* @see PApplet#nfc(float, int)
*/
static public String[] nfc(int num[]) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfc(num[i]);
}
return formatted;
}
/**
* nfc() or "number format with commas". This is an unfortunate misnomer
* because in locales where a comma is not the separator for numbers, it
* won't actually be outputting a comma, it'll use whatever makes sense for
* the locale.
*/
static public String nfc(int num) {
if ((int_nf != null) &&
(int_nf_digits == 0) &&
int_nf_commas) {
return int_nf.format(num);
}
int_nf = NumberFormat.getInstance();
int_nf.setGroupingUsed(true);
int_nf_commas = true;
int_nf.setMinimumIntegerDigits(0);
int_nf_digits = 0;
return int_nf.format(num);
}
/**
* number format signed (or space)
* Formats a number but leaves a blank space in the front
* when it's positive so that it can be properly aligned with
* numbers that have a negative sign in front of them.
*/
/**
* ( begin auto-generated from nfs.xml )
*
* Utility function for formatting numbers into strings. Similar to
* <b>nf()</b> but leaves a blank space in front of positive numbers so
* they align with negative numbers in spite of the minus symbol. There are
* two versions, one for formatting floats and one for formatting ints. The
* values for the <b>digits</b>, <b>left</b>, and <b>right</b> parameters
* should always be positive integers.
*
* ( end auto-generated )
* @webref data:string_functions
* @param num the number(s) to format
* @param digits number of digits to pad with zeroes
* @see PApplet#nf(float, int, int)
* @see PApplet#nfp(float, int, int)
* @see PApplet#nfc(float, int)
*/
static public String nfs(int num, int digits) {
return (num < 0) ? nf(num, digits) : (' ' + nf(num, digits));
}
static public String[] nfs(int num[], int digits) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfs(num[i], digits);
}
return formatted;
}
//
/**
* number format positive (or plus)
* Formats a number, always placing a - or + sign
* in the front when it's negative or positive.
*/
/**
* ( begin auto-generated from nfp.xml )
*
* Utility function for formatting numbers into strings. Similar to
* <b>nf()</b> but puts a "+" in front of positive numbers and a "-" in
* front of negative numbers. There are two versions, one for formatting
* floats and one for formatting ints. The values for the <b>digits</b>,
* <b>left</b>, and <b>right</b> parameters should always be positive integers.
*
* ( end auto-generated )
* @webref data:string_functions
* @param num the number(s) to format
* @param digits number of digits to pad with zeroes
* @see PApplet#nf(float, int, int)
* @see PApplet#nfs(float, int, int)
* @see PApplet#nfc(float, int)
*/
static public String nfp(int num, int digits) {
return (num < 0) ? nf(num, digits) : ('+' + nf(num, digits));
}
static public String[] nfp(int num[], int digits) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfp(num[i], digits);
}
return formatted;
}
//////////////////////////////////////////////////////////////
// FLOAT NUMBER FORMATTING
static private NumberFormat float_nf;
static private int float_nf_left, float_nf_right;
static private boolean float_nf_commas;
static public String[] nf(float num[], int left, int right) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nf(num[i], left, right);
}
return formatted;
}
/**
* @param num[] the number(s) to format
* @param left number of digits to the left of the decimal point
* @param right number of digits to the right of the decimal point
*/
static public String nf(float num, int left, int right) {
if ((float_nf != null) &&
(float_nf_left == left) &&
(float_nf_right == right) &&
!float_nf_commas) {
return float_nf.format(num);
}
float_nf = NumberFormat.getInstance();
float_nf.setGroupingUsed(false);
float_nf_commas = false;
if (left != 0) float_nf.setMinimumIntegerDigits(left);
if (right != 0) {
float_nf.setMinimumFractionDigits(right);
float_nf.setMaximumFractionDigits(right);
}
float_nf_left = left;
float_nf_right = right;
return float_nf.format(num);
}
/**
* @param num[] the number(s) to format
* @param right number of digits to the right of the decimal point
*/
static public String[] nfc(float num[], int right) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfc(num[i], right);
}
return formatted;
}
static public String nfc(float num, int right) {
if ((float_nf != null) &&
(float_nf_left == 0) &&
(float_nf_right == right) &&
float_nf_commas) {
return float_nf.format(num);
}
float_nf = NumberFormat.getInstance();
float_nf.setGroupingUsed(true);
float_nf_commas = true;
if (right != 0) {
float_nf.setMinimumFractionDigits(right);
float_nf.setMaximumFractionDigits(right);
}
float_nf_left = 0;
float_nf_right = right;
return float_nf.format(num);
}
/**
* @param num[] the number(s) to format
* @param left the number of digits to the left of the decimal point
* @param right the number of digits to the right of the decimal point
*/
static public String[] nfs(float num[], int left, int right) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfs(num[i], left, right);
}
return formatted;
}
static public String nfs(float num, int left, int right) {
return (num < 0) ? nf(num, left, right) : (' ' + nf(num, left, right));
}
/**
* @param left the number of digits to the left of the decimal point
* @param right the number of digits to the right of the decimal point
*/
static public String[] nfp(float num[], int left, int right) {
String formatted[] = new String[num.length];
for (int i = 0; i < formatted.length; i++) {
formatted[i] = nfp(num[i], left, right);
}
return formatted;
}
static public String nfp(float num, int left, int right) {
return (num < 0) ? nf(num, left, right) : ('+' + nf(num, left, right));
}
//////////////////////////////////////////////////////////////
// HEX/BINARY CONVERSION
/**
* ( begin auto-generated from hex.xml )
*
* Converts a byte, char, int, or color to a String containing the
* equivalent hexadecimal notation. For example color(0, 102, 153) will
* convert to the String "FF006699". This function can help make your geeky
* debugging sessions much happier.
* <br/> <br/>
* Note that the maximum number of digits is 8, because an int value can
* only represent up to 32 bits. Specifying more than eight digits will
* simply shorten the string to eight anyway.
*
* ( end auto-generated )
* @webref data:conversion
* @param value the value to convert
* @see PApplet#unhex(String)
* @see PApplet#binary(byte)
* @see PApplet#unbinary(String)
*/
static final public String hex(byte value) {
return hex(value, 2);
}
static final public String hex(char value) {
return hex(value, 4);
}
static final public String hex(int value) {
return hex(value, 8);
}
/**
* @param digits the number of digits (maximum 8)
*/
static final public String hex(int value, int digits) {
String stuff = Integer.toHexString(value).toUpperCase();
if (digits > 8) {
digits = 8;
}
int length = stuff.length();
if (length > digits) {
return stuff.substring(length - digits);
} else if (length < digits) {
return "00000000".substring(8 - (digits-length)) + stuff;
}
return stuff;
}
/**
* ( begin auto-generated from unhex.xml )
*
* Converts a String representation of a hexadecimal number to its
* equivalent integer value.
*
* ( end auto-generated )
*
* @webref data:conversion
* @param value String to convert to an integer
* @see PApplet#hex(int, int)
* @see PApplet#binary(byte)
* @see PApplet#unbinary(String)
*/
static final public int unhex(String value) {
// has to parse as a Long so that it'll work for numbers bigger than 2^31
return (int) (Long.parseLong(value, 16));
}
//
/**
* Returns a String that contains the binary value of a byte.
* The returned value will always have 8 digits.
*/
static final public String binary(byte value) {
return binary(value, 8);
}
/**
* Returns a String that contains the binary value of a char.
* The returned value will always have 16 digits because chars
* are two bytes long.
*/
static final public String binary(char value) {
return binary(value, 16);
}
/**
* Returns a String that contains the binary value of an int. The length
* depends on the size of the number itself. If you want a specific number
* of digits use binary(int what, int digits) to specify how many.
*/
static final public String binary(int value) {
return binary(value, 32);
}
/*
* Returns a String that contains the binary value of an int.
* The digits parameter determines how many digits will be used.
*/
/**
* ( begin auto-generated from binary.xml )
*
* Converts a byte, char, int, or color to a String containing the
* equivalent binary notation. For example color(0, 102, 153, 255) will
* convert to the String "11111111000000000110011010011001". This function
* can help make your geeky debugging sessions much happier.
* <br/> <br/>
* Note that the maximum number of digits is 32, because an int value can
* only represent up to 32 bits. Specifying more than 32 digits will simply
* shorten the string to 32 anyway.
*
* ( end auto-generated )
* @webref data:conversion
* @param value value to convert
* @param digits number of digits to return
* @see PApplet#unbinary(String)
* @see PApplet#hex(int,int)
* @see PApplet#unhex(String)
*/
static final public String binary(int value, int digits) {
String stuff = Integer.toBinaryString(value);
if (digits > 32) {
digits = 32;
}
int length = stuff.length();
if (length > digits) {
return stuff.substring(length - digits);
} else if (length < digits) {
int offset = 32 - (digits-length);
return "00000000000000000000000000000000".substring(offset) + stuff;
}
return stuff;
}
/**
* ( begin auto-generated from unbinary.xml )
*
* Converts a String representation of a binary number to its equivalent
* integer value. For example, unbinary("00001000") will return 8.
*
* ( end auto-generated )
* @webref data:conversion
* @param value String to convert to an integer
* @see PApplet#binary(byte)
* @see PApplet#hex(int,int)
* @see PApplet#unhex(String)
*/
static final public int unbinary(String value) {
return Integer.parseInt(value, 2);
}
//////////////////////////////////////////////////////////////
// COLOR FUNCTIONS
// moved here so that they can work without
// the graphics actually being instantiated (outside setup)
/**
* ( begin auto-generated from color.xml )
*
* Creates colors for storing in variables of the <b>color</b> datatype.
* The parameters are interpreted as RGB or HSB values depending on the
* current <b>colorMode()</b>. The default mode is RGB values from 0 to 255
* and therefore, the function call <b>color(255, 204, 0)</b> will return a
* bright yellow color. More about how colors are stored can be found in
* the reference for the <a href="color_datatype.html">color</a> datatype.
*
* ( end auto-generated )
* @webref color:creating_reading
* @param gray number specifying value between white and black
* @see PApplet#colorMode(int)
*/
public final int color(int gray) {
if (g == null) {
if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
return 0xff000000 | (gray << 16) | (gray << 8) | gray;
}
return g.color(gray);
}
/**
* @nowebref
* @param fgray number specifying value between white and black
*/
public final int color(float fgray) {
if (g == null) {
int gray = (int) fgray;
if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
return 0xff000000 | (gray << 16) | (gray << 8) | gray;
}
return g.color(fgray);
}
/**
* As of 0116 this also takes color(#FF8800, alpha)
* @param alpha relative to current color range
*/
public final int color(int gray, int alpha) {
if (g == null) {
if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
if (gray > 255) {
// then assume this is actually a #FF8800
return (alpha << 24) | (gray & 0xFFFFFF);
} else {
//if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
return (alpha << 24) | (gray << 16) | (gray << 8) | gray;
}
}
return g.color(gray, alpha);
}
/**
* @nowebref
*/
public final int color(float fgray, float falpha) {
if (g == null) {
int gray = (int) fgray;
int alpha = (int) falpha;
if (gray > 255) gray = 255; else if (gray < 0) gray = 0;
if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
return 0xff000000 | (gray << 16) | (gray << 8) | gray;
}
return g.color(fgray, falpha);
}
/**
* @param v1 red or hue values relative to the current color range
* @param v2 green or saturation values relative to the current color range
* @param v3 blue or brightness values relative to the current color range
*/
public final int color(int v1, int v2, int v3) {
if (g == null) {
if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0;
if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0;
if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0;
return 0xff000000 | (v1 << 16) | (v2 << 8) | v3;
}
return g.color(v1, v2, v3);
}
public final int color(int v1, int v2, int v3, int alpha) {
if (g == null) {
if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0;
if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0;
if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0;
return (alpha << 24) | (v1 << 16) | (v2 << 8) | v3;
}
return g.color(v1, v2, v3, alpha);
}
public final int color(float v1, float v2, float v3) {
if (g == null) {
if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0;
if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0;
if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0;
return 0xff000000 | ((int)v1 << 16) | ((int)v2 << 8) | (int)v3;
}
return g.color(v1, v2, v3);
}
public final int color(float v1, float v2, float v3, float alpha) {
if (g == null) {
if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0;
if (v1 > 255) v1 = 255; else if (v1 < 0) v1 = 0;
if (v2 > 255) v2 = 255; else if (v2 < 0) v2 = 0;
if (v3 > 255) v3 = 255; else if (v3 < 0) v3 = 0;
return ((int)alpha << 24) | ((int)v1 << 16) | ((int)v2 << 8) | (int)v3;
}
return g.color(v1, v2, v3, alpha);
}
static public int blendColor(int c1, int c2, int mode) {
return PImage.blendColor(c1, c2, mode);
}
//////////////////////////////////////////////////////////////
// MAIN
/**
* Set this sketch to communicate its state back to the PDE.
* <p/>
* This uses the stderr stream to write positions of the window
* (so that it will be saved by the PDE for the next run) and
* notify on quit. See more notes in the Worker class.
*/
public void setupExternalMessages() {
frame.addComponentListener(new ComponentAdapter() {
@Override
public void componentMoved(ComponentEvent e) {
Point where = ((Frame) e.getSource()).getLocation();
System.err.println(PApplet.EXTERNAL_MOVE + " " +
where.x + " " + where.y);
System.err.flush(); // doesn't seem to help or hurt
}
});
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
// System.err.println(PApplet.EXTERNAL_QUIT);
// System.err.flush(); // important
// System.exit(0);
exit(); // don't quit, need to just shut everything down (0133)
}
});
}
/**
* Set up a listener that will fire proper component resize events
* in cases where frame.setResizable(true) is called.
*/
public void setupFrameResizeListener() {
frame.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
// Ignore bad resize events fired during setup to fix
// http://dev.processing.org/bugs/show_bug.cgi?id=341
// This should also fix the blank screen on Linux bug
// http://dev.processing.org/bugs/show_bug.cgi?id=282
if (frame.isResizable()) {
// might be multiple resize calls before visible (i.e. first
// when pack() is called, then when it's resized for use).
// ignore them because it's not the user resizing things.
Frame farm = (Frame) e.getComponent();
if (farm.isVisible()) {
Insets insets = farm.getInsets();
Dimension windowSize = farm.getSize();
Rectangle newBounds =
new Rectangle(insets.left, insets.top,
windowSize.width - insets.left - insets.right,
windowSize.height - insets.top - insets.bottom);
Rectangle oldBounds = getBounds();
if (!newBounds.equals(oldBounds)) {
// the ComponentListener in PApplet will handle calling size()
setBounds(newBounds);
}
}
}
}
});
}
// /**
// * GIF image of the Processing logo.
// */
// static public final byte[] ICON_IMAGE = {
// 71, 73, 70, 56, 57, 97, 16, 0, 16, 0, -77, 0, 0, 0, 0, 0, -1, -1, -1, 12,
// 12, 13, -15, -15, -14, 45, 57, 74, 54, 80, 111, 47, 71, 97, 62, 88, 117,
// 1, 14, 27, 7, 41, 73, 15, 52, 85, 2, 31, 55, 4, 54, 94, 18, 69, 109, 37,
// 87, 126, -1, -1, -1, 33, -7, 4, 1, 0, 0, 15, 0, 44, 0, 0, 0, 0, 16, 0, 16,
// 0, 0, 4, 122, -16, -107, 114, -86, -67, 83, 30, -42, 26, -17, -100, -45,
// 56, -57, -108, 48, 40, 122, -90, 104, 67, -91, -51, 32, -53, 77, -78, -100,
// 47, -86, 12, 76, -110, -20, -74, -101, 97, -93, 27, 40, 20, -65, 65, 48,
// -111, 99, -20, -112, -117, -123, -47, -105, 24, 114, -112, 74, 69, 84, 25,
// 93, 88, -75, 9, 46, 2, 49, 88, -116, -67, 7, -19, -83, 60, 38, 3, -34, 2,
// 66, -95, 27, -98, 13, 4, -17, 55, 33, 109, 11, 11, -2, -128, 121, 123, 62,
// 91, 120, -128, 127, 122, 115, 102, 2, 119, 0, -116, -113, -119, 6, 102,
// 121, -108, -126, 5, 18, 6, 4, -102, -101, -100, 114, 15, 17, 0, 59
// };
static ArrayList<Image> iconImages;
protected void setIconImage(Frame frame) {
// On OS X, this only affects what shows up in the dock when minimized.
// So this is actually a step backwards. Brilliant.
if (platform != MACOSX) {
//Image image = Toolkit.getDefaultToolkit().createImage(ICON_IMAGE);
//frame.setIconImage(image);
try {
if (iconImages == null) {
iconImages = new ArrayList<Image>();
final int[] sizes = { 16, 24, 32, 48, 64 };
for (int sz : sizes) {
URL url = getClass().getResource("/icon/icon-" + sz + ".png");
Image image = Toolkit.getDefaultToolkit().getImage(url);
iconImages.add(image);
//iconImages.add(Toolkit.getLibImage("icons/pde-" + sz + ".png", frame));
}
}
frame.setIconImages(iconImages);
} catch (Exception e) {
//e.printStackTrace(); // more or less harmless; don't spew errors
}
}
}
// Not gonna do this dynamically, only on startup. Too much headache.
// public void fullscreen() {
// if (frame != null) {
// if (PApplet.platform == MACOSX) {
// japplemenubar.JAppleMenuBar.hide();
// }
// GraphicsConfiguration gc = frame.getGraphicsConfiguration();
// Rectangle rect = gc.getBounds();
//// GraphicsDevice device = gc.getDevice();
// frame.setBounds(rect.x, rect.y, rect.width, rect.height);
// }
// }
/**
* main() method for running this class from the command line.
* <p>
* <B>The options shown here are not yet finalized and will be
* changing over the next several releases.</B>
* <p>
* The simplest way to turn and applet into an application is to
* add the following code to your program:
* <PRE>static public void main(String args[]) {
* PApplet.main("YourSketchName", args);
* }</PRE>
* This will properly launch your applet from a double-clickable
* .jar or from the command line.
* <PRE>
* Parameters useful for launching or also used by the PDE:
*
* --location=x,y upper-lefthand corner of where the applet
* should appear on screen. if not used,
* the default is to center on the main screen.
*
* --full-screen put the applet into full screen "present" mode.
*
* --hide-stop use to hide the stop button in situations where
* you don't want to allow users to exit. also
* see the FAQ on information for capturing the ESC
* key when running in presentation mode.
*
* --stop-color=#xxxxxx color of the 'stop' text used to quit an
* sketch when it's in present mode.
*
* --bgcolor=#xxxxxx background color of the window.
*
* --sketch-path location of where to save files from functions
* like saveStrings() or saveFrame(). defaults to
* the folder that the java application was
* launched from, which means if this isn't set by
* the pde, everything goes into the same folder
* as processing.exe.
*
* --display=n set what display should be used by this sketch.
* displays are numbered starting from 0.
*
* Parameters used by Processing when running via the PDE
*
* --external set when the applet is being used by the PDE
*
* --editor-location=x,y position of the upper-lefthand corner of the
* editor window, for placement of applet window
* </PRE>
*/
static public void main(final String[] args) {
runSketch(args, null);
}
/**
* Convenience method so that PApplet.main("YourSketch") launches a sketch,
* rather than having to wrap it into a String array.
* @param mainClass name of the class to load (with package if any)
*/
static public void main(final String mainClass) {
main(mainClass, null);
}
/**
* Convenience method so that PApplet.main("YourSketch", args) launches a
* sketch, rather than having to wrap it into a String array, and appending
* the 'args' array when not null.
* @param mainClass name of the class to load (with package if any)
* @param args command line arguments to pass to the sketch
*/
static public void main(final String mainClass, final String[] passedArgs) {
String[] args = new String[] { mainClass };
if (passedArgs != null) {
args = concat(args, passedArgs);
}
runSketch(args, null);
}
static public void runSketch(final String args[], final PApplet constructedApplet) {
// Disable abyssmally slow Sun renderer on OS X 10.5.
if (platform == MACOSX) {
// Only run this on OS X otherwise it can cause a permissions error.
// http://dev.processing.org/bugs/show_bug.cgi?id=976
System.setProperty("apple.awt.graphics.UseQuartz",
String.valueOf(useQuartz));
}
// Doesn't seem to do much to help avoid flicker
System.setProperty("sun.awt.noerasebackground", "true");
// This doesn't do anything.
// if (platform == WINDOWS) {
// // For now, disable the D3D renderer on Java 6u10 because
// // it causes problems with Present mode.
// // http://dev.processing.org/bugs/show_bug.cgi?id=1009
// System.setProperty("sun.java2d.d3d", "false");
// }
if (args.length < 1) {
System.err.println("Usage: PApplet <appletname>");
System.err.println("For additional options, " +
"see the Javadoc for PApplet");
System.exit(1);
}
// EventQueue.invokeLater(new Runnable() {
// public void run() {
// runSketchEDT(args, constructedApplet);
// }
// });
// }
//
//
// static public void runSketchEDT(final String args[], final PApplet constructedApplet) {
boolean external = false;
int[] location = null;
int[] editorLocation = null;
String name = null;
boolean present = false;
// boolean exclusive = false;
// Color backgroundColor = Color.BLACK;
Color backgroundColor = null; //Color.BLACK;
Color stopColor = Color.GRAY;
GraphicsDevice displayDevice = null;
boolean hideStop = false;
String param = null, value = null;
// try to get the user folder. if running under java web start,
// this may cause a security exception if the code is not signed.
// http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Integrate;action=display;num=1159386274
String folder = null;
try {
folder = System.getProperty("user.dir");
} catch (Exception e) { }
int argIndex = 0;
while (argIndex < args.length) {
int equals = args[argIndex].indexOf('=');
if (equals != -1) {
param = args[argIndex].substring(0, equals);
value = args[argIndex].substring(equals + 1);
if (param.equals(ARGS_EDITOR_LOCATION)) {
external = true;
editorLocation = parseInt(split(value, ','));
} else if (param.equals(ARGS_DISPLAY)) {
int deviceIndex = Integer.parseInt(value);
GraphicsEnvironment environment =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice devices[] = environment.getScreenDevices();
if ((deviceIndex >= 0) && (deviceIndex < devices.length)) {
displayDevice = devices[deviceIndex];
} else {
System.err.println("Display " + value + " does not exist, " +
"using the default display instead.");
for (int i = 0; i < devices.length; i++) {
System.err.println(i + " is " + devices[i]);
}
}
} else if (param.equals(ARGS_BGCOLOR)) {
if (value.charAt(0) == '#') value = value.substring(1);
backgroundColor = new Color(Integer.parseInt(value, 16));
} else if (param.equals(ARGS_STOP_COLOR)) {
if (value.charAt(0) == '#') value = value.substring(1);
stopColor = new Color(Integer.parseInt(value, 16));
} else if (param.equals(ARGS_SKETCH_FOLDER)) {
folder = value;
} else if (param.equals(ARGS_LOCATION)) {
location = parseInt(split(value, ','));
}
} else {
if (args[argIndex].equals(ARGS_PRESENT)) { // keep for compatability
present = true;
} else if (args[argIndex].equals(ARGS_FULL_SCREEN)) {
present = true;
// } else if (args[argIndex].equals(ARGS_EXCLUSIVE)) {
// exclusive = true;
} else if (args[argIndex].equals(ARGS_HIDE_STOP)) {
hideStop = true;
} else if (args[argIndex].equals(ARGS_EXTERNAL)) {
external = true;
} else {
name = args[argIndex];
break; // because of break, argIndex won't increment again
}
}
argIndex++;
}
// Set this property before getting into any GUI init code
//System.setProperty("com.apple.mrj.application.apple.menu.about.name", name);
// This )*)(*@#$ Apple crap don't work no matter where you put it
// (static method of the class, at the top of main, wherever)
if (displayDevice == null) {
GraphicsEnvironment environment =
GraphicsEnvironment.getLocalGraphicsEnvironment();
displayDevice = environment.getDefaultScreenDevice();
}
Frame frame = new Frame(displayDevice.getDefaultConfiguration());
// JFrame frame = new JFrame(displayDevice.getDefaultConfiguration());
/*
Frame frame = null;
if (displayDevice != null) {
frame = new Frame(displayDevice.getDefaultConfiguration());
} else {
frame = new Frame();
}
*/
//Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
// remove the grow box by default
// users who want it back can call frame.setResizable(true)
// frame.setResizable(false);
// moved later (issue #467)
final PApplet applet;
if (constructedApplet != null) {
applet = constructedApplet;
} else {
try {
Class<?> c = Thread.currentThread().getContextClassLoader().loadClass(name);
applet = (PApplet) c.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// Set the trimmings around the image
applet.setIconImage(frame);
frame.setTitle(name);
// frame.setIgnoreRepaint(true); // does nothing
// frame.addComponentListener(new ComponentAdapter() {
// public void componentResized(ComponentEvent e) {
// Component c = e.getComponent();
//// Rectangle bounds = c.getBounds();
// System.out.println(" " + c.getName() + " wants to be: " + c.getSize());
// }
// });
// frame.addComponentListener(new ComponentListener() {
//
// public void componentShown(ComponentEvent e) {
// debug("frame: " + e);
// debug(" applet valid? " + applet.isValid());
//// ((PGraphicsJava2D) applet.g).redraw();
// }
//
// public void componentResized(ComponentEvent e) {
// println("frame: " + e + " " + applet.frame.getInsets());
// Insets insets = applet.frame.getInsets();
// int wide = e.getComponent().getWidth() - (insets.left + insets.right);
// int high = e.getComponent().getHeight() - (insets.top + insets.bottom);
// if (applet.getWidth() != wide || applet.getHeight() != high) {
// debug("Frame.componentResized() setting applet size " + wide + " " + high);
// applet.setSize(wide, high);
// }
// }
//
// public void componentMoved(ComponentEvent e) {
// //println("frame: " + e + " " + applet.frame.getInsets());
// Insets insets = applet.frame.getInsets();
// int wide = e.getComponent().getWidth() - (insets.left + insets.right);
// int high = e.getComponent().getHeight() - (insets.top + insets.bottom);
// //applet.g.setsi
// if (applet.getWidth() != wide || applet.getHeight() != high) {
// debug("Frame.componentMoved() setting applet size " + wide + " " + high);
// applet.setSize(wide, high);
// }
// }
//
// public void componentHidden(ComponentEvent e) {
// debug("frame: " + e);
// }
// });
// A handful of things that need to be set before init/start.
applet.frame = frame;
applet.sketchPath = folder;
// If the applet doesn't call for full screen, but the command line does,
// enable it. Conversely, if the command line does not, don't disable it.
// applet.fullScreen |= present;
// Query the applet to see if it wants to be full screen all the time.
present |= applet.sketchFullScreen();
// pass everything after the class name in as args to the sketch itself
// (fixed for 2.0a5, this was just subsetting by 1, which didn't skip opts)
applet.args = PApplet.subset(args, argIndex + 1);
applet.external = external;
// Need to save the window bounds at full screen,
// because pack() will cause the bounds to go to zero.
// http://dev.processing.org/bugs/show_bug.cgi?id=923
Rectangle screenRect =
displayDevice.getDefaultConfiguration().getBounds();
// DisplayMode doesn't work here, because we can't get the upper-left
// corner of the display, which is important for multi-display setups.
// Sketch has already requested to be the same as the screen's
// width and height, so let's roll with full screen mode.
if (screenRect.width == applet.sketchWidth() &&
screenRect.height == applet.sketchHeight()) {
present = true;
}
// For 0149, moving this code (up to the pack() method) before init().
// For OpenGL (and perhaps other renderers in the future), a peer is
// needed before a GLDrawable can be created. So pack() needs to be
// called on the Frame before applet.init(), which itself calls size(),
// and launches the Thread that will kick off setup().
// http://dev.processing.org/bugs/show_bug.cgi?id=891
// http://dev.processing.org/bugs/show_bug.cgi?id=908
if (present) {
// if (platform == MACOSX) {
// // Call some native code to remove the menu bar on OS X. Not necessary
// // on Linux and Windows, who are happy to make full screen windows.
// japplemenubar.JAppleMenuBar.hide();
// }
frame.setUndecorated(true);
if (backgroundColor != null) {
frame.setBackground(backgroundColor);
}
// if (exclusive) {
// displayDevice.setFullScreenWindow(frame);
// // this trashes the location of the window on os x
// //frame.setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
// fullScreenRect = frame.getBounds();
// } else {
frame.setBounds(screenRect);
frame.setVisible(true);
// }
}
frame.setLayout(null);
frame.add(applet);
if (present) {
frame.invalidate();
} else {
frame.pack();
}
// insufficient, places the 100x100 sketches offset strangely
//frame.validate();
// disabling resize has to happen after pack() to avoid apparent Apple bug
// http://code.google.com/p/processing/issues/detail?id=467
frame.setResizable(false);
applet.init();
// applet.start();
// Wait until the applet has figured out its width.
// In a static mode app, this will be after setup() has completed,
// and the empty draw() has set "finished" to true.
// TODO make sure this won't hang if the applet has an exception.
while (applet.defaultSize && !applet.finished) {
//System.out.println("default size");
try {
Thread.sleep(5);
} catch (InterruptedException e) {
//System.out.println("interrupt");
}
}
// // If 'present' wasn't already set, but the applet initializes
// // to full screen, attempt to make things full screen anyway.
// if (!present &&
// applet.width == screenRect.width &&
// applet.height == screenRect.height) {
// // bounds will be set below, but can't change to setUndecorated() now
// present = true;
// }
// // Opting not to do this, because we can't remove the decorations on the
// // window at this point. And re-opening a new winodw is a lot of mess.
// // Better all around to just encourage the use of sketchFullScreen()
// // or cmd/ctrl-shift-R in the PDE.
if (present) {
if (platform == MACOSX) {
// Call some native code to remove the menu bar on OS X. Not necessary
// on Linux and Windows, who are happy to make full screen windows.
japplemenubar.JAppleMenuBar.hide();
}
// After the pack(), the screen bounds are gonna be 0s
frame.setBounds(screenRect);
applet.setBounds((screenRect.width - applet.width) / 2,
(screenRect.height - applet.height) / 2,
applet.width, applet.height);
if (!hideStop) {
Label label = new Label("stop");
label.setForeground(stopColor);
label.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(java.awt.event.MouseEvent e) {
System.exit(0);
}
});
frame.add(label);
Dimension labelSize = label.getPreferredSize();
// sometimes shows up truncated on mac
//System.out.println("label width is " + labelSize.width);
labelSize = new Dimension(100, labelSize.height);
label.setSize(labelSize);
label.setLocation(20, screenRect.height - labelSize.height - 20);
}
// not always running externally when in present mode
if (external) {
applet.setupExternalMessages();
}
} else { // if not presenting
// can't do pack earlier cuz present mode don't like it
// (can't go full screen with a frame after calling pack)
// frame.pack(); // get insets. get more.
Insets insets = frame.getInsets();
int windowW = Math.max(applet.width, MIN_WINDOW_WIDTH) +
insets.left + insets.right;
int windowH = Math.max(applet.height, MIN_WINDOW_HEIGHT) +
insets.top + insets.bottom;
frame.setSize(windowW, windowH);
if (location != null) {
// a specific location was received from the Runner
// (applet has been run more than once, user placed window)
frame.setLocation(location[0], location[1]);
} else if (external && editorLocation != null) {
int locationX = editorLocation[0] - 20;
int locationY = editorLocation[1];
if (locationX - windowW > 10) {
// if it fits to the left of the window
frame.setLocation(locationX - windowW, locationY);
} else { // doesn't fit
// if it fits inside the editor window,
// offset slightly from upper lefthand corner
// so that it's plunked inside the text area
locationX = editorLocation[0] + 66;
locationY = editorLocation[1] + 66;
if ((locationX + windowW > applet.displayWidth - 33) ||
(locationY + windowH > applet.displayHeight - 33)) {
// otherwise center on screen
locationX = (applet.displayWidth - windowW) / 2;
locationY = (applet.displayHeight - windowH) / 2;
}
frame.setLocation(locationX, locationY);
}
} else { // just center on screen
// Can't use frame.setLocationRelativeTo(null) because it sends the
// frame to the main display, which undermines the --display setting.
frame.setLocation(screenRect.x + (screenRect.width - applet.width) / 2,
screenRect.y + (screenRect.height - applet.height) / 2);
}
Point frameLoc = frame.getLocation();
if (frameLoc.y < 0) {
// Windows actually allows you to place frames where they can't be
// closed. Awesome. http://dev.processing.org/bugs/show_bug.cgi?id=1508
frame.setLocation(frameLoc.x, 30);
}
if (backgroundColor != null) {
// if (backgroundColor == Color.black) { //BLACK) {
// // this means no bg color unless specified
// backgroundColor = SystemColor.control;
// }
frame.setBackground(backgroundColor);
}
int usableWindowH = windowH - insets.top - insets.bottom;
applet.setBounds((windowW - applet.width)/2,
insets.top + (usableWindowH - applet.height)/2,
applet.width, applet.height);
if (external) {
applet.setupExternalMessages();
} else { // !external
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
}
// handle frame resizing events
applet.setupFrameResizeListener();
// all set for rockin
if (applet.displayable()) {
frame.setVisible(true);
}
}
// Disabling for 0185, because it causes an assertion failure on OS X
// http://code.google.com/p/processing/issues/detail?id=258
// (Although this doesn't seem to be the one that was causing problems.)
//applet.requestFocus(); // ask for keydowns
}
/**
* These methods provide a means for running an already-constructed
* sketch. In particular, it makes it easy to launch a sketch in
* Jython:
*
* <pre>class MySketch(PApplet):
* pass
*
*MySketch().runSketch();</pre>
*/
protected void runSketch(final String[] args) {
final String[] argsWithSketchName = new String[args.length + 1];
System.arraycopy(args, 0, argsWithSketchName, 0, args.length);
final String className = this.getClass().getSimpleName();
final String cleanedClass =
className.replaceAll("__[^_]+__\\$", "").replaceAll("\\$\\d+", "");
argsWithSketchName[args.length] = cleanedClass;
runSketch(argsWithSketchName, this);
}
protected void runSketch() {
runSketch(new String[0]);
}
//////////////////////////////////////////////////////////////
/**
* ( begin auto-generated from beginRecord.xml )
*
* Opens a new file and all subsequent drawing functions are echoed to this
* file as well as the display window. The <b>beginRecord()</b> function
* requires two parameters, the first is the renderer and the second is the
* file name. This function is always used with <b>endRecord()</b> to stop
* the recording process and close the file.
* <br /> <br />
* Note that beginRecord() will only pick up any settings that happen after
* it has been called. For instance, if you call textFont() before
* beginRecord(), then that font will not be set for the file that you're
* recording to.
*
* ( end auto-generated )
*
* @webref output:files
* @param renderer for example, PDF
* @param filename filename for output
* @see PApplet#endRecord()
*/
public PGraphics beginRecord(String renderer, String filename) {
filename = insertFrame(filename);
PGraphics rec = createGraphics(width, height, renderer, filename);
beginRecord(rec);
return rec;
}
/**
* @nowebref
* Begin recording (echoing) commands to the specified PGraphics object.
*/
public void beginRecord(PGraphics recorder) {
this.recorder = recorder;
recorder.beginDraw();
}
/**
* ( begin auto-generated from endRecord.xml )
*
* Stops the recording process started by <b>beginRecord()</b> and closes
* the file.
*
* ( end auto-generated )
* @webref output:files
* @see PApplet#beginRecord(String, String)
*/
public void endRecord() {
if (recorder != null) {
recorder.endDraw();
recorder.dispose();
recorder = null;
}
}
/**
* ( begin auto-generated from beginRaw.xml )
*
* To create vectors from 3D data, use the <b>beginRaw()</b> and
* <b>endRaw()</b> commands. These commands will grab the shape data just
* before it is rendered to the screen. At this stage, your entire scene is
* nothing but a long list of individual lines and triangles. This means
* that a shape created with <b>sphere()</b> function will be made up of
* hundreds of triangles, rather than a single object. Or that a
* multi-segment line shape (such as a curve) will be rendered as
* individual segments.
* <br /><br />
* When using <b>beginRaw()</b> and <b>endRaw()</b>, it's possible to write
* to either a 2D or 3D renderer. For instance, <b>beginRaw()</b> with the
* PDF library will write the geometry as flattened triangles and lines,
* even if recording from the <b>P3D</b> renderer.
* <br /><br />
* If you want a background to show up in your files, use <b>rect(0, 0,
* width, height)</b> after setting the <b>fill()</b> to the background
* color. Otherwise the background will not be rendered to the file because
* the background is not shape.
* <br /><br />
* Using <b>hint(ENABLE_DEPTH_SORT)</b> can improve the appearance of 3D
* geometry drawn to 2D file formats. See the <b>hint()</b> reference for
* more details.
* <br /><br />
* See examples in the reference for the <b>PDF</b> and <b>DXF</b>
* libraries for more information.
*
* ( end auto-generated )
*
* @webref output:files
* @param renderer for example, PDF or DXF
* @param filename filename for output
* @see PApplet#endRaw()
* @see PApplet#hint(int)
*/
public PGraphics beginRaw(String renderer, String filename) {
filename = insertFrame(filename);
PGraphics rec = createGraphics(width, height, renderer, filename);
g.beginRaw(rec);
return rec;
}
/**
* @nowebref
* Begin recording raw shape data to the specified renderer.
*
* This simply echoes to g.beginRaw(), but since is placed here (rather than
* generated by preproc.pl) for clarity and so that it doesn't echo the
* command should beginRecord() be in use.
*
* @param rawGraphics ???
*/
public void beginRaw(PGraphics rawGraphics) {
g.beginRaw(rawGraphics);
}
/**
* ( begin auto-generated from endRaw.xml )
*
* Complement to <b>beginRaw()</b>; they must always be used together. See
* the <b>beginRaw()</b> reference for details.
*
* ( end auto-generated )
*
* @webref output:files
* @see PApplet#beginRaw(String, String)
*/
public void endRaw() {
g.endRaw();
}
/**
* Starts shape recording and returns the PShape object that will
* contain the geometry.
*/
/*
public PShape beginRecord() {
return g.beginRecord();
}
*/
//////////////////////////////////////////////////////////////
/**
* ( begin auto-generated from loadPixels.xml )
*
* Loads the pixel data for the display window into the <b>pixels[]</b>
* array. This function must always be called before reading from or
* writing to <b>pixels[]</b>.
* <br/><br/> renderers may or may not seem to require <b>loadPixels()</b>
* or <b>updatePixels()</b>. However, the rule is that any time you want to
* manipulate the <b>pixels[]</b> array, you must first call
* <b>loadPixels()</b>, and after changes have been made, call
* <b>updatePixels()</b>. Even if the renderer may not seem to use this
* function in the current Processing release, this will always be subject
* to change.
*
* ( end auto-generated )
* <h3>Advanced</h3>
* Override the g.pixels[] function to set the pixels[] array
* that's part of the PApplet object. Allows the use of
* pixels[] in the code, rather than g.pixels[].
*
* @webref image:pixels
* @see PApplet#pixels
* @see PApplet#updatePixels()
*/
public void loadPixels() {
g.loadPixels();
pixels = g.pixels;
}
/**
* ( begin auto-generated from updatePixels.xml )
*
* Updates the display window with the data in the <b>pixels[]</b> array.
* Use in conjunction with <b>loadPixels()</b>. If you're only reading
* pixels from the array, there's no need to call <b>updatePixels()</b>
* unless there are changes.
* <br/><br/> renderers may or may not seem to require <b>loadPixels()</b>
* or <b>updatePixels()</b>. However, the rule is that any time you want to
* manipulate the <b>pixels[]</b> array, you must first call
* <b>loadPixels()</b>, and after changes have been made, call
* <b>updatePixels()</b>. Even if the renderer may not seem to use this
* function in the current Processing release, this will always be subject
* to change.
* <br/> <br/>
* Currently, none of the renderers use the additional parameters to
* <b>updatePixels()</b>, however this may be implemented in the future.
*
* ( end auto-generated )
* @webref image:pixels
* @see PApplet#loadPixels()
* @see PApplet#pixels
*/
public void updatePixels() {
g.updatePixels();
}
/**
* @nowebref
* @param x1 x-coordinate of the upper-left corner
* @param y1 y-coordinate of the upper-left corner
* @param x2 width of the region
* @param y2 height of the region
*/
public void updatePixels(int x1, int y1, int x2, int y2) {
g.updatePixels(x1, y1, x2, y2);
}
//////////////////////////////////////////////////////////////
// EVERYTHING BELOW THIS LINE IS AUTOMATICALLY GENERATED. DO NOT TOUCH!
// This includes the Javadoc comments, which are automatically copied from
// the PImage and PGraphics source code files.
// public functions for processing.core
/**
* Store data of some kind for the renderer that requires extra metadata of
* some kind. Usually this is a renderer-specific representation of the
* image data, for instance a BufferedImage with tint() settings applied for
* PGraphicsJava2D, or resized image data and OpenGL texture indices for
* PGraphicsOpenGL.
* @param renderer The PGraphics renderer associated to the image
* @param storage The metadata required by the renderer
*/
public void setCache(PImage image, Object storage) {
if (recorder != null) recorder.setCache(image, storage);
g.setCache(image, storage);
}
/**
* Get cache storage data for the specified renderer. Because each renderer
* will cache data in different formats, it's necessary to store cache data
* keyed by the renderer object. Otherwise, attempting to draw the same
* image to both a PGraphicsJava2D and a PGraphicsOpenGL will cause errors.
* @param renderer The PGraphics renderer associated to the image
* @return metadata stored for the specified renderer
*/
public Object getCache(PImage image) {
return g.getCache(image);
}
/**
* Remove information associated with this renderer from the cache, if any.
* @param renderer The PGraphics renderer whose cache data should be removed
*/
public void removeCache(PImage image) {
if (recorder != null) recorder.removeCache(image);
g.removeCache(image);
}
public PGL beginPGL() {
return g.beginPGL();
}
public void endPGL() {
if (recorder != null) recorder.endPGL();
g.endPGL();
}
public void flush() {
if (recorder != null) recorder.flush();
g.flush();
}
public void hint(int which) {
if (recorder != null) recorder.hint(which);
g.hint(which);
}
/**
* Start a new shape of type POLYGON
*/
public void beginShape() {
if (recorder != null) recorder.beginShape();
g.beginShape();
}
/**
* ( begin auto-generated from beginShape.xml )
*
* Using the <b>beginShape()</b> and <b>endShape()</b> functions allow
* creating more complex forms. <b>beginShape()</b> begins recording
* vertices for a shape and <b>endShape()</b> stops recording. The value of
* the <b>MODE</b> parameter tells it which types of shapes to create from
* the provided vertices. With no mode specified, the shape can be any
* irregular polygon. The parameters available for beginShape() are POINTS,
* LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, and QUAD_STRIP.
* After calling the <b>beginShape()</b> function, a series of
* <b>vertex()</b> commands must follow. To stop drawing the shape, call
* <b>endShape()</b>. The <b>vertex()</b> function with two parameters
* specifies a position in 2D and the <b>vertex()</b> function with three
* parameters specifies a position in 3D. Each shape will be outlined with
* the current stroke color and filled with the fill color.
* <br/> <br/>
* Transformations such as <b>translate()</b>, <b>rotate()</b>, and
* <b>scale()</b> do not work within <b>beginShape()</b>. It is also not
* possible to use other shapes, such as <b>ellipse()</b> or <b>rect()</b>
* within <b>beginShape()</b>.
* <br/> <br/>
* The P3D renderer settings allow <b>stroke()</b> and <b>fill()</b>
* settings to be altered per-vertex, however the default P2D renderer does
* not. Settings such as <b>strokeWeight()</b>, <b>strokeCap()</b>, and
* <b>strokeJoin()</b> cannot be changed while inside a
* <b>beginShape()</b>/<b>endShape()</b> block with any renderer.
*
* ( end auto-generated )
* @webref shape:vertex
* @param kind Either POINTS, LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, or QUAD_STRIP
* @see PGraphics#endShape()
* @see PGraphics#vertex(float, float, float, float, float)
* @see PGraphics#curveVertex(float, float, float)
* @see PGraphics#bezierVertex(float, float, float, float, float, float, float, float, float)
*/
public void beginShape(int kind) {
if (recorder != null) recorder.beginShape(kind);
g.beginShape(kind);
}
/**
* Sets whether the upcoming vertex is part of an edge.
* Equivalent to glEdgeFlag(), for people familiar with OpenGL.
*/
public void edge(boolean edge) {
if (recorder != null) recorder.edge(edge);
g.edge(edge);
}
/**
* ( begin auto-generated from normal.xml )
*
* Sets the current normal vector. This is for drawing three dimensional
* shapes and surfaces and specifies a vector perpendicular to the surface
* of the shape which determines how lighting affects it. Processing
* attempts to automatically assign normals to shapes, but since that's
* imperfect, this is a better option when you want more control. This
* function is identical to glNormal3f() in OpenGL.
*
* ( end auto-generated )
* @webref lights_camera:lights
* @param nx x direction
* @param ny y direction
* @param nz z direction
* @see PGraphics#beginShape(int)
* @see PGraphics#endShape(int)
* @see PGraphics#lights()
*/
public void normal(float nx, float ny, float nz) {
if (recorder != null) recorder.normal(nx, ny, nz);
g.normal(nx, ny, nz);
}
/**
* ( begin auto-generated from textureMode.xml )
*
* Sets the coordinate space for texture mapping. There are two options,
* IMAGE, which refers to the actual coordinates of the image, and
* NORMAL, which refers to a normalized space of values ranging from 0
* to 1. The default mode is IMAGE. In IMAGE, if an image is 100 x 200
* pixels, mapping the image onto the entire size of a quad would require
* the points (0,0) (0,100) (100,200) (0,200). The same mapping in
* NORMAL_SPACE is (0,0) (0,1) (1,1) (0,1).
*
* ( end auto-generated )
* @webref image:textures
* @param mode either IMAGE or NORMAL
* @see PGraphics#texture(PImage)
*/
public void textureMode(int mode) {
if (recorder != null) recorder.textureMode(mode);
g.textureMode(mode);
}
/**
* ( begin auto-generated from textureWrap.xml )
*
* Description to come...
*
* ( end auto-generated from textureWrap.xml )
*
* @webref image:textures
* @param wrap Either CLAMP (default) or REPEAT
*/
public void textureWrap(int wrap) {
if (recorder != null) recorder.textureWrap(wrap);
g.textureWrap(wrap);
}
/**
* ( begin auto-generated from texture.xml )
*
* Sets a texture to be applied to vertex points. The <b>texture()</b>
* function must be called between <b>beginShape()</b> and
* <b>endShape()</b> and before any calls to <b>vertex()</b>.
* <br/> <br/>
* When textures are in use, the fill color is ignored. Instead, use tint()
* to specify the color of the texture as it is applied to the shape.
*
* ( end auto-generated )
* @webref image:textures
* @param image reference to a PImage object
* @see PGraphics#textureMode(int)
* @see PGraphics#beginShape(int)
* @see PGraphics#endShape(int)
* @see PGraphics#vertex(float, float, float, float, float)
*/
public void texture(PImage image) {
if (recorder != null) recorder.texture(image);
g.texture(image);
}
/**
* Removes texture image for current shape.
* Needs to be called between beginShape and endShape
*
*/
public void noTexture() {
if (recorder != null) recorder.noTexture();
g.noTexture();
}
public void vertex(float x, float y) {
if (recorder != null) recorder.vertex(x, y);
g.vertex(x, y);
}
public void vertex(float x, float y, float z) {
if (recorder != null) recorder.vertex(x, y, z);
g.vertex(x, y, z);
}
/**
* Used by renderer subclasses or PShape to efficiently pass in already
* formatted vertex information.
* @param v vertex parameters, as a float array of length VERTEX_FIELD_COUNT
*/
public void vertex(float[] v) {
if (recorder != null) recorder.vertex(v);
g.vertex(v);
}
public void vertex(float x, float y, float u, float v) {
if (recorder != null) recorder.vertex(x, y, u, v);
g.vertex(x, y, u, v);
}
/**
* ( begin auto-generated from vertex.xml )
*
* All shapes are constructed by connecting a series of vertices.
* <b>vertex()</b> is used to specify the vertex coordinates for points,
* lines, triangles, quads, and polygons and is used exclusively within the
* <b>beginShape()</b> and <b>endShape()</b> function.<br />
* <br />
* Drawing a vertex in 3D using the <b>z</b> parameter requires the P3D
* parameter in combination with size as shown in the above example.<br />
* <br />
* This function is also used to map a texture onto the geometry. The
* <b>texture()</b> function declares the texture to apply to the geometry
* and the <b>u</b> and <b>v</b> coordinates set define the mapping of this
* texture to the form. By default, the coordinates used for <b>u</b> and
* <b>v</b> are specified in relation to the image's size in pixels, but
* this relation can be changed with <b>textureMode()</b>.
*
* ( end auto-generated )
* @webref shape:vertex
* @param x x-coordinate of the vertex
* @param y y-coordinate of the vertex
* @param z z-coordinate of the vertex
* @param u horizontal coordinate for the texture mapping
* @param v vertical coordinate for the texture mapping
* @see PGraphics#beginShape(int)
* @see PGraphics#endShape(int)
* @see PGraphics#bezierVertex(float, float, float, float, float, float, float, float, float)
* @see PGraphics#quadraticVertex(float, float, float, float, float, float)
* @see PGraphics#curveVertex(float, float, float)
* @see PGraphics#texture(PImage)
*/
public void vertex(float x, float y, float z, float u, float v) {
if (recorder != null) recorder.vertex(x, y, z, u, v);
g.vertex(x, y, z, u, v);
}
/**
* @webref shape:vertex
*/
public void beginContour() {
if (recorder != null) recorder.beginContour();
g.beginContour();
}
/**
* @webref shape:vertex
*/
public void endContour() {
if (recorder != null) recorder.endContour();
g.endContour();
}
public void endShape() {
if (recorder != null) recorder.endShape();
g.endShape();
}
/**
* ( begin auto-generated from endShape.xml )
*
* The <b>endShape()</b> function is the companion to <b>beginShape()</b>
* and may only be called after <b>beginShape()</b>. When <b>endshape()</b>
* is called, all of image data defined since the previous call to
* <b>beginShape()</b> is written into the image buffer. The constant CLOSE
* as the value for the MODE parameter to close the shape (to connect the
* beginning and the end).
*
* ( end auto-generated )
* @webref shape:vertex
* @param mode use CLOSE to close the shape
* @see PGraphics#beginShape(int)
*/
public void endShape(int mode) {
if (recorder != null) recorder.endShape(mode);
g.endShape(mode);
}
/**
* @webref shape
* @param filename name of file to load, can be .svg or .obj
* @see PShape
* @see PApplet#createShape()
*/
public PShape loadShape(String filename) {
return g.loadShape(filename);
}
public PShape loadShape(String filename, String options) {
return g.loadShape(filename, options);
}
/**
* @webref shape
* @see PShape
* @see PShape#endShape()
* @see PApplet#loadShape(String)
*/
public PShape createShape() {
return g.createShape();
}
public PShape createShape(PShape source) {
return g.createShape(source);
}
/**
* @param type either POINTS, LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, QUAD_STRIP
*/
public PShape createShape(int type) {
return g.createShape(type);
}
/**
* @param kind either LINE, TRIANGLE, RECT, ELLIPSE, ARC, SPHERE, BOX
* @param p parameters that match the kind of shape
*/
public PShape createShape(int kind, float... p) {
return g.createShape(kind, p);
}
/**
* ( begin auto-generated from loadShader.xml )
*
* This is a new reference entry for Processing 2.0. It will be updated shortly.
*
* ( end auto-generated )
*
* @webref rendering:shaders
* @param fragFilename name of fragment shader file
*/
public PShader loadShader(String fragFilename) {
return g.loadShader(fragFilename);
}
/**
* @param vertFilename name of vertex shader file
*/
public PShader loadShader(String fragFilename, String vertFilename) {
return g.loadShader(fragFilename, vertFilename);
}
/**
* ( begin auto-generated from shader.xml )
*
* This is a new reference entry for Processing 2.0. It will be updated shortly.
*
* ( end auto-generated )
*
* @webref rendering:shaders
* @param shader name of shader file
*/
public void shader(PShader shader) {
if (recorder != null) recorder.shader(shader);
g.shader(shader);
}
/**
* @param kind type of shader, either POINTS, LINES, or TRIANGLES
*/
public void shader(PShader shader, int kind) {
if (recorder != null) recorder.shader(shader, kind);
g.shader(shader, kind);
}
/**
* ( begin auto-generated from resetShader.xml )
*
* This is a new reference entry for Processing 2.0. It will be updated shortly.
*
* ( end auto-generated )
*
* @webref rendering:shaders
*/
public void resetShader() {
if (recorder != null) recorder.resetShader();
g.resetShader();
}
/**
* @param kind type of shader, either POINTS, LINES, or TRIANGLES
*/
public void resetShader(int kind) {
if (recorder != null) recorder.resetShader(kind);
g.resetShader(kind);
}
/**
* @param shader the fragment shader to apply
*/
public void filter(PShader shader) {
if (recorder != null) recorder.filter(shader);
g.filter(shader);
}
/*
* @webref rendering:shaders
* @param a x-coordinate of the rectangle by default
* @param b y-coordinate of the rectangle by default
* @param c width of the rectangle by default
* @param d height of the rectangle by default
*/
public void clip(float a, float b, float c, float d) {
if (recorder != null) recorder.clip(a, b, c, d);
g.clip(a, b, c, d);
}
/*
* @webref rendering:shaders
*/
public void noClip() {
if (recorder != null) recorder.noClip();
g.noClip();
}
/**
* ( begin auto-generated from blendMode.xml )
*
* This is a new reference entry for Processing 2.0. It will be updated shortly.
*
* ( end auto-generated )
*
* @webref Rendering
* @param mode the blending mode to use
*/
public void blendMode(int mode) {
if (recorder != null) recorder.blendMode(mode);
g.blendMode(mode);
}
public void bezierVertex(float x2, float y2,
float x3, float y3,
float x4, float y4) {
if (recorder != null) recorder.bezierVertex(x2, y2, x3, y3, x4, y4);
g.bezierVertex(x2, y2, x3, y3, x4, y4);
}
/**
* ( begin auto-generated from bezierVertex.xml )
*
* Specifies vertex coordinates for Bezier curves. Each call to
* <b>bezierVertex()</b> defines the position of two control points and one
* anchor point of a Bezier curve, adding a new segment to a line or shape.
* The first time <b>bezierVertex()</b> is used within a
* <b>beginShape()</b> call, it must be prefaced with a call to
* <b>vertex()</b> to set the first anchor point. This function must be
* used between <b>beginShape()</b> and <b>endShape()</b> and only when
* there is no MODE parameter specified to <b>beginShape()</b>. Using the
* 3D version requires rendering with P3D (see the Environment reference
* for more information).
*
* ( end auto-generated )
* @webref shape:vertex
* @param x2 the x-coordinate of the 1st control point
* @param y2 the y-coordinate of the 1st control point
* @param z2 the z-coordinate of the 1st control point
* @param x3 the x-coordinate of the 2nd control point
* @param y3 the y-coordinate of the 2nd control point
* @param z3 the z-coordinate of the 2nd control point
* @param x4 the x-coordinate of the anchor point
* @param y4 the y-coordinate of the anchor point
* @param z4 the z-coordinate of the anchor point
* @see PGraphics#curveVertex(float, float, float)
* @see PGraphics#vertex(float, float, float, float, float)
* @see PGraphics#quadraticVertex(float, float, float, float, float, float)
* @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
*/
public void bezierVertex(float x2, float y2, float z2,
float x3, float y3, float z3,
float x4, float y4, float z4) {
if (recorder != null) recorder.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4);
g.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4);
}
/**
* @webref shape:vertex
* @param cx the x-coordinate of the control point
* @param cy the y-coordinate of the control point
* @param x3 the x-coordinate of the anchor point
* @param y3 the y-coordinate of the anchor point
* @see PGraphics#curveVertex(float, float, float)
* @see PGraphics#vertex(float, float, float, float, float)
* @see PGraphics#bezierVertex(float, float, float, float, float, float)
* @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
*/
public void quadraticVertex(float cx, float cy,
float x3, float y3) {
if (recorder != null) recorder.quadraticVertex(cx, cy, x3, y3);
g.quadraticVertex(cx, cy, x3, y3);
}
/**
* @param cz the z-coordinate of the control point
* @param z3 the z-coordinate of the anchor point
*/
public void quadraticVertex(float cx, float cy, float cz,
float x3, float y3, float z3) {
if (recorder != null) recorder.quadraticVertex(cx, cy, cz, x3, y3, z3);
g.quadraticVertex(cx, cy, cz, x3, y3, z3);
}
/**
* ( begin auto-generated from curveVertex.xml )
*
* Specifies vertex coordinates for curves. This function may only be used
* between <b>beginShape()</b> and <b>endShape()</b> and only when there is
* no MODE parameter specified to <b>beginShape()</b>. The first and last
* points in a series of <b>curveVertex()</b> lines will be used to guide
* the beginning and end of a the curve. A minimum of four points is
* required to draw a tiny curve between the second and third points.
* Adding a fifth point with <b>curveVertex()</b> will draw the curve
* between the second, third, and fourth points. The <b>curveVertex()</b>
* function is an implementation of Catmull-Rom splines. Using the 3D
* version requires rendering with P3D (see the Environment reference for
* more information).
*
* ( end auto-generated )
*
* @webref shape:vertex
* @param x the x-coordinate of the vertex
* @param y the y-coordinate of the vertex
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#beginShape(int)
* @see PGraphics#endShape(int)
* @see PGraphics#vertex(float, float, float, float, float)
* @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#quadraticVertex(float, float, float, float, float, float)
*/
public void curveVertex(float x, float y) {
if (recorder != null) recorder.curveVertex(x, y);
g.curveVertex(x, y);
}
/**
* @param z the z-coordinate of the vertex
*/
public void curveVertex(float x, float y, float z) {
if (recorder != null) recorder.curveVertex(x, y, z);
g.curveVertex(x, y, z);
}
/**
* ( begin auto-generated from point.xml )
*
* Draws a point, a coordinate in space at the dimension of one pixel. The
* first parameter is the horizontal value for the point, the second value
* is the vertical value for the point, and the optional third value is the
* depth value. Drawing this shape in 3D with the <b>z</b> parameter
* requires the P3D parameter in combination with <b>size()</b> as shown in
* the above example.
*
* ( end auto-generated )
*
* @webref shape:2d_primitives
* @param x x-coordinate of the point
* @param y y-coordinate of the point
*/
public void point(float x, float y) {
if (recorder != null) recorder.point(x, y);
g.point(x, y);
}
/**
* @param z z-coordinate of the point
*/
public void point(float x, float y, float z) {
if (recorder != null) recorder.point(x, y, z);
g.point(x, y, z);
}
/**
* ( begin auto-generated from line.xml )
*
* Draws a line (a direct path between two points) to the screen. The
* version of <b>line()</b> with four parameters draws the line in 2D. To
* color a line, use the <b>stroke()</b> function. A line cannot be filled,
* therefore the <b>fill()</b> function will not affect the color of a
* line. 2D lines are drawn with a width of one pixel by default, but this
* can be changed with the <b>strokeWeight()</b> function. The version with
* six parameters allows the line to be placed anywhere within XYZ space.
* Drawing this shape in 3D with the <b>z</b> parameter requires the P3D
* parameter in combination with <b>size()</b> as shown in the above example.
*
* ( end auto-generated )
* @webref shape:2d_primitives
* @param x1 x-coordinate of the first point
* @param y1 y-coordinate of the first point
* @param x2 x-coordinate of the second point
* @param y2 y-coordinate of the second point
* @see PGraphics#strokeWeight(float)
* @see PGraphics#strokeJoin(int)
* @see PGraphics#strokeCap(int)
* @see PGraphics#beginShape()
*/
public void line(float x1, float y1, float x2, float y2) {
if (recorder != null) recorder.line(x1, y1, x2, y2);
g.line(x1, y1, x2, y2);
}
/**
* @param z1 z-coordinate of the first point
* @param z2 z-coordinate of the second point
*/
public void line(float x1, float y1, float z1,
float x2, float y2, float z2) {
if (recorder != null) recorder.line(x1, y1, z1, x2, y2, z2);
g.line(x1, y1, z1, x2, y2, z2);
}
/**
* ( begin auto-generated from triangle.xml )
*
* A triangle is a plane created by connecting three points. The first two
* arguments specify the first point, the middle two arguments specify the
* second point, and the last two arguments specify the third point.
*
* ( end auto-generated )
* @webref shape:2d_primitives
* @param x1 x-coordinate of the first point
* @param y1 y-coordinate of the first point
* @param x2 x-coordinate of the second point
* @param y2 y-coordinate of the second point
* @param x3 x-coordinate of the third point
* @param y3 y-coordinate of the third point
* @see PApplet#beginShape()
*/
public void triangle(float x1, float y1, float x2, float y2,
float x3, float y3) {
if (recorder != null) recorder.triangle(x1, y1, x2, y2, x3, y3);
g.triangle(x1, y1, x2, y2, x3, y3);
}
/**
* ( begin auto-generated from quad.xml )
*
* A quad is a quadrilateral, a four sided polygon. It is similar to a
* rectangle, but the angles between its edges are not constrained to
* ninety degrees. The first pair of parameters (x1,y1) sets the first
* vertex and the subsequent pairs should proceed clockwise or
* counter-clockwise around the defined shape.
*
* ( end auto-generated )
* @webref shape:2d_primitives
* @param x1 x-coordinate of the first corner
* @param y1 y-coordinate of the first corner
* @param x2 x-coordinate of the second corner
* @param y2 y-coordinate of the second corner
* @param x3 x-coordinate of the third corner
* @param y3 y-coordinate of the third corner
* @param x4 x-coordinate of the fourth corner
* @param y4 y-coordinate of the fourth corner
*/
public void quad(float x1, float y1, float x2, float y2,
float x3, float y3, float x4, float y4) {
if (recorder != null) recorder.quad(x1, y1, x2, y2, x3, y3, x4, y4);
g.quad(x1, y1, x2, y2, x3, y3, x4, y4);
}
/**
* ( begin auto-generated from rectMode.xml )
*
* Modifies the location from which rectangles draw. The default mode is
* <b>rectMode(CORNER)</b>, which specifies the location to be the upper
* left corner of the shape and uses the third and fourth parameters of
* <b>rect()</b> to specify the width and height. The syntax
* <b>rectMode(CORNERS)</b> uses the first and second parameters of
* <b>rect()</b> to set the location of one corner and uses the third and
* fourth parameters to set the opposite corner. The syntax
* <b>rectMode(CENTER)</b> draws the image from its center point and uses
* the third and forth parameters of <b>rect()</b> to specify the image's
* width and height. The syntax <b>rectMode(RADIUS)</b> draws the image
* from its center point and uses the third and forth parameters of
* <b>rect()</b> to specify half of the image's width and height. The
* parameter must be written in ALL CAPS because Processing is a case
* sensitive language. Note: In version 125, the mode named CENTER_RADIUS
* was shortened to RADIUS.
*
* ( end auto-generated )
* @webref shape:attributes
* @param mode either CORNER, CORNERS, CENTER, or RADIUS
* @see PGraphics#rect(float, float, float, float)
*/
public void rectMode(int mode) {
if (recorder != null) recorder.rectMode(mode);
g.rectMode(mode);
}
/**
* ( begin auto-generated from rect.xml )
*
* Draws a rectangle to the screen. A rectangle is a four-sided shape with
* every angle at ninety degrees. By default, the first two parameters set
* the location of the upper-left corner, the third sets the width, and the
* fourth sets the height. These parameters may be changed with the
* <b>rectMode()</b> function.
*
* ( end auto-generated )
*
* @webref shape:2d_primitives
* @param a x-coordinate of the rectangle by default
* @param b y-coordinate of the rectangle by default
* @param c width of the rectangle by default
* @param d height of the rectangle by default
* @see PGraphics#rectMode(int)
* @see PGraphics#quad(float, float, float, float, float, float, float, float)
*/
public void rect(float a, float b, float c, float d) {
if (recorder != null) recorder.rect(a, b, c, d);
g.rect(a, b, c, d);
}
/**
* @param r radii for all four corners
*/
public void rect(float a, float b, float c, float d, float r) {
if (recorder != null) recorder.rect(a, b, c, d, r);
g.rect(a, b, c, d, r);
}
/**
* @param tl radius for top-left corner
* @param tr radius for top-right corner
* @param br radius for bottom-right corner
* @param bl radius for bottom-left corner
*/
public void rect(float a, float b, float c, float d,
float tl, float tr, float br, float bl) {
if (recorder != null) recorder.rect(a, b, c, d, tl, tr, br, bl);
g.rect(a, b, c, d, tl, tr, br, bl);
}
/**
* ( begin auto-generated from ellipseMode.xml )
*
* The origin of the ellipse is modified by the <b>ellipseMode()</b>
* function. The default configuration is <b>ellipseMode(CENTER)</b>, which
* specifies the location of the ellipse as the center of the shape. The
* <b>RADIUS</b> mode is the same, but the width and height parameters to
* <b>ellipse()</b> specify the radius of the ellipse, rather than the
* diameter. The <b>CORNER</b> mode draws the shape from the upper-left
* corner of its bounding box. The <b>CORNERS</b> mode uses the four
* parameters to <b>ellipse()</b> to set two opposing corners of the
* ellipse's bounding box. The parameter must be written in ALL CAPS
* because Processing is a case-sensitive language.
*
* ( end auto-generated )
* @webref shape:attributes
* @param mode either CENTER, RADIUS, CORNER, or CORNERS
* @see PApplet#ellipse(float, float, float, float)
* @see PApplet#arc(float, float, float, float, float, float)
*/
public void ellipseMode(int mode) {
if (recorder != null) recorder.ellipseMode(mode);
g.ellipseMode(mode);
}
/**
* ( begin auto-generated from ellipse.xml )
*
* Draws an ellipse (oval) in the display window. An ellipse with an equal
* <b>width</b> and <b>height</b> is a circle. The first two parameters set
* the location, the third sets the width, and the fourth sets the height.
* The origin may be changed with the <b>ellipseMode()</b> function.
*
* ( end auto-generated )
* @webref shape:2d_primitives
* @param a x-coordinate of the ellipse
* @param b y-coordinate of the ellipse
* @param c width of the ellipse by default
* @param d height of the ellipse by default
* @see PApplet#ellipseMode(int)
* @see PApplet#arc(float, float, float, float, float, float)
*/
public void ellipse(float a, float b, float c, float d) {
if (recorder != null) recorder.ellipse(a, b, c, d);
g.ellipse(a, b, c, d);
}
/**
* ( begin auto-generated from arc.xml )
*
* Draws an arc in the display window. Arcs are drawn along the outer edge
* of an ellipse defined by the <b>x</b>, <b>y</b>, <b>width</b> and
* <b>height</b> parameters. The origin or the arc's ellipse may be changed
* with the <b>ellipseMode()</b> function. The <b>start</b> and <b>stop</b>
* parameters specify the angles at which to draw the arc.
*
* ( end auto-generated )
* @webref shape:2d_primitives
* @param a x-coordinate of the arc's ellipse
* @param b y-coordinate of the arc's ellipse
* @param c width of the arc's ellipse by default
* @param d height of the arc's ellipse by default
* @param start angle to start the arc, specified in radians
* @param stop angle to stop the arc, specified in radians
* @see PApplet#ellipse(float, float, float, float)
* @see PApplet#ellipseMode(int)
* @see PApplet#radians(float)
* @see PApplet#degrees(float)
*/
public void arc(float a, float b, float c, float d,
float start, float stop) {
if (recorder != null) recorder.arc(a, b, c, d, start, stop);
g.arc(a, b, c, d, start, stop);
}
/*
* @param mode either OPEN, CHORD, or PIE
*/
public void arc(float a, float b, float c, float d,
float start, float stop, int mode) {
if (recorder != null) recorder.arc(a, b, c, d, start, stop, mode);
g.arc(a, b, c, d, start, stop, mode);
}
/**
* ( begin auto-generated from box.xml )
*
* A box is an extruded rectangle. A box with equal dimension on all sides
* is a cube.
*
* ( end auto-generated )
*
* @webref shape:3d_primitives
* @param size dimension of the box in all dimensions (creates a cube)
* @see PGraphics#sphere(float)
*/
public void box(float size) {
if (recorder != null) recorder.box(size);
g.box(size);
}
/**
* @param w dimension of the box in the x-dimension
* @param h dimension of the box in the y-dimension
* @param d dimension of the box in the z-dimension
*/
public void box(float w, float h, float d) {
if (recorder != null) recorder.box(w, h, d);
g.box(w, h, d);
}
/**
* ( begin auto-generated from sphereDetail.xml )
*
* Controls the detail used to render a sphere by adjusting the number of
* vertices of the sphere mesh. The default resolution is 30, which creates
* a fairly detailed sphere definition with vertices every 360/30 = 12
* degrees. If you're going to render a great number of spheres per frame,
* it is advised to reduce the level of detail using this function. The
* setting stays active until <b>sphereDetail()</b> is called again with a
* new parameter and so should <i>not</i> be called prior to every
* <b>sphere()</b> statement, unless you wish to render spheres with
* different settings, e.g. using less detail for smaller spheres or ones
* further away from the camera. To control the detail of the horizontal
* and vertical resolution independently, use the version of the functions
* with two parameters.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Code for sphereDetail() submitted by toxi [031031].
* Code for enhanced u/v version from davbol [080801].
*
* @param res number of segments (minimum 3) used per full circle revolution
* @webref shape:3d_primitives
* @see PGraphics#sphere(float)
*/
public void sphereDetail(int res) {
if (recorder != null) recorder.sphereDetail(res);
g.sphereDetail(res);
}
/**
* @param ures number of segments used longitudinally per full circle revolutoin
* @param vres number of segments used latitudinally from top to bottom
*/
public void sphereDetail(int ures, int vres) {
if (recorder != null) recorder.sphereDetail(ures, vres);
g.sphereDetail(ures, vres);
}
/**
* ( begin auto-generated from sphere.xml )
*
* A sphere is a hollow ball made from tessellated triangles.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* <P>
* Implementation notes:
* <P>
* cache all the points of the sphere in a static array
* top and bottom are just a bunch of triangles that land
* in the center point
* <P>
* sphere is a series of concentric circles who radii vary
* along the shape, based on, er.. cos or something
* <PRE>
* [toxi 031031] new sphere code. removed all multiplies with
* radius, as scale() will take care of that anyway
*
* [toxi 031223] updated sphere code (removed modulos)
* and introduced sphereAt(x,y,z,r)
* to avoid additional translate()'s on the user/sketch side
*
* [davbol 080801] now using separate sphereDetailU/V
* </PRE>
*
* @webref shape:3d_primitives
* @param r the radius of the sphere
* @see PGraphics#sphereDetail(int)
*/
public void sphere(float r) {
if (recorder != null) recorder.sphere(r);
g.sphere(r);
}
/**
* ( begin auto-generated from bezierPoint.xml )
*
* Evaluates the Bezier at point t for points a, b, c, d. The parameter t
* varies between 0 and 1, a and d are points on the curve, and b and c are
* the control points. This can be done once with the x coordinates and a
* second time with the y coordinates to get the location of a bezier curve
* at t.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* For instance, to convert the following example:<PRE>
* stroke(255, 102, 0);
* line(85, 20, 10, 10);
* line(90, 90, 15, 80);
* stroke(0, 0, 0);
* bezier(85, 20, 10, 10, 90, 90, 15, 80);
*
* // draw it in gray, using 10 steps instead of the default 20
* // this is a slower way to do it, but useful if you need
* // to do things with the coordinates at each step
* stroke(128);
* beginShape(LINE_STRIP);
* for (int i = 0; i <= 10; i++) {
* float t = i / 10.0f;
* float x = bezierPoint(85, 10, 90, 15, t);
* float y = bezierPoint(20, 10, 90, 80, t);
* vertex(x, y);
* }
* endShape();</PRE>
*
* @webref shape:curves
* @param a coordinate of first point on the curve
* @param b coordinate of first control point
* @param c coordinate of second control point
* @param d coordinate of second point on the curve
* @param t value between 0 and 1
* @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#bezierVertex(float, float, float, float, float, float)
* @see PGraphics#curvePoint(float, float, float, float, float)
*/
public float bezierPoint(float a, float b, float c, float d, float t) {
return g.bezierPoint(a, b, c, d, t);
}
/**
* ( begin auto-generated from bezierTangent.xml )
*
* Calculates the tangent of a point on a Bezier curve. There is a good
* definition of <a href="http://en.wikipedia.org/wiki/Tangent"
* target="new"><em>tangent</em> on Wikipedia</a>.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Code submitted by Dave Bollinger (davol) for release 0136.
*
* @webref shape:curves
* @param a coordinate of first point on the curve
* @param b coordinate of first control point
* @param c coordinate of second control point
* @param d coordinate of second point on the curve
* @param t value between 0 and 1
* @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#bezierVertex(float, float, float, float, float, float)
* @see PGraphics#curvePoint(float, float, float, float, float)
*/
public float bezierTangent(float a, float b, float c, float d, float t) {
return g.bezierTangent(a, b, c, d, t);
}
/**
* ( begin auto-generated from bezierDetail.xml )
*
* Sets the resolution at which Beziers display. The default value is 20.
* This function is only useful when using the P3D renderer as the default
* P2D renderer does not use this information.
*
* ( end auto-generated )
*
* @webref shape:curves
* @param detail resolution of the curves
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#curveVertex(float, float, float)
* @see PGraphics#curveTightness(float)
*/
public void bezierDetail(int detail) {
if (recorder != null) recorder.bezierDetail(detail);
g.bezierDetail(detail);
}
public void bezier(float x1, float y1,
float x2, float y2,
float x3, float y3,
float x4, float y4) {
if (recorder != null) recorder.bezier(x1, y1, x2, y2, x3, y3, x4, y4);
g.bezier(x1, y1, x2, y2, x3, y3, x4, y4);
}
/**
* ( begin auto-generated from bezier.xml )
*
* Draws a Bezier curve on the screen. These curves are defined by a series
* of anchor and control points. The first two parameters specify the first
* anchor point and the last two parameters specify the other anchor point.
* The middle parameters specify the control points which define the shape
* of the curve. Bezier curves were developed by French engineer Pierre
* Bezier. Using the 3D version requires rendering with P3D (see the
* Environment reference for more information).
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Draw a cubic bezier curve. The first and last points are
* the on-curve points. The middle two are the 'control' points,
* or 'handles' in an application like Illustrator.
* <P>
* Identical to typing:
* <PRE>beginShape();
* vertex(x1, y1);
* bezierVertex(x2, y2, x3, y3, x4, y4);
* endShape();
* </PRE>
* In Postscript-speak, this would be:
* <PRE>moveto(x1, y1);
* curveto(x2, y2, x3, y3, x4, y4);</PRE>
* If you were to try and continue that curve like so:
* <PRE>curveto(x5, y5, x6, y6, x7, y7);</PRE>
* This would be done in processing by adding these statements:
* <PRE>bezierVertex(x5, y5, x6, y6, x7, y7)
* </PRE>
* To draw a quadratic (instead of cubic) curve,
* use the control point twice by doubling it:
* <PRE>bezier(x1, y1, cx, cy, cx, cy, x2, y2);</PRE>
*
* @webref shape:curves
* @param x1 coordinates for the first anchor point
* @param y1 coordinates for the first anchor point
* @param z1 coordinates for the first anchor point
* @param x2 coordinates for the first control point
* @param y2 coordinates for the first control point
* @param z2 coordinates for the first control point
* @param x3 coordinates for the second control point
* @param y3 coordinates for the second control point
* @param z3 coordinates for the second control point
* @param x4 coordinates for the second anchor point
* @param y4 coordinates for the second anchor point
* @param z4 coordinates for the second anchor point
*
* @see PGraphics#bezierVertex(float, float, float, float, float, float)
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
*/
public void bezier(float x1, float y1, float z1,
float x2, float y2, float z2,
float x3, float y3, float z3,
float x4, float y4, float z4) {
if (recorder != null) recorder.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
g.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
}
/**
* ( begin auto-generated from curvePoint.xml )
*
* Evalutes the curve at point t for points a, b, c, d. The parameter t
* varies between 0 and 1, a and d are points on the curve, and b and c are
* the control points. This can be done once with the x coordinates and a
* second time with the y coordinates to get the location of a curve at t.
*
* ( end auto-generated )
*
* @webref shape:curves
* @param a coordinate of first point on the curve
* @param b coordinate of second point on the curve
* @param c coordinate of third point on the curve
* @param d coordinate of fourth point on the curve
* @param t value between 0 and 1
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#curveVertex(float, float)
* @see PGraphics#bezierPoint(float, float, float, float, float)
*/
public float curvePoint(float a, float b, float c, float d, float t) {
return g.curvePoint(a, b, c, d, t);
}
/**
* ( begin auto-generated from curveTangent.xml )
*
* Calculates the tangent of a point on a curve. There's a good definition
* of <em><a href="http://en.wikipedia.org/wiki/Tangent"
* target="new">tangent</em> on Wikipedia</a>.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Code thanks to Dave Bollinger (Bug #715)
*
* @webref shape:curves
* @param a coordinate of first point on the curve
* @param b coordinate of first control point
* @param c coordinate of second control point
* @param d coordinate of second point on the curve
* @param t value between 0 and 1
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#curveVertex(float, float)
* @see PGraphics#curvePoint(float, float, float, float, float)
* @see PGraphics#bezierTangent(float, float, float, float, float)
*/
public float curveTangent(float a, float b, float c, float d, float t) {
return g.curveTangent(a, b, c, d, t);
}
/**
* ( begin auto-generated from curveDetail.xml )
*
* Sets the resolution at which curves display. The default value is 20.
* This function is only useful when using the P3D renderer as the default
* P2D renderer does not use this information.
*
* ( end auto-generated )
*
* @webref shape:curves
* @param detail resolution of the curves
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#curveVertex(float, float)
* @see PGraphics#curveTightness(float)
*/
public void curveDetail(int detail) {
if (recorder != null) recorder.curveDetail(detail);
g.curveDetail(detail);
}
/**
* ( begin auto-generated from curveTightness.xml )
*
* Modifies the quality of forms created with <b>curve()</b> and
* <b>curveVertex()</b>. The parameter <b>squishy</b> determines how the
* curve fits to the vertex points. The value 0.0 is the default value for
* <b>squishy</b> (this value defines the curves to be Catmull-Rom splines)
* and the value 1.0 connects all the points with straight lines. Values
* within the range -5.0 and 5.0 will deform the curves but will leave them
* recognizable and as values increase in magnitude, they will continue to deform.
*
* ( end auto-generated )
*
* @webref shape:curves
* @param tightness amount of deformation from the original vertices
* @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#curveVertex(float, float)
*/
public void curveTightness(float tightness) {
if (recorder != null) recorder.curveTightness(tightness);
g.curveTightness(tightness);
}
/**
* ( begin auto-generated from curve.xml )
*
* Draws a curved line on the screen. The first and second parameters
* specify the beginning control point and the last two parameters specify
* the ending control point. The middle parameters specify the start and
* stop of the curve. Longer curves can be created by putting a series of
* <b>curve()</b> functions together or using <b>curveVertex()</b>. An
* additional function called <b>curveTightness()</b> provides control for
* the visual quality of the curve. The <b>curve()</b> function is an
* implementation of Catmull-Rom splines. Using the 3D version requires
* rendering with P3D (see the Environment reference for more information).
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* As of revision 0070, this function no longer doubles the first
* and last points. The curves are a bit more boring, but it's more
* mathematically correct, and properly mirrored in curvePoint().
* <P>
* Identical to typing out:<PRE>
* beginShape();
* curveVertex(x1, y1);
* curveVertex(x2, y2);
* curveVertex(x3, y3);
* curveVertex(x4, y4);
* endShape();
* </PRE>
*
* @webref shape:curves
* @param x1 coordinates for the beginning control point
* @param y1 coordinates for the beginning control point
* @param x2 coordinates for the first point
* @param y2 coordinates for the first point
* @param x3 coordinates for the second point
* @param y3 coordinates for the second point
* @param x4 coordinates for the ending control point
* @param y4 coordinates for the ending control point
* @see PGraphics#curveVertex(float, float)
* @see PGraphics#curveTightness(float)
* @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float)
*/
public void curve(float x1, float y1,
float x2, float y2,
float x3, float y3,
float x4, float y4) {
if (recorder != null) recorder.curve(x1, y1, x2, y2, x3, y3, x4, y4);
g.curve(x1, y1, x2, y2, x3, y3, x4, y4);
}
/**
* @param z1 coordinates for the beginning control point
* @param z2 coordinates for the first point
* @param z3 coordinates for the second point
* @param z4 coordinates for the ending control point
*/
public void curve(float x1, float y1, float z1,
float x2, float y2, float z2,
float x3, float y3, float z3,
float x4, float y4, float z4) {
if (recorder != null) recorder.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
g.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4);
}
/**
* ( begin auto-generated from smooth.xml )
*
* Draws all geometry with smooth (anti-aliased) edges. This will sometimes
* slow down the frame rate of the application, but will enhance the visual
* refinement. Note that <b>smooth()</b> will also improve image quality of
* resized images, and <b>noSmooth()</b> will disable image (and font)
* smoothing altogether.
*
* ( end auto-generated )
*
* @webref shape:attributes
* @see PGraphics#noSmooth()
* @see PGraphics#hint(int)
* @see PApplet#size(int, int, String)
*/
public void smooth() {
if (recorder != null) recorder.smooth();
g.smooth();
}
/**
*
* @param level either 2, 4, or 8
*/
public void smooth(int level) {
if (recorder != null) recorder.smooth(level);
g.smooth(level);
}
/**
* ( begin auto-generated from noSmooth.xml )
*
* Draws all geometry with jagged (aliased) edges.
*
* ( end auto-generated )
* @webref shape:attributes
* @see PGraphics#smooth()
*/
public void noSmooth() {
if (recorder != null) recorder.noSmooth();
g.noSmooth();
}
/**
* ( begin auto-generated from imageMode.xml )
*
* Modifies the location from which images draw. The default mode is
* <b>imageMode(CORNER)</b>, which specifies the location to be the upper
* left corner and uses the fourth and fifth parameters of <b>image()</b>
* to set the image's width and height. The syntax
* <b>imageMode(CORNERS)</b> uses the second and third parameters of
* <b>image()</b> to set the location of one corner of the image and uses
* the fourth and fifth parameters to set the opposite corner. Use
* <b>imageMode(CENTER)</b> to draw images centered at the given x and y
* position.<br />
* <br />
* The parameter to <b>imageMode()</b> must be written in ALL CAPS because
* Processing is a case-sensitive language.
*
* ( end auto-generated )
*
* @webref image:loading_displaying
* @param mode either CORNER, CORNERS, or CENTER
* @see PApplet#loadImage(String, String)
* @see PImage
* @see PGraphics#image(PImage, float, float, float, float)
* @see PGraphics#background(float, float, float, float)
*/
public void imageMode(int mode) {
if (recorder != null) recorder.imageMode(mode);
g.imageMode(mode);
}
/**
* ( begin auto-generated from image.xml )
*
* Displays images to the screen. The images must be in the sketch's "data"
* directory to load correctly. Select "Add file..." from the "Sketch" menu
* to add the image. Processing currently works with GIF, JPEG, and Targa
* images. The <b>img</b> parameter specifies the image to display and the
* <b>x</b> and <b>y</b> parameters define the location of the image from
* its upper-left corner. The image is displayed at its original size
* unless the <b>width</b> and <b>height</b> parameters specify a different
* size.<br />
* <br />
* The <b>imageMode()</b> function changes the way the parameters work. For
* example, a call to <b>imageMode(CORNERS)</b> will change the
* <b>width</b> and <b>height</b> parameters to define the x and y values
* of the opposite corner of the image.<br />
* <br />
* The color of an image may be modified with the <b>tint()</b> function.
* This function will maintain transparency for GIF and PNG images.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Starting with release 0124, when using the default (JAVA2D) renderer,
* smooth() will also improve image quality of resized images.
*
* @webref image:loading_displaying
* @param img the image to display
* @param a x-coordinate of the image
* @param b y-coordinate of the image
* @see PApplet#loadImage(String, String)
* @see PImage
* @see PGraphics#imageMode(int)
* @see PGraphics#tint(float)
* @see PGraphics#background(float, float, float, float)
* @see PGraphics#alpha(int)
*/
public void image(PImage img, float a, float b) {
if (recorder != null) recorder.image(img, a, b);
g.image(img, a, b);
}
/**
* @param c width to display the image
* @param d height to display the image
*/
public void image(PImage img, float a, float b, float c, float d) {
if (recorder != null) recorder.image(img, a, b, c, d);
g.image(img, a, b, c, d);
}
/**
* Draw an image(), also specifying u/v coordinates.
* In this method, the u, v coordinates are always based on image space
* location, regardless of the current textureMode().
*
* @nowebref
*/
public void image(PImage img,
float a, float b, float c, float d,
int u1, int v1, int u2, int v2) {
if (recorder != null) recorder.image(img, a, b, c, d, u1, v1, u2, v2);
g.image(img, a, b, c, d, u1, v1, u2, v2);
}
/**
* ( begin auto-generated from shapeMode.xml )
*
* Modifies the location from which shapes draw. The default mode is
* <b>shapeMode(CORNER)</b>, which specifies the location to be the upper
* left corner of the shape and uses the third and fourth parameters of
* <b>shape()</b> to specify the width and height. The syntax
* <b>shapeMode(CORNERS)</b> uses the first and second parameters of
* <b>shape()</b> to set the location of one corner and uses the third and
* fourth parameters to set the opposite corner. The syntax
* <b>shapeMode(CENTER)</b> draws the shape from its center point and uses
* the third and forth parameters of <b>shape()</b> to specify the width
* and height. The parameter must be written in "ALL CAPS" because
* Processing is a case sensitive language.
*
* ( end auto-generated )
*
* @webref shape:loading_displaying
* @param mode either CORNER, CORNERS, CENTER
* @see PGraphics#shape(PShape)
* @see PGraphics#rectMode(int)
*/
public void shapeMode(int mode) {
if (recorder != null) recorder.shapeMode(mode);
g.shapeMode(mode);
}
public void shape(PShape shape) {
if (recorder != null) recorder.shape(shape);
g.shape(shape);
}
/**
* ( begin auto-generated from shape.xml )
*
* Displays shapes to the screen. The shapes must be in the sketch's "data"
* directory to load correctly. Select "Add file..." from the "Sketch" menu
* to add the shape. Processing currently works with SVG shapes only. The
* <b>sh</b> parameter specifies the shape to display and the <b>x</b> and
* <b>y</b> parameters define the location of the shape from its upper-left
* corner. The shape is displayed at its original size unless the
* <b>width</b> and <b>height</b> parameters specify a different size. The
* <b>shapeMode()</b> function changes the way the parameters work. A call
* to <b>shapeMode(CORNERS)</b>, for example, will change the width and
* height parameters to define the x and y values of the opposite corner of
* the shape.
* <br /><br />
* Note complex shapes may draw awkwardly with P3D. This renderer does not
* yet support shapes that have holes or complicated breaks.
*
* ( end auto-generated )
*
* @webref shape:loading_displaying
* @param shape the shape to display
* @param x x-coordinate of the shape
* @param y y-coordinate of the shape
* @see PShape
* @see PApplet#loadShape(String)
* @see PGraphics#shapeMode(int)
*
* Convenience method to draw at a particular location.
*/
public void shape(PShape shape, float x, float y) {
if (recorder != null) recorder.shape(shape, x, y);
g.shape(shape, x, y);
}
/**
* @param a x-coordinate of the shape
* @param b y-coordinate of the shape
* @param c width to display the shape
* @param d height to display the shape
*/
public void shape(PShape shape, float a, float b, float c, float d) {
if (recorder != null) recorder.shape(shape, a, b, c, d);
g.shape(shape, a, b, c, d);
}
public void textAlign(int alignX) {
if (recorder != null) recorder.textAlign(alignX);
g.textAlign(alignX);
}
/**
* ( begin auto-generated from textAlign.xml )
*
* Sets the current alignment for drawing text. The parameters LEFT,
* CENTER, and RIGHT set the display characteristics of the letters in
* relation to the values for the <b>x</b> and <b>y</b> parameters of the
* <b>text()</b> function.
* <br/> <br/>
* In Processing 0125 and later, an optional second parameter can be used
* to vertically align the text. BASELINE is the default, and the vertical
* alignment will be reset to BASELINE if the second parameter is not used.
* The TOP and CENTER parameters are straightforward. The BOTTOM parameter
* offsets the line based on the current <b>textDescent()</b>. For multiple
* lines, the final line will be aligned to the bottom, with the previous
* lines appearing above it.
* <br/> <br/>
* When using <b>text()</b> with width and height parameters, BASELINE is
* ignored, and treated as TOP. (Otherwise, text would by default draw
* outside the box, since BASELINE is the default setting. BASELINE is not
* a useful drawing mode for text drawn in a rectangle.)
* <br/> <br/>
* The vertical alignment is based on the value of <b>textAscent()</b>,
* which many fonts do not specify correctly. It may be necessary to use a
* hack and offset by a few pixels by hand so that the offset looks
* correct. To do this as less of a hack, use some percentage of
* <b>textAscent()</b> or <b>textDescent()</b> so that the hack works even
* if you change the size of the font.
*
* ( end auto-generated )
*
* @webref typography:attributes
* @param alignX horizontal alignment, either LEFT, CENTER, or RIGHT
* @param alignY vertical alignment, either TOP, BOTTOM, CENTER, or BASELINE
* @see PApplet#loadFont(String)
* @see PFont
* @see PGraphics#text(String, float, float)
*/
public void textAlign(int alignX, int alignY) {
if (recorder != null) recorder.textAlign(alignX, alignY);
g.textAlign(alignX, alignY);
}
/**
* ( begin auto-generated from textAscent.xml )
*
* Returns ascent of the current font at its current size. This information
* is useful for determining the height of the font above the baseline. For
* example, adding the <b>textAscent()</b> and <b>textDescent()</b> values
* will give you the total height of the line.
*
* ( end auto-generated )
*
* @webref typography:metrics
* @see PGraphics#textDescent()
*/
public float textAscent() {
return g.textAscent();
}
/**
* ( begin auto-generated from textDescent.xml )
*
* Returns descent of the current font at its current size. This
* information is useful for determining the height of the font below the
* baseline. For example, adding the <b>textAscent()</b> and
* <b>textDescent()</b> values will give you the total height of the line.
*
* ( end auto-generated )
*
* @webref typography:metrics
* @see PGraphics#textAscent()
*/
public float textDescent() {
return g.textDescent();
}
/**
* ( begin auto-generated from textFont.xml )
*
* Sets the current font that will be drawn with the <b>text()</b>
* function. Fonts must be loaded with <b>loadFont()</b> before it can be
* used. This font will be used in all subsequent calls to the
* <b>text()</b> function. If no <b>size</b> parameter is input, the font
* will appear at its original size (the size it was created at with the
* "Create Font..." tool) until it is changed with <b>textSize()</b>. <br
* /> <br /> Because fonts are usually bitmaped, you should create fonts at
* the sizes that will be used most commonly. Using <b>textFont()</b>
* without the size parameter will result in the cleanest-looking text. <br
* /><br /> With the default (JAVA2D) and PDF renderers, it's also possible
* to enable the use of native fonts via the command
* <b>hint(ENABLE_NATIVE_FONTS)</b>. This will produce vector text in
* JAVA2D sketches and PDF output in cases where the vector data is
* available: when the font is still installed, or the font is created via
* the <b>createFont()</b> function (rather than the Create Font tool).
*
* ( end auto-generated )
*
* @webref typography:loading_displaying
* @param which any variable of the type PFont
* @see PApplet#createFont(String, float, boolean)
* @see PApplet#loadFont(String)
* @see PFont#PFont
* @see PGraphics#text(String, float, float)
*/
public void textFont(PFont which) {
if (recorder != null) recorder.textFont(which);
g.textFont(which);
}
/**
* @param size the size of the letters in units of pixels
*/
public void textFont(PFont which, float size) {
if (recorder != null) recorder.textFont(which, size);
g.textFont(which, size);
}
/**
* ( begin auto-generated from textLeading.xml )
*
* Sets the spacing between lines of text in units of pixels. This setting
* will be used in all subsequent calls to the <b>text()</b> function.
*
* ( end auto-generated )
*
* @webref typography:attributes
* @param leading the size in pixels for spacing between lines
* @see PApplet#loadFont(String)
* @see PFont#PFont
* @see PGraphics#text(String, float, float)
* @see PGraphics#textFont(PFont)
*/
public void textLeading(float leading) {
if (recorder != null) recorder.textLeading(leading);
g.textLeading(leading);
}
/**
* ( begin auto-generated from textMode.xml )
*
* Sets the way text draws to the screen. In the default configuration, the
* <b>MODEL</b> mode, it's possible to rotate, scale, and place letters in
* two and three dimensional space.<br />
* <br />
* The <b>SHAPE</b> mode draws text using the the glyph outlines of
* individual characters rather than as textures. This mode is only
* supported with the <b>PDF</b> and <b>P3D</b> renderer settings. With the
* <b>PDF</b> renderer, you must call <b>textMode(SHAPE)</b> before any
* other drawing occurs. If the outlines are not available, then
* <b>textMode(SHAPE)</b> will be ignored and <b>textMode(MODEL)</b> will
* be used instead.<br />
* <br />
* The <b>textMode(SHAPE)</b> option in <b>P3D</b> can be combined with
* <b>beginRaw()</b> to write vector-accurate text to 2D and 3D output
* files, for instance <b>DXF</b> or <b>PDF</b>. The <b>SHAPE</b> mode is
* not currently optimized for <b>P3D</b>, so if recording shape data, use
* <b>textMode(MODEL)</b> until you're ready to capture the geometry with <b>beginRaw()</b>.
*
* ( end auto-generated )
*
* @webref typography:attributes
* @param mode either MODEL or SHAPE
* @see PApplet#loadFont(String)
* @see PFont#PFont
* @see PGraphics#text(String, float, float)
* @see PGraphics#textFont(PFont)
* @see PGraphics#beginRaw(PGraphics)
* @see PApplet#createFont(String, float, boolean)
*/
public void textMode(int mode) {
if (recorder != null) recorder.textMode(mode);
g.textMode(mode);
}
/**
* ( begin auto-generated from textSize.xml )
*
* Sets the current font size. This size will be used in all subsequent
* calls to the <b>text()</b> function. Font size is measured in units of pixels.
*
* ( end auto-generated )
*
* @webref typography:attributes
* @param size the size of the letters in units of pixels
* @see PApplet#loadFont(String)
* @see PFont#PFont
* @see PGraphics#text(String, float, float)
* @see PGraphics#textFont(PFont)
*/
public void textSize(float size) {
if (recorder != null) recorder.textSize(size);
g.textSize(size);
}
/**
* @param c the character to measure
*/
public float textWidth(char c) {
return g.textWidth(c);
}
/**
* ( begin auto-generated from textWidth.xml )
*
* Calculates and returns the width of any character or text string.
*
* ( end auto-generated )
*
* @webref typography:attributes
* @param str the String of characters to measure
* @see PApplet#loadFont(String)
* @see PFont#PFont
* @see PGraphics#text(String, float, float)
* @see PGraphics#textFont(PFont)
*/
public float textWidth(String str) {
return g.textWidth(str);
}
/**
* @nowebref
*/
public float textWidth(char[] chars, int start, int length) {
return g.textWidth(chars, start, length);
}
/**
* ( begin auto-generated from text.xml )
*
* Draws text to the screen. Displays the information specified in the
* <b>data</b> or <b>stringdata</b> parameters on the screen in the
* position specified by the <b>x</b> and <b>y</b> parameters and the
* optional <b>z</b> parameter. A default font will be used unless a font
* is set with the <b>textFont()</b> function. Change the color of the text
* with the <b>fill()</b> function. The text displays in relation to the
* <b>textAlign()</b> function, which gives the option to draw to the left,
* right, and center of the coordinates.
* <br /><br />
* The <b>x2</b> and <b>y2</b> parameters define a rectangular area to
* display within and may only be used with string data. For text drawn
* inside a rectangle, the coordinates are interpreted based on the current
* <b>rectMode()</b> setting.
*
* ( end auto-generated )
*
* @webref typography:loading_displaying
* @param c the alphanumeric character to be displayed
* @param x x-coordinate of text
* @param y y-coordinate of text
* @see PGraphics#textAlign(int, int)
* @see PGraphics#textMode(int)
* @see PApplet#loadFont(String)
* @see PGraphics#textFont(PFont)
* @see PGraphics#rectMode(int)
* @see PGraphics#fill(int, float)
* @see_external String
*/
public void text(char c, float x, float y) {
if (recorder != null) recorder.text(c, x, y);
g.text(c, x, y);
}
/**
* @param z z-coordinate of text
*/
public void text(char c, float x, float y, float z) {
if (recorder != null) recorder.text(c, x, y, z);
g.text(c, x, y, z);
}
/**
* <h3>Advanced</h3>
* Draw a chunk of text.
* Newlines that are \n (Unix newline or linefeed char, ascii 10)
* are honored, but \r (carriage return, Windows and Mac OS) are
* ignored.
*/
public void text(String str, float x, float y) {
if (recorder != null) recorder.text(str, x, y);
g.text(str, x, y);
}
/**
* <h3>Advanced</h3>
* Method to draw text from an array of chars. This method will usually be
* more efficient than drawing from a String object, because the String will
* not be converted to a char array before drawing.
* @param chars the alphanumberic symbols to be displayed
* @param start array index at which to start writing characters
* @param stop array index at which to stop writing characters
*/
public void text(char[] chars, int start, int stop, float x, float y) {
if (recorder != null) recorder.text(chars, start, stop, x, y);
g.text(chars, start, stop, x, y);
}
/**
* Same as above but with a z coordinate.
*/
public void text(String str, float x, float y, float z) {
if (recorder != null) recorder.text(str, x, y, z);
g.text(str, x, y, z);
}
public void text(char[] chars, int start, int stop,
float x, float y, float z) {
if (recorder != null) recorder.text(chars, start, stop, x, y, z);
g.text(chars, start, stop, x, y, z);
}
/**
* <h3>Advanced</h3>
* Draw text in a box that is constrained to a particular size.
* The current rectMode() determines what the coordinates mean
* (whether x1/y1/x2/y2 or x/y/w/h).
* <P/>
* Note that the x,y coords of the start of the box
* will align with the *ascent* of the text, not the baseline,
* as is the case for the other text() functions.
* <P/>
* Newlines that are \n (Unix newline or linefeed char, ascii 10)
* are honored, and \r (carriage return, Windows and Mac OS) are
* ignored.
*
* @param x1 by default, the x-coordinate of text, see rectMode() for more info
* @param y1 by default, the x-coordinate of text, see rectMode() for more info
* @param x2 by default, the width of the text box, see rectMode() for more info
* @param y2 by default, the height of the text box, see rectMode() for more info
*/
public void text(String str, float x1, float y1, float x2, float y2) {
if (recorder != null) recorder.text(str, x1, y1, x2, y2);
g.text(str, x1, y1, x2, y2);
}
public void text(int num, float x, float y) {
if (recorder != null) recorder.text(num, x, y);
g.text(num, x, y);
}
public void text(int num, float x, float y, float z) {
if (recorder != null) recorder.text(num, x, y, z);
g.text(num, x, y, z);
}
/**
* This does a basic number formatting, to avoid the
* generally ugly appearance of printing floats.
* Users who want more control should use their own nf() cmmand,
* or if they want the long, ugly version of float,
* use String.valueOf() to convert the float to a String first.
*
* @param num the numeric value to be displayed
*/
public void text(float num, float x, float y) {
if (recorder != null) recorder.text(num, x, y);
g.text(num, x, y);
}
public void text(float num, float x, float y, float z) {
if (recorder != null) recorder.text(num, x, y, z);
g.text(num, x, y, z);
}
/**
* ( begin auto-generated from pushMatrix.xml )
*
* Pushes the current transformation matrix onto the matrix stack.
* Understanding <b>pushMatrix()</b> and <b>popMatrix()</b> requires
* understanding the concept of a matrix stack. The <b>pushMatrix()</b>
* function saves the current coordinate system to the stack and
* <b>popMatrix()</b> restores the prior coordinate system.
* <b>pushMatrix()</b> and <b>popMatrix()</b> are used in conjuction with
* the other transformation functions and may be embedded to control the
* scope of the transformations.
*
* ( end auto-generated )
*
* @webref transform
* @see PGraphics#popMatrix()
* @see PGraphics#translate(float, float, float)
* @see PGraphics#rotate(float)
* @see PGraphics#rotateX(float)
* @see PGraphics#rotateY(float)
* @see PGraphics#rotateZ(float)
*/
public void pushMatrix() {
if (recorder != null) recorder.pushMatrix();
g.pushMatrix();
}
/**
* ( begin auto-generated from popMatrix.xml )
*
* Pops the current transformation matrix off the matrix stack.
* Understanding pushing and popping requires understanding the concept of
* a matrix stack. The <b>pushMatrix()</b> function saves the current
* coordinate system to the stack and <b>popMatrix()</b> restores the prior
* coordinate system. <b>pushMatrix()</b> and <b>popMatrix()</b> are used
* in conjuction with the other transformation functions and may be
* embedded to control the scope of the transformations.
*
* ( end auto-generated )
*
* @webref transform
* @see PGraphics#pushMatrix()
*/
public void popMatrix() {
if (recorder != null) recorder.popMatrix();
g.popMatrix();
}
/**
* ( begin auto-generated from translate.xml )
*
* Specifies an amount to displace objects within the display window. The
* <b>x</b> parameter specifies left/right translation, the <b>y</b>
* parameter specifies up/down translation, and the <b>z</b> parameter
* specifies translations toward/away from the screen. Using this function
* with the <b>z</b> parameter requires using P3D as a parameter in
* combination with size as shown in the above example. Transformations
* apply to everything that happens after and subsequent calls to the
* function accumulates the effect. For example, calling <b>translate(50,
* 0)</b> and then <b>translate(20, 0)</b> is the same as <b>translate(70,
* 0)</b>. If <b>translate()</b> is called within <b>draw()</b>, the
* transformation is reset when the loop begins again. This function can be
* further controlled by the <b>pushMatrix()</b> and <b>popMatrix()</b>.
*
* ( end auto-generated )
*
* @webref transform
* @param x left/right translation
* @param y up/down translation
* @see PGraphics#popMatrix()
* @see PGraphics#pushMatrix()
* @see PGraphics#rotate(float)
* @see PGraphics#rotateX(float)
* @see PGraphics#rotateY(float)
* @see PGraphics#rotateZ(float)
* @see PGraphics#scale(float, float, float)
*/
public void translate(float x, float y) {
if (recorder != null) recorder.translate(x, y);
g.translate(x, y);
}
/**
* @param z forward/backward translation
*/
public void translate(float x, float y, float z) {
if (recorder != null) recorder.translate(x, y, z);
g.translate(x, y, z);
}
/**
* ( begin auto-generated from rotate.xml )
*
* Rotates a shape the amount specified by the <b>angle</b> parameter.
* Angles should be specified in radians (values from 0 to TWO_PI) or
* converted to radians with the <b>radians()</b> function.
* <br/> <br/>
* Objects are always rotated around their relative position to the origin
* and positive numbers rotate objects in a clockwise direction.
* Transformations apply to everything that happens after and subsequent
* calls to the function accumulates the effect. For example, calling
* <b>rotate(HALF_PI)</b> and then <b>rotate(HALF_PI)</b> is the same as
* <b>rotate(PI)</b>. All tranformations are reset when <b>draw()</b>
* begins again.
* <br/> <br/>
* Technically, <b>rotate()</b> multiplies the current transformation
* matrix by a rotation matrix. This function can be further controlled by
* the <b>pushMatrix()</b> and <b>popMatrix()</b>.
*
* ( end auto-generated )
*
* @webref transform
* @param angle angle of rotation specified in radians
* @see PGraphics#popMatrix()
* @see PGraphics#pushMatrix()
* @see PGraphics#rotateX(float)
* @see PGraphics#rotateY(float)
* @see PGraphics#rotateZ(float)
* @see PGraphics#scale(float, float, float)
* @see PApplet#radians(float)
*/
public void rotate(float angle) {
if (recorder != null) recorder.rotate(angle);
g.rotate(angle);
}
/**
* ( begin auto-generated from rotateX.xml )
*
* Rotates a shape around the x-axis the amount specified by the
* <b>angle</b> parameter. Angles should be specified in radians (values
* from 0 to PI*2) or converted to radians with the <b>radians()</b>
* function. Objects are always rotated around their relative position to
* the origin and positive numbers rotate objects in a counterclockwise
* direction. Transformations apply to everything that happens after and
* subsequent calls to the function accumulates the effect. For example,
* calling <b>rotateX(PI/2)</b> and then <b>rotateX(PI/2)</b> is the same
* as <b>rotateX(PI)</b>. If <b>rotateX()</b> is called within the
* <b>draw()</b>, the transformation is reset when the loop begins again.
* This function requires using P3D as a third parameter to <b>size()</b>
* as shown in the example above.
*
* ( end auto-generated )
*
* @webref transform
* @param angle angle of rotation specified in radians
* @see PGraphics#popMatrix()
* @see PGraphics#pushMatrix()
* @see PGraphics#rotate(float)
* @see PGraphics#rotateY(float)
* @see PGraphics#rotateZ(float)
* @see PGraphics#scale(float, float, float)
* @see PGraphics#translate(float, float, float)
*/
public void rotateX(float angle) {
if (recorder != null) recorder.rotateX(angle);
g.rotateX(angle);
}
/**
* ( begin auto-generated from rotateY.xml )
*
* Rotates a shape around the y-axis the amount specified by the
* <b>angle</b> parameter. Angles should be specified in radians (values
* from 0 to PI*2) or converted to radians with the <b>radians()</b>
* function. Objects are always rotated around their relative position to
* the origin and positive numbers rotate objects in a counterclockwise
* direction. Transformations apply to everything that happens after and
* subsequent calls to the function accumulates the effect. For example,
* calling <b>rotateY(PI/2)</b> and then <b>rotateY(PI/2)</b> is the same
* as <b>rotateY(PI)</b>. If <b>rotateY()</b> is called within the
* <b>draw()</b>, the transformation is reset when the loop begins again.
* This function requires using P3D as a third parameter to <b>size()</b>
* as shown in the examples above.
*
* ( end auto-generated )
*
* @webref transform
* @param angle angle of rotation specified in radians
* @see PGraphics#popMatrix()
* @see PGraphics#pushMatrix()
* @see PGraphics#rotate(float)
* @see PGraphics#rotateX(float)
* @see PGraphics#rotateZ(float)
* @see PGraphics#scale(float, float, float)
* @see PGraphics#translate(float, float, float)
*/
public void rotateY(float angle) {
if (recorder != null) recorder.rotateY(angle);
g.rotateY(angle);
}
/**
* ( begin auto-generated from rotateZ.xml )
*
* Rotates a shape around the z-axis the amount specified by the
* <b>angle</b> parameter. Angles should be specified in radians (values
* from 0 to PI*2) or converted to radians with the <b>radians()</b>
* function. Objects are always rotated around their relative position to
* the origin and positive numbers rotate objects in a counterclockwise
* direction. Transformations apply to everything that happens after and
* subsequent calls to the function accumulates the effect. For example,
* calling <b>rotateZ(PI/2)</b> and then <b>rotateZ(PI/2)</b> is the same
* as <b>rotateZ(PI)</b>. If <b>rotateZ()</b> is called within the
* <b>draw()</b>, the transformation is reset when the loop begins again.
* This function requires using P3D as a third parameter to <b>size()</b>
* as shown in the examples above.
*
* ( end auto-generated )
*
* @webref transform
* @param angle angle of rotation specified in radians
* @see PGraphics#popMatrix()
* @see PGraphics#pushMatrix()
* @see PGraphics#rotate(float)
* @see PGraphics#rotateX(float)
* @see PGraphics#rotateY(float)
* @see PGraphics#scale(float, float, float)
* @see PGraphics#translate(float, float, float)
*/
public void rotateZ(float angle) {
if (recorder != null) recorder.rotateZ(angle);
g.rotateZ(angle);
}
/**
* <h3>Advanced</h3>
* Rotate about a vector in space. Same as the glRotatef() function.
* @param x
* @param y
* @param z
*/
public void rotate(float angle, float x, float y, float z) {
if (recorder != null) recorder.rotate(angle, x, y, z);
g.rotate(angle, x, y, z);
}
/**
* ( begin auto-generated from scale.xml )
*
* Increases or decreases the size of a shape by expanding and contracting
* vertices. Objects always scale from their relative origin to the
* coordinate system. Scale values are specified as decimal percentages.
* For example, the function call <b>scale(2.0)</b> increases the dimension
* of a shape by 200%. Transformations apply to everything that happens
* after and subsequent calls to the function multiply the effect. For
* example, calling <b>scale(2.0)</b> and then <b>scale(1.5)</b> is the
* same as <b>scale(3.0)</b>. If <b>scale()</b> is called within
* <b>draw()</b>, the transformation is reset when the loop begins again.
* Using this fuction with the <b>z</b> parameter requires using P3D as a
* parameter for <b>size()</b> as shown in the example above. This function
* can be further controlled by <b>pushMatrix()</b> and <b>popMatrix()</b>.
*
* ( end auto-generated )
*
* @webref transform
* @param s percentage to scale the object
* @see PGraphics#pushMatrix()
* @see PGraphics#popMatrix()
* @see PGraphics#translate(float, float, float)
* @see PGraphics#rotate(float)
* @see PGraphics#rotateX(float)
* @see PGraphics#rotateY(float)
* @see PGraphics#rotateZ(float)
*/
public void scale(float s) {
if (recorder != null) recorder.scale(s);
g.scale(s);
}
/**
* <h3>Advanced</h3>
* Scale in X and Y. Equivalent to scale(sx, sy, 1).
*
* Not recommended for use in 3D, because the z-dimension is just
* scaled by 1, since there's no way to know what else to scale it by.
*
* @param x percentage to scale the object in the x-axis
* @param y percentage to scale the object in the y-axis
*/
public void scale(float x, float y) {
if (recorder != null) recorder.scale(x, y);
g.scale(x, y);
}
/**
* @param z percentage to scale the object in the z-axis
*/
public void scale(float x, float y, float z) {
if (recorder != null) recorder.scale(x, y, z);
g.scale(x, y, z);
}
/**
* ( begin auto-generated from shearX.xml )
*
* Shears a shape around the x-axis the amount specified by the
* <b>angle</b> parameter. Angles should be specified in radians (values
* from 0 to PI*2) or converted to radians with the <b>radians()</b>
* function. Objects are always sheared around their relative position to
* the origin and positive numbers shear objects in a clockwise direction.
* Transformations apply to everything that happens after and subsequent
* calls to the function accumulates the effect. For example, calling
* <b>shearX(PI/2)</b> and then <b>shearX(PI/2)</b> is the same as
* <b>shearX(PI)</b>. If <b>shearX()</b> is called within the
* <b>draw()</b>, the transformation is reset when the loop begins again.
* <br/> <br/>
* Technically, <b>shearX()</b> multiplies the current transformation
* matrix by a rotation matrix. This function can be further controlled by
* the <b>pushMatrix()</b> and <b>popMatrix()</b> functions.
*
* ( end auto-generated )
*
* @webref transform
* @param angle angle of shear specified in radians
* @see PGraphics#popMatrix()
* @see PGraphics#pushMatrix()
* @see PGraphics#shearY(float)
* @see PGraphics#scale(float, float, float)
* @see PGraphics#translate(float, float, float)
* @see PApplet#radians(float)
*/
public void shearX(float angle) {
if (recorder != null) recorder.shearX(angle);
g.shearX(angle);
}
/**
* ( begin auto-generated from shearY.xml )
*
* Shears a shape around the y-axis the amount specified by the
* <b>angle</b> parameter. Angles should be specified in radians (values
* from 0 to PI*2) or converted to radians with the <b>radians()</b>
* function. Objects are always sheared around their relative position to
* the origin and positive numbers shear objects in a clockwise direction.
* Transformations apply to everything that happens after and subsequent
* calls to the function accumulates the effect. For example, calling
* <b>shearY(PI/2)</b> and then <b>shearY(PI/2)</b> is the same as
* <b>shearY(PI)</b>. If <b>shearY()</b> is called within the
* <b>draw()</b>, the transformation is reset when the loop begins again.
* <br/> <br/>
* Technically, <b>shearY()</b> multiplies the current transformation
* matrix by a rotation matrix. This function can be further controlled by
* the <b>pushMatrix()</b> and <b>popMatrix()</b> functions.
*
* ( end auto-generated )
*
* @webref transform
* @param angle angle of shear specified in radians
* @see PGraphics#popMatrix()
* @see PGraphics#pushMatrix()
* @see PGraphics#shearX(float)
* @see PGraphics#scale(float, float, float)
* @see PGraphics#translate(float, float, float)
* @see PApplet#radians(float)
*/
public void shearY(float angle) {
if (recorder != null) recorder.shearY(angle);
g.shearY(angle);
}
/**
* ( begin auto-generated from resetMatrix.xml )
*
* Replaces the current matrix with the identity matrix. The equivalent
* function in OpenGL is glLoadIdentity().
*
* ( end auto-generated )
*
* @webref transform
* @see PGraphics#pushMatrix()
* @see PGraphics#popMatrix()
* @see PGraphics#applyMatrix(PMatrix)
* @see PGraphics#printMatrix()
*/
public void resetMatrix() {
if (recorder != null) recorder.resetMatrix();
g.resetMatrix();
}
/**
* ( begin auto-generated from applyMatrix.xml )
*
* Multiplies the current matrix by the one specified through the
* parameters. This is very slow because it will try to calculate the
* inverse of the transform, so avoid it whenever possible. The equivalent
* function in OpenGL is glMultMatrix().
*
* ( end auto-generated )
*
* @webref transform
* @source
* @see PGraphics#pushMatrix()
* @see PGraphics#popMatrix()
* @see PGraphics#resetMatrix()
* @see PGraphics#printMatrix()
*/
public void applyMatrix(PMatrix source) {
if (recorder != null) recorder.applyMatrix(source);
g.applyMatrix(source);
}
public void applyMatrix(PMatrix2D source) {
if (recorder != null) recorder.applyMatrix(source);
g.applyMatrix(source);
}
/**
* @param n00 numbers which define the 4x4 matrix to be multiplied
* @param n01 numbers which define the 4x4 matrix to be multiplied
* @param n02 numbers which define the 4x4 matrix to be multiplied
* @param n10 numbers which define the 4x4 matrix to be multiplied
* @param n11 numbers which define the 4x4 matrix to be multiplied
* @param n12 numbers which define the 4x4 matrix to be multiplied
*/
public void applyMatrix(float n00, float n01, float n02,
float n10, float n11, float n12) {
if (recorder != null) recorder.applyMatrix(n00, n01, n02, n10, n11, n12);
g.applyMatrix(n00, n01, n02, n10, n11, n12);
}
public void applyMatrix(PMatrix3D source) {
if (recorder != null) recorder.applyMatrix(source);
g.applyMatrix(source);
}
/**
* @param n03 numbers which define the 4x4 matrix to be multiplied
* @param n13 numbers which define the 4x4 matrix to be multiplied
* @param n20 numbers which define the 4x4 matrix to be multiplied
* @param n21 numbers which define the 4x4 matrix to be multiplied
* @param n22 numbers which define the 4x4 matrix to be multiplied
* @param n23 numbers which define the 4x4 matrix to be multiplied
* @param n30 numbers which define the 4x4 matrix to be multiplied
* @param n31 numbers which define the 4x4 matrix to be multiplied
* @param n32 numbers which define the 4x4 matrix to be multiplied
* @param n33 numbers which define the 4x4 matrix to be multiplied
*/
public void applyMatrix(float n00, float n01, float n02, float n03,
float n10, float n11, float n12, float n13,
float n20, float n21, float n22, float n23,
float n30, float n31, float n32, float n33) {
if (recorder != null) recorder.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33);
g.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33);
}
public PMatrix getMatrix() {
return g.getMatrix();
}
/**
* Copy the current transformation matrix into the specified target.
* Pass in null to create a new matrix.
*/
public PMatrix2D getMatrix(PMatrix2D target) {
return g.getMatrix(target);
}
/**
* Copy the current transformation matrix into the specified target.
* Pass in null to create a new matrix.
*/
public PMatrix3D getMatrix(PMatrix3D target) {
return g.getMatrix(target);
}
/**
* Set the current transformation matrix to the contents of another.
*/
public void setMatrix(PMatrix source) {
if (recorder != null) recorder.setMatrix(source);
g.setMatrix(source);
}
/**
* Set the current transformation to the contents of the specified source.
*/
public void setMatrix(PMatrix2D source) {
if (recorder != null) recorder.setMatrix(source);
g.setMatrix(source);
}
/**
* Set the current transformation to the contents of the specified source.
*/
public void setMatrix(PMatrix3D source) {
if (recorder != null) recorder.setMatrix(source);
g.setMatrix(source);
}
/**
* ( begin auto-generated from printMatrix.xml )
*
* Prints the current matrix to the Console (the text window at the bottom
* of Processing).
*
* ( end auto-generated )
*
* @webref transform
* @see PGraphics#pushMatrix()
* @see PGraphics#popMatrix()
* @see PGraphics#resetMatrix()
* @see PGraphics#applyMatrix(PMatrix)
*/
public void printMatrix() {
if (recorder != null) recorder.printMatrix();
g.printMatrix();
}
/**
* ( begin auto-generated from beginCamera.xml )
*
* The <b>beginCamera()</b> and <b>endCamera()</b> functions enable
* advanced customization of the camera space. The functions are useful if
* you want to more control over camera movement, however for most users,
* the <b>camera()</b> function will be sufficient.<br /><br />The camera
* functions will replace any transformations (such as <b>rotate()</b> or
* <b>translate()</b>) that occur before them in <b>draw()</b>, but they
* will not automatically replace the camera transform itself. For this
* reason, camera functions should be placed at the beginning of
* <b>draw()</b> (so that transformations happen afterwards), and the
* <b>camera()</b> function can be used after <b>beginCamera()</b> if you
* want to reset the camera before applying transformations.<br /><br
* />This function sets the matrix mode to the camera matrix so calls such
* as <b>translate()</b>, <b>rotate()</b>, applyMatrix() and resetMatrix()
* affect the camera. <b>beginCamera()</b> should always be used with a
* following <b>endCamera()</b> and pairs of <b>beginCamera()</b> and
* <b>endCamera()</b> cannot be nested.
*
* ( end auto-generated )
*
* @webref lights_camera:camera
* @see PGraphics#camera()
* @see PGraphics#endCamera()
* @see PGraphics#applyMatrix(PMatrix)
* @see PGraphics#resetMatrix()
* @see PGraphics#translate(float, float, float)
* @see PGraphics#scale(float, float, float)
*/
public void beginCamera() {
if (recorder != null) recorder.beginCamera();
g.beginCamera();
}
/**
* ( begin auto-generated from endCamera.xml )
*
* The <b>beginCamera()</b> and <b>endCamera()</b> functions enable
* advanced customization of the camera space. Please see the reference for
* <b>beginCamera()</b> for a description of how the functions are used.
*
* ( end auto-generated )
*
* @webref lights_camera:camera
* @see PGraphics#camera(float, float, float, float, float, float, float, float, float)
*/
public void endCamera() {
if (recorder != null) recorder.endCamera();
g.endCamera();
}
/**
* ( begin auto-generated from camera.xml )
*
* Sets the position of the camera through setting the eye position, the
* center of the scene, and which axis is facing upward. Moving the eye
* position and the direction it is pointing (the center of the scene)
* allows the images to be seen from different angles. The version without
* any parameters sets the camera to the default position, pointing to the
* center of the display window with the Y axis as up. The default values
* are <b>camera(width/2.0, height/2.0, (height/2.0) / tan(PI*30.0 /
* 180.0), width/2.0, height/2.0, 0, 0, 1, 0)</b>. This function is similar
* to <b>gluLookAt()</b> in OpenGL, but it first clears the current camera settings.
*
* ( end auto-generated )
*
* @webref lights_camera:camera
* @see PGraphics#endCamera()
* @see PGraphics#frustum(float, float, float, float, float, float)
*/
public void camera() {
if (recorder != null) recorder.camera();
g.camera();
}
/**
* @param eyeX x-coordinate for the eye
* @param eyeY y-coordinate for the eye
* @param eyeZ z-coordinate for the eye
* @param centerX x-coordinate for the center of the scene
* @param centerY y-coordinate for the center of the scene
* @param centerZ z-coordinate for the center of the scene
* @param upX usually 0.0, 1.0, or -1.0
* @param upY usually 0.0, 1.0, or -1.0
* @param upZ usually 0.0, 1.0, or -1.0
*/
public void camera(float eyeX, float eyeY, float eyeZ,
float centerX, float centerY, float centerZ,
float upX, float upY, float upZ) {
if (recorder != null) recorder.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ);
g.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ);
}
/**
* ( begin auto-generated from printCamera.xml )
*
* Prints the current camera matrix to the Console (the text window at the
* bottom of Processing).
*
* ( end auto-generated )
* @webref lights_camera:camera
* @see PGraphics#camera(float, float, float, float, float, float, float, float, float)
*/
public void printCamera() {
if (recorder != null) recorder.printCamera();
g.printCamera();
}
/**
* ( begin auto-generated from ortho.xml )
*
* Sets an orthographic projection and defines a parallel clipping volume.
* All objects with the same dimension appear the same size, regardless of
* whether they are near or far from the camera. The parameters to this
* function specify the clipping volume where left and right are the
* minimum and maximum x values, top and bottom are the minimum and maximum
* y values, and near and far are the minimum and maximum z values. If no
* parameters are given, the default is used: ortho(0, width, 0, height,
* -10, 10).
*
* ( end auto-generated )
*
* @webref lights_camera:camera
*/
public void ortho() {
if (recorder != null) recorder.ortho();
g.ortho();
}
/**
* @param left left plane of the clipping volume
* @param right right plane of the clipping volume
* @param bottom bottom plane of the clipping volume
* @param top top plane of the clipping volume
*/
public void ortho(float left, float right,
float bottom, float top) {
if (recorder != null) recorder.ortho(left, right, bottom, top);
g.ortho(left, right, bottom, top);
}
/**
* @param near maximum distance from the origin to the viewer
* @param far maximum distance from the origin away from the viewer
*/
public void ortho(float left, float right,
float bottom, float top,
float near, float far) {
if (recorder != null) recorder.ortho(left, right, bottom, top, near, far);
g.ortho(left, right, bottom, top, near, far);
}
/**
* ( begin auto-generated from perspective.xml )
*
* Sets a perspective projection applying foreshortening, making distant
* objects appear smaller than closer ones. The parameters define a viewing
* volume with the shape of truncated pyramid. Objects near to the front of
* the volume appear their actual size, while farther objects appear
* smaller. This projection simulates the perspective of the world more
* accurately than orthographic projection. The version of perspective
* without parameters sets the default perspective and the version with
* four parameters allows the programmer to set the area precisely. The
* default values are: perspective(PI/3.0, width/height, cameraZ/10.0,
* cameraZ*10.0) where cameraZ is ((height/2.0) / tan(PI*60.0/360.0));
*
* ( end auto-generated )
*
* @webref lights_camera:camera
*/
public void perspective() {
if (recorder != null) recorder.perspective();
g.perspective();
}
/**
* @param fovy field-of-view angle (in radians) for vertical direction
* @param aspect ratio of width to height
* @param zNear z-position of nearest clipping plane
* @param zFar z-position of farthest clipping plane
*/
public void perspective(float fovy, float aspect, float zNear, float zFar) {
if (recorder != null) recorder.perspective(fovy, aspect, zNear, zFar);
g.perspective(fovy, aspect, zNear, zFar);
}
/**
* ( begin auto-generated from frustum.xml )
*
* Sets a perspective matrix defined through the parameters. Works like
* glFrustum, except it wipes out the current perspective matrix rather
* than muliplying itself with it.
*
* ( end auto-generated )
*
* @webref lights_camera:camera
* @param left left coordinate of the clipping plane
* @param right right coordinate of the clipping plane
* @param bottom bottom coordinate of the clipping plane
* @param top top coordinate of the clipping plane
* @param near near component of the clipping plane; must be greater than zero
* @param far far component of the clipping plane; must be greater than the near value
* @see PGraphics#camera(float, float, float, float, float, float, float, float, float)
* @see PGraphics#endCamera()
* @see PGraphics#perspective(float, float, float, float)
*/
public void frustum(float left, float right,
float bottom, float top,
float near, float far) {
if (recorder != null) recorder.frustum(left, right, bottom, top, near, far);
g.frustum(left, right, bottom, top, near, far);
}
/**
* ( begin auto-generated from printProjection.xml )
*
* Prints the current projection matrix to the Console (the text window at
* the bottom of Processing).
*
* ( end auto-generated )
*
* @webref lights_camera:camera
* @see PGraphics#camera(float, float, float, float, float, float, float, float, float)
*/
public void printProjection() {
if (recorder != null) recorder.printProjection();
g.printProjection();
}
/**
* ( begin auto-generated from screenX.xml )
*
* Takes a three-dimensional X, Y, Z position and returns the X value for
* where it will appear on a (two-dimensional) screen.
*
* ( end auto-generated )
*
* @webref lights_camera:coordinates
* @param x 3D x-coordinate to be mapped
* @param y 3D y-coordinate to be mapped
* @see PGraphics#screenY(float, float, float)
* @see PGraphics#screenZ(float, float, float)
*/
public float screenX(float x, float y) {
return g.screenX(x, y);
}
/**
* ( begin auto-generated from screenY.xml )
*
* Takes a three-dimensional X, Y, Z position and returns the Y value for
* where it will appear on a (two-dimensional) screen.
*
* ( end auto-generated )
*
* @webref lights_camera:coordinates
* @param x 3D x-coordinate to be mapped
* @param y 3D y-coordinate to be mapped
* @see PGraphics#screenX(float, float, float)
* @see PGraphics#screenZ(float, float, float)
*/
public float screenY(float x, float y) {
return g.screenY(x, y);
}
/**
* @param z 3D z-coordinate to be mapped
*/
public float screenX(float x, float y, float z) {
return g.screenX(x, y, z);
}
/**
* @param z 3D z-coordinate to be mapped
*/
public float screenY(float x, float y, float z) {
return g.screenY(x, y, z);
}
/**
* ( begin auto-generated from screenZ.xml )
*
* Takes a three-dimensional X, Y, Z position and returns the Z value for
* where it will appear on a (two-dimensional) screen.
*
* ( end auto-generated )
*
* @webref lights_camera:coordinates
* @param x 3D x-coordinate to be mapped
* @param y 3D y-coordinate to be mapped
* @param z 3D z-coordinate to be mapped
* @see PGraphics#screenX(float, float, float)
* @see PGraphics#screenY(float, float, float)
*/
public float screenZ(float x, float y, float z) {
return g.screenZ(x, y, z);
}
/**
* ( begin auto-generated from modelX.xml )
*
* Returns the three-dimensional X, Y, Z position in model space. This
* returns the X value for a given coordinate based on the current set of
* transformations (scale, rotate, translate, etc.) The X value can be used
* to place an object in space relative to the location of the original
* point once the transformations are no longer in use.
* <br/> <br/>
* In the example, the <b>modelX()</b>, <b>modelY()</b>, and
* <b>modelZ()</b> functions record the location of a box in space after
* being placed using a series of translate and rotate commands. After
* popMatrix() is called, those transformations no longer apply, but the
* (x, y, z) coordinate returned by the model functions is used to place
* another box in the same location.
*
* ( end auto-generated )
*
* @webref lights_camera:coordinates
* @param x 3D x-coordinate to be mapped
* @param y 3D y-coordinate to be mapped
* @param z 3D z-coordinate to be mapped
* @see PGraphics#modelY(float, float, float)
* @see PGraphics#modelZ(float, float, float)
*/
public float modelX(float x, float y, float z) {
return g.modelX(x, y, z);
}
/**
* ( begin auto-generated from modelY.xml )
*
* Returns the three-dimensional X, Y, Z position in model space. This
* returns the Y value for a given coordinate based on the current set of
* transformations (scale, rotate, translate, etc.) The Y value can be used
* to place an object in space relative to the location of the original
* point once the transformations are no longer in use.<br />
* <br />
* In the example, the <b>modelX()</b>, <b>modelY()</b>, and
* <b>modelZ()</b> functions record the location of a box in space after
* being placed using a series of translate and rotate commands. After
* popMatrix() is called, those transformations no longer apply, but the
* (x, y, z) coordinate returned by the model functions is used to place
* another box in the same location.
*
* ( end auto-generated )
*
* @webref lights_camera:coordinates
* @param x 3D x-coordinate to be mapped
* @param y 3D y-coordinate to be mapped
* @param z 3D z-coordinate to be mapped
* @see PGraphics#modelX(float, float, float)
* @see PGraphics#modelZ(float, float, float)
*/
public float modelY(float x, float y, float z) {
return g.modelY(x, y, z);
}
/**
* ( begin auto-generated from modelZ.xml )
*
* Returns the three-dimensional X, Y, Z position in model space. This
* returns the Z value for a given coordinate based on the current set of
* transformations (scale, rotate, translate, etc.) The Z value can be used
* to place an object in space relative to the location of the original
* point once the transformations are no longer in use.<br />
* <br />
* In the example, the <b>modelX()</b>, <b>modelY()</b>, and
* <b>modelZ()</b> functions record the location of a box in space after
* being placed using a series of translate and rotate commands. After
* popMatrix() is called, those transformations no longer apply, but the
* (x, y, z) coordinate returned by the model functions is used to place
* another box in the same location.
*
* ( end auto-generated )
*
* @webref lights_camera:coordinates
* @param x 3D x-coordinate to be mapped
* @param y 3D y-coordinate to be mapped
* @param z 3D z-coordinate to be mapped
* @see PGraphics#modelX(float, float, float)
* @see PGraphics#modelY(float, float, float)
*/
public float modelZ(float x, float y, float z) {
return g.modelZ(x, y, z);
}
/**
* ( begin auto-generated from pushStyle.xml )
*
* The <b>pushStyle()</b> function saves the current style settings and
* <b>popStyle()</b> restores the prior settings. Note that these functions
* are always used together. They allow you to change the style settings
* and later return to what you had. When a new style is started with
* <b>pushStyle()</b>, it builds on the current style information. The
* <b>pushStyle()</b> and <b>popStyle()</b> functions can be embedded to
* provide more control (see the second example above for a demonstration.)
* <br /><br />
* The style information controlled by the following functions are included
* in the style:
* fill(), stroke(), tint(), strokeWeight(), strokeCap(), strokeJoin(),
* imageMode(), rectMode(), ellipseMode(), shapeMode(), colorMode(),
* textAlign(), textFont(), textMode(), textSize(), textLeading(),
* emissive(), specular(), shininess(), ambient()
*
* ( end auto-generated )
*
* @webref structure
* @see PGraphics#popStyle()
*/
public void pushStyle() {
if (recorder != null) recorder.pushStyle();
g.pushStyle();
}
/**
* ( begin auto-generated from popStyle.xml )
*
* The <b>pushStyle()</b> function saves the current style settings and
* <b>popStyle()</b> restores the prior settings; these functions are
* always used together. They allow you to change the style settings and
* later return to what you had. When a new style is started with
* <b>pushStyle()</b>, it builds on the current style information. The
* <b>pushStyle()</b> and <b>popStyle()</b> functions can be embedded to
* provide more control (see the second example above for a demonstration.)
*
* ( end auto-generated )
*
* @webref structure
* @see PGraphics#pushStyle()
*/
public void popStyle() {
if (recorder != null) recorder.popStyle();
g.popStyle();
}
public void style(PStyle s) {
if (recorder != null) recorder.style(s);
g.style(s);
}
/**
* ( begin auto-generated from strokeWeight.xml )
*
* Sets the width of the stroke used for lines, points, and the border
* around shapes. All widths are set in units of pixels.
* <br/> <br/>
* When drawing with P3D, series of connected lines (such as the stroke
* around a polygon, triangle, or ellipse) produce unattractive results
* when a thick stroke weight is set (<a
* href="http://code.google.com/p/processing/issues/detail?id=123">see
* Issue 123</a>). With P3D, the minimum and maximum values for
* <b>strokeWeight()</b> are controlled by the graphics card and the
* operating system's OpenGL implementation. For instance, the thickness
* may not go higher than 10 pixels.
*
* ( end auto-generated )
*
* @webref shape:attributes
* @param weight the weight (in pixels) of the stroke
* @see PGraphics#stroke(int, float)
* @see PGraphics#strokeJoin(int)
* @see PGraphics#strokeCap(int)
*/
public void strokeWeight(float weight) {
if (recorder != null) recorder.strokeWeight(weight);
g.strokeWeight(weight);
}
/**
* ( begin auto-generated from strokeJoin.xml )
*
* Sets the style of the joints which connect line segments. These joints
* are either mitered, beveled, or rounded and specified with the
* corresponding parameters MITER, BEVEL, and ROUND. The default joint is
* MITER.
* <br/> <br/>
* This function is not available with the P3D renderer, (<a
* href="http://code.google.com/p/processing/issues/detail?id=123">see
* Issue 123</a>). More information about the renderers can be found in the
* <b>size()</b> reference.
*
* ( end auto-generated )
*
* @webref shape:attributes
* @param join either MITER, BEVEL, ROUND
* @see PGraphics#stroke(int, float)
* @see PGraphics#strokeWeight(float)
* @see PGraphics#strokeCap(int)
*/
public void strokeJoin(int join) {
if (recorder != null) recorder.strokeJoin(join);
g.strokeJoin(join);
}
/**
* ( begin auto-generated from strokeCap.xml )
*
* Sets the style for rendering line endings. These ends are either
* squared, extended, or rounded and specified with the corresponding
* parameters SQUARE, PROJECT, and ROUND. The default cap is ROUND.
* <br/> <br/>
* This function is not available with the P3D renderer (<a
* href="http://code.google.com/p/processing/issues/detail?id=123">see
* Issue 123</a>). More information about the renderers can be found in the
* <b>size()</b> reference.
*
* ( end auto-generated )
*
* @webref shape:attributes
* @param cap either SQUARE, PROJECT, or ROUND
* @see PGraphics#stroke(int, float)
* @see PGraphics#strokeWeight(float)
* @see PGraphics#strokeJoin(int)
* @see PApplet#size(int, int, String, String)
*/
public void strokeCap(int cap) {
if (recorder != null) recorder.strokeCap(cap);
g.strokeCap(cap);
}
/**
* ( begin auto-generated from noStroke.xml )
*
* Disables drawing the stroke (outline). If both <b>noStroke()</b> and
* <b>noFill()</b> are called, nothing will be drawn to the screen.
*
* ( end auto-generated )
*
* @webref color:setting
* @see PGraphics#stroke(float, float, float, float)
*/
public void noStroke() {
if (recorder != null) recorder.noStroke();
g.noStroke();
}
/**
* ( begin auto-generated from stroke.xml )
*
* Sets the color used to draw lines and borders around shapes. This color
* is either specified in terms of the RGB or HSB color depending on the
* current <b>colorMode()</b> (the default color space is RGB, with each
* value in the range from 0 to 255).
* <br/> <br/>
* When using hexadecimal notation to specify a color, use "#" or "0x"
* before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six
* digits to specify a color (the way colors are specified in HTML and
* CSS). When using the hexadecimal notation starting with "0x", the
* hexadecimal value must be specified with eight characters; the first two
* characters define the alpha component and the remainder the red, green,
* and blue components.
* <br/> <br/>
* The value for the parameter "gray" must be less than or equal to the
* current maximum value as specified by <b>colorMode()</b>. The default
* maximum value is 255.
*
* ( end auto-generated )
*
* @param rgb color value in hexadecimal notation
* @see PGraphics#noStroke()
* @see PGraphics#fill(int, float)
* @see PGraphics#tint(int, float)
* @see PGraphics#background(float, float, float, float)
* @see PGraphics#colorMode(int, float, float, float, float)
*/
public void stroke(int rgb) {
if (recorder != null) recorder.stroke(rgb);
g.stroke(rgb);
}
/**
* @param alpha opacity of the stroke
*/
public void stroke(int rgb, float alpha) {
if (recorder != null) recorder.stroke(rgb, alpha);
g.stroke(rgb, alpha);
}
/**
* @param gray specifies a value between white and black
*/
public void stroke(float gray) {
if (recorder != null) recorder.stroke(gray);
g.stroke(gray);
}
public void stroke(float gray, float alpha) {
if (recorder != null) recorder.stroke(gray, alpha);
g.stroke(gray, alpha);
}
/**
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
* @webref color:setting
*/
public void stroke(float v1, float v2, float v3) {
if (recorder != null) recorder.stroke(v1, v2, v3);
g.stroke(v1, v2, v3);
}
public void stroke(float v1, float v2, float v3, float alpha) {
if (recorder != null) recorder.stroke(v1, v2, v3, alpha);
g.stroke(v1, v2, v3, alpha);
}
/**
* ( begin auto-generated from noTint.xml )
*
* Removes the current fill value for displaying images and reverts to
* displaying images with their original hues.
*
* ( end auto-generated )
*
* @webref image:loading_displaying
* @usage web_application
* @see PGraphics#tint(float, float, float, float)
* @see PGraphics#image(PImage, float, float, float, float)
*/
public void noTint() {
if (recorder != null) recorder.noTint();
g.noTint();
}
/**
* ( begin auto-generated from tint.xml )
*
* Sets the fill value for displaying images. Images can be tinted to
* specified colors or made transparent by setting the alpha.<br />
* <br />
* To make an image transparent, but not change it's color, use white as
* the tint color and specify an alpha value. For instance, tint(255, 128)
* will make an image 50% transparent (unless <b>colorMode()</b> has been
* used).<br />
* <br />
* When using hexadecimal notation to specify a color, use "#" or "0x"
* before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six
* digits to specify a color (the way colors are specified in HTML and
* CSS). When using the hexadecimal notation starting with "0x", the
* hexadecimal value must be specified with eight characters; the first two
* characters define the alpha component and the remainder the red, green,
* and blue components.<br />
* <br />
* The value for the parameter "gray" must be less than or equal to the
* current maximum value as specified by <b>colorMode()</b>. The default
* maximum value is 255.<br />
* <br />
* The <b>tint()</b> function is also used to control the coloring of
* textures in 3D.
*
* ( end auto-generated )
*
* @webref image:loading_displaying
* @usage web_application
* @param rgb color value in hexadecimal notation
* @see PGraphics#noTint()
* @see PGraphics#image(PImage, float, float, float, float)
*/
public void tint(int rgb) {
if (recorder != null) recorder.tint(rgb);
g.tint(rgb);
}
/**
* @param alpha opacity of the image
*/
public void tint(int rgb, float alpha) {
if (recorder != null) recorder.tint(rgb, alpha);
g.tint(rgb, alpha);
}
/**
* @param gray specifies a value between white and black
*/
public void tint(float gray) {
if (recorder != null) recorder.tint(gray);
g.tint(gray);
}
public void tint(float gray, float alpha) {
if (recorder != null) recorder.tint(gray, alpha);
g.tint(gray, alpha);
}
/**
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
*/
public void tint(float v1, float v2, float v3) {
if (recorder != null) recorder.tint(v1, v2, v3);
g.tint(v1, v2, v3);
}
public void tint(float v1, float v2, float v3, float alpha) {
if (recorder != null) recorder.tint(v1, v2, v3, alpha);
g.tint(v1, v2, v3, alpha);
}
/**
* ( begin auto-generated from noFill.xml )
*
* Disables filling geometry. If both <b>noStroke()</b> and <b>noFill()</b>
* are called, nothing will be drawn to the screen.
*
* ( end auto-generated )
*
* @webref color:setting
* @usage web_application
* @see PGraphics#fill(float, float, float, float)
*/
public void noFill() {
if (recorder != null) recorder.noFill();
g.noFill();
}
/**
* ( begin auto-generated from fill.xml )
*
* Sets the color used to fill shapes. For example, if you run <b>fill(204,
* 102, 0)</b>, all subsequent shapes will be filled with orange. This
* color is either specified in terms of the RGB or HSB color depending on
* the current <b>colorMode()</b> (the default color space is RGB, with
* each value in the range from 0 to 255).
* <br/> <br/>
* When using hexadecimal notation to specify a color, use "#" or "0x"
* before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six
* digits to specify a color (the way colors are specified in HTML and
* CSS). When using the hexadecimal notation starting with "0x", the
* hexadecimal value must be specified with eight characters; the first two
* characters define the alpha component and the remainder the red, green,
* and blue components.
* <br/> <br/>
* The value for the parameter "gray" must be less than or equal to the
* current maximum value as specified by <b>colorMode()</b>. The default
* maximum value is 255.
* <br/> <br/>
* To change the color of an image (or a texture), use tint().
*
* ( end auto-generated )
*
* @webref color:setting
* @usage web_application
* @param rgb color variable or hex value
* @see PGraphics#noFill()
* @see PGraphics#stroke(int, float)
* @see PGraphics#tint(int, float)
* @see PGraphics#background(float, float, float, float)
* @see PGraphics#colorMode(int, float, float, float, float)
*/
public void fill(int rgb) {
if (recorder != null) recorder.fill(rgb);
g.fill(rgb);
}
/**
* @param alpha opacity of the fill
*/
public void fill(int rgb, float alpha) {
if (recorder != null) recorder.fill(rgb, alpha);
g.fill(rgb, alpha);
}
/**
* @param gray number specifying value between white and black
*/
public void fill(float gray) {
if (recorder != null) recorder.fill(gray);
g.fill(gray);
}
public void fill(float gray, float alpha) {
if (recorder != null) recorder.fill(gray, alpha);
g.fill(gray, alpha);
}
/**
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
*/
public void fill(float v1, float v2, float v3) {
if (recorder != null) recorder.fill(v1, v2, v3);
g.fill(v1, v2, v3);
}
public void fill(float v1, float v2, float v3, float alpha) {
if (recorder != null) recorder.fill(v1, v2, v3, alpha);
g.fill(v1, v2, v3, alpha);
}
/**
* ( begin auto-generated from ambient.xml )
*
* Sets the ambient reflectance for shapes drawn to the screen. This is
* combined with the ambient light component of environment. The color
* components set through the parameters define the reflectance. For
* example in the default color mode, setting v1=255, v2=126, v3=0, would
* cause all the red light to reflect and half of the green light to
* reflect. Used in combination with <b>emissive()</b>, <b>specular()</b>,
* and <b>shininess()</b> in setting the material properties of shapes.
*
* ( end auto-generated )
*
* @webref lights_camera:material_properties
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#emissive(float, float, float)
* @see PGraphics#specular(float, float, float)
* @see PGraphics#shininess(float)
*/
public void ambient(int rgb) {
if (recorder != null) recorder.ambient(rgb);
g.ambient(rgb);
}
/**
* @param gray number specifying value between white and black
*/
public void ambient(float gray) {
if (recorder != null) recorder.ambient(gray);
g.ambient(gray);
}
/**
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
*/
public void ambient(float v1, float v2, float v3) {
if (recorder != null) recorder.ambient(v1, v2, v3);
g.ambient(v1, v2, v3);
}
/**
* ( begin auto-generated from specular.xml )
*
* Sets the specular color of the materials used for shapes drawn to the
* screen, which sets the color of hightlights. Specular refers to light
* which bounces off a surface in a perferred direction (rather than
* bouncing in all directions like a diffuse light). Used in combination
* with <b>emissive()</b>, <b>ambient()</b>, and <b>shininess()</b> in
* setting the material properties of shapes.
*
* ( end auto-generated )
*
* @webref lights_camera:material_properties
* @usage web_application
* @param rgb color to set
* @see PGraphics#lightSpecular(float, float, float)
* @see PGraphics#ambient(float, float, float)
* @see PGraphics#emissive(float, float, float)
* @see PGraphics#shininess(float)
*/
public void specular(int rgb) {
if (recorder != null) recorder.specular(rgb);
g.specular(rgb);
}
/**
* gray number specifying value between white and black
*/
public void specular(float gray) {
if (recorder != null) recorder.specular(gray);
g.specular(gray);
}
/**
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
*/
public void specular(float v1, float v2, float v3) {
if (recorder != null) recorder.specular(v1, v2, v3);
g.specular(v1, v2, v3);
}
/**
* ( begin auto-generated from shininess.xml )
*
* Sets the amount of gloss in the surface of shapes. Used in combination
* with <b>ambient()</b>, <b>specular()</b>, and <b>emissive()</b> in
* setting the material properties of shapes.
*
* ( end auto-generated )
*
* @webref lights_camera:material_properties
* @usage web_application
* @param shine degree of shininess
* @see PGraphics#emissive(float, float, float)
* @see PGraphics#ambient(float, float, float)
* @see PGraphics#specular(float, float, float)
*/
public void shininess(float shine) {
if (recorder != null) recorder.shininess(shine);
g.shininess(shine);
}
/**
* ( begin auto-generated from emissive.xml )
*
* Sets the emissive color of the material used for drawing shapes drawn to
* the screen. Used in combination with <b>ambient()</b>,
* <b>specular()</b>, and <b>shininess()</b> in setting the material
* properties of shapes.
*
* ( end auto-generated )
*
* @webref lights_camera:material_properties
* @usage web_application
* @param rgb color to set
* @see PGraphics#ambient(float, float, float)
* @see PGraphics#specular(float, float, float)
* @see PGraphics#shininess(float)
*/
public void emissive(int rgb) {
if (recorder != null) recorder.emissive(rgb);
g.emissive(rgb);
}
/**
* gray number specifying value between white and black
*/
public void emissive(float gray) {
if (recorder != null) recorder.emissive(gray);
g.emissive(gray);
}
/**
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
*/
public void emissive(float v1, float v2, float v3) {
if (recorder != null) recorder.emissive(v1, v2, v3);
g.emissive(v1, v2, v3);
}
/**
* ( begin auto-generated from lights.xml )
*
* Sets the default ambient light, directional light, falloff, and specular
* values. The defaults are ambientLight(128, 128, 128) and
* directionalLight(128, 128, 128, 0, 0, -1), lightFalloff(1, 0, 0), and
* lightSpecular(0, 0, 0). Lights need to be included in the draw() to
* remain persistent in a looping program. Placing them in the setup() of a
* looping program will cause them to only have an effect the first time
* through the loop.
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @see PGraphics#ambientLight(float, float, float, float, float, float)
* @see PGraphics#directionalLight(float, float, float, float, float, float)
* @see PGraphics#pointLight(float, float, float, float, float, float)
* @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#noLights()
*/
public void lights() {
if (recorder != null) recorder.lights();
g.lights();
}
/**
* ( begin auto-generated from noLights.xml )
*
* Disable all lighting. Lighting is turned off by default and enabled with
* the <b>lights()</b> function. This function can be used to disable
* lighting so that 2D geometry (which does not require lighting) can be
* drawn after a set of lighted 3D geometry.
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @see PGraphics#lights()
*/
public void noLights() {
if (recorder != null) recorder.noLights();
g.noLights();
}
/**
* ( begin auto-generated from ambientLight.xml )
*
* Adds an ambient light. Ambient light doesn't come from a specific
* direction, the rays have light have bounced around so much that objects
* are evenly lit from all sides. Ambient lights are almost always used in
* combination with other types of lights. Lights need to be included in
* the <b>draw()</b> to remain persistent in a looping program. Placing
* them in the <b>setup()</b> of a looping program will cause them to only
* have an effect the first time through the loop. The effect of the
* parameters is determined by the current color mode.
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
* @see PGraphics#lights()
* @see PGraphics#directionalLight(float, float, float, float, float, float)
* @see PGraphics#pointLight(float, float, float, float, float, float)
* @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float)
*/
public void ambientLight(float v1, float v2, float v3) {
if (recorder != null) recorder.ambientLight(v1, v2, v3);
g.ambientLight(v1, v2, v3);
}
/**
* @param x x-coordinate of the light
* @param y y-coordinate of the light
* @param z z-coordinate of the light
*/
public void ambientLight(float v1, float v2, float v3,
float x, float y, float z) {
if (recorder != null) recorder.ambientLight(v1, v2, v3, x, y, z);
g.ambientLight(v1, v2, v3, x, y, z);
}
/**
* ( begin auto-generated from directionalLight.xml )
*
* Adds a directional light. Directional light comes from one direction and
* is stronger when hitting a surface squarely and weaker if it hits at a a
* gentle angle. After hitting a surface, a directional lights scatters in
* all directions. Lights need to be included in the <b>draw()</b> to
* remain persistent in a looping program. Placing them in the
* <b>setup()</b> of a looping program will cause them to only have an
* effect the first time through the loop. The affect of the <b>v1</b>,
* <b>v2</b>, and <b>v3</b> parameters is determined by the current color
* mode. The <b>nx</b>, <b>ny</b>, and <b>nz</b> parameters specify the
* direction the light is facing. For example, setting <b>ny</b> to -1 will
* cause the geometry to be lit from below (the light is facing directly upward).
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
* @param nx direction along the x-axis
* @param ny direction along the y-axis
* @param nz direction along the z-axis
* @see PGraphics#lights()
* @see PGraphics#ambientLight(float, float, float, float, float, float)
* @see PGraphics#pointLight(float, float, float, float, float, float)
* @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float)
*/
public void directionalLight(float v1, float v2, float v3,
float nx, float ny, float nz) {
if (recorder != null) recorder.directionalLight(v1, v2, v3, nx, ny, nz);
g.directionalLight(v1, v2, v3, nx, ny, nz);
}
/**
* ( begin auto-generated from pointLight.xml )
*
* Adds a point light. Lights need to be included in the <b>draw()</b> to
* remain persistent in a looping program. Placing them in the
* <b>setup()</b> of a looping program will cause them to only have an
* effect the first time through the loop. The affect of the <b>v1</b>,
* <b>v2</b>, and <b>v3</b> parameters is determined by the current color
* mode. The <b>x</b>, <b>y</b>, and <b>z</b> parameters set the position
* of the light.
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
* @param x x-coordinate of the light
* @param y y-coordinate of the light
* @param z z-coordinate of the light
* @see PGraphics#lights()
* @see PGraphics#directionalLight(float, float, float, float, float, float)
* @see PGraphics#ambientLight(float, float, float, float, float, float)
* @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float)
*/
public void pointLight(float v1, float v2, float v3,
float x, float y, float z) {
if (recorder != null) recorder.pointLight(v1, v2, v3, x, y, z);
g.pointLight(v1, v2, v3, x, y, z);
}
/**
* ( begin auto-generated from spotLight.xml )
*
* Adds a spot light. Lights need to be included in the <b>draw()</b> to
* remain persistent in a looping program. Placing them in the
* <b>setup()</b> of a looping program will cause them to only have an
* effect the first time through the loop. The affect of the <b>v1</b>,
* <b>v2</b>, and <b>v3</b> parameters is determined by the current color
* mode. The <b>x</b>, <b>y</b>, and <b>z</b> parameters specify the
* position of the light and <b>nx</b>, <b>ny</b>, <b>nz</b> specify the
* direction or light. The <b>angle</b> parameter affects angle of the
* spotlight cone.
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
* @param x x-coordinate of the light
* @param y y-coordinate of the light
* @param z z-coordinate of the light
* @param nx direction along the x axis
* @param ny direction along the y axis
* @param nz direction along the z axis
* @param angle angle of the spotlight cone
* @param concentration exponent determining the center bias of the cone
* @see PGraphics#lights()
* @see PGraphics#directionalLight(float, float, float, float, float, float)
* @see PGraphics#pointLight(float, float, float, float, float, float)
* @see PGraphics#ambientLight(float, float, float, float, float, float)
*/
public void spotLight(float v1, float v2, float v3,
float x, float y, float z,
float nx, float ny, float nz,
float angle, float concentration) {
if (recorder != null) recorder.spotLight(v1, v2, v3, x, y, z, nx, ny, nz, angle, concentration);
g.spotLight(v1, v2, v3, x, y, z, nx, ny, nz, angle, concentration);
}
/**
* ( begin auto-generated from lightFalloff.xml )
*
* Sets the falloff rates for point lights, spot lights, and ambient
* lights. The parameters are used to determine the falloff with the
* following equation:<br /><br />d = distance from light position to
* vertex position<br />falloff = 1 / (CONSTANT + d * LINEAR + (d*d) *
* QUADRATIC)<br /><br />Like <b>fill()</b>, it affects only the elements
* which are created after it in the code. The default value if
* <b>LightFalloff(1.0, 0.0, 0.0)</b>. Thinking about an ambient light with
* a falloff can be tricky. It is used, for example, if you wanted a region
* of your scene to be lit ambiently one color and another region to be lit
* ambiently by another color, you would use an ambient light with location
* and falloff. You can think of it as a point light that doesn't care
* which direction a surface is facing.
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @param constant constant value or determining falloff
* @param linear linear value for determining falloff
* @param quadratic quadratic value for determining falloff
* @see PGraphics#lights()
* @see PGraphics#ambientLight(float, float, float, float, float, float)
* @see PGraphics#pointLight(float, float, float, float, float, float)
* @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float)
* @see PGraphics#lightSpecular(float, float, float)
*/
public void lightFalloff(float constant, float linear, float quadratic) {
if (recorder != null) recorder.lightFalloff(constant, linear, quadratic);
g.lightFalloff(constant, linear, quadratic);
}
/**
* ( begin auto-generated from lightSpecular.xml )
*
* Sets the specular color for lights. Like <b>fill()</b>, it affects only
* the elements which are created after it in the code. Specular refers to
* light which bounces off a surface in a perferred direction (rather than
* bouncing in all directions like a diffuse light) and is used for
* creating highlights. The specular quality of a light interacts with the
* specular material qualities set through the <b>specular()</b> and
* <b>shininess()</b> functions.
*
* ( end auto-generated )
*
* @webref lights_camera:lights
* @usage web_application
* @param v1 red or hue value (depending on current color mode)
* @param v2 green or saturation value (depending on current color mode)
* @param v3 blue or brightness value (depending on current color mode)
* @see PGraphics#specular(float, float, float)
* @see PGraphics#lights()
* @see PGraphics#ambientLight(float, float, float, float, float, float)
* @see PGraphics#pointLight(float, float, float, float, float, float)
* @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float)
*/
public void lightSpecular(float v1, float v2, float v3) {
if (recorder != null) recorder.lightSpecular(v1, v2, v3);
g.lightSpecular(v1, v2, v3);
}
/**
* ( begin auto-generated from background.xml )
*
* The <b>background()</b> function sets the color used for the background
* of the Processing window. The default background is light gray. In the
* <b>draw()</b> function, the background color is used to clear the
* display window at the beginning of each frame.
* <br/> <br/>
* An image can also be used as the background for a sketch, however its
* width and height must be the same size as the sketch window. To resize
* an image 'b' to the size of the sketch window, use b.resize(width, height).
* <br/> <br/>
* Images used as background will ignore the current <b>tint()</b> setting.
* <br/> <br/>
* It is not possible to use transparency (alpha) in background colors with
* the main drawing surface, however they will work properly with <b>createGraphics()</b>.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* <p>Clear the background with a color that includes an alpha value. This can
* only be used with objects created by createGraphics(), because the main
* drawing surface cannot be set transparent.</p>
* <p>It might be tempting to use this function to partially clear the screen
* on each frame, however that's not how this function works. When calling
* background(), the pixels will be replaced with pixels that have that level
* of transparency. To do a semi-transparent overlay, use fill() with alpha
* and draw a rectangle.</p>
*
* @webref color:setting
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#stroke(float)
* @see PGraphics#fill(float)
* @see PGraphics#tint(float)
* @see PGraphics#colorMode(int)
*/
public void background(int rgb) {
if (recorder != null) recorder.background(rgb);
g.background(rgb);
}
/**
* @param alpha opacity of the background
*/
public void background(int rgb, float alpha) {
if (recorder != null) recorder.background(rgb, alpha);
g.background(rgb, alpha);
}
/**
* @param gray specifies a value between white and black
*/
public void background(float gray) {
if (recorder != null) recorder.background(gray);
g.background(gray);
}
public void background(float gray, float alpha) {
if (recorder != null) recorder.background(gray, alpha);
g.background(gray, alpha);
}
/**
* @param v1 red or hue value (depending on the current color mode)
* @param v2 green or saturation value (depending on the current color mode)
* @param v3 blue or brightness value (depending on the current color mode)
*/
public void background(float v1, float v2, float v3) {
if (recorder != null) recorder.background(v1, v2, v3);
g.background(v1, v2, v3);
}
public void background(float v1, float v2, float v3, float alpha) {
if (recorder != null) recorder.background(v1, v2, v3, alpha);
g.background(v1, v2, v3, alpha);
}
/**
* @webref color:setting
*/
public void clear() {
if (recorder != null) recorder.clear();
g.clear();
}
/**
* Takes an RGB or ARGB image and sets it as the background.
* The width and height of the image must be the same size as the sketch.
* Use image.resize(width, height) to make short work of such a task.<br/>
* <br/>
* Note that even if the image is set as RGB, the high 8 bits of each pixel
* should be set opaque (0xFF000000) because the image data will be copied
* directly to the screen, and non-opaque background images may have strange
* behavior. Use image.filter(OPAQUE) to handle this easily.<br/>
* <br/>
* When using 3D, this will also clear the zbuffer (if it exists).
*
* @param image PImage to set as background (must be same size as the sketch window)
*/
public void background(PImage image) {
if (recorder != null) recorder.background(image);
g.background(image);
}
/**
* ( begin auto-generated from colorMode.xml )
*
* Changes the way Processing interprets color data. By default, the
* parameters for <b>fill()</b>, <b>stroke()</b>, <b>background()</b>, and
* <b>color()</b> are defined by values between 0 and 255 using the RGB
* color model. The <b>colorMode()</b> function is used to change the
* numerical range used for specifying colors and to switch color systems.
* For example, calling <b>colorMode(RGB, 1.0)</b> will specify that values
* are specified between 0 and 1. The limits for defining colors are
* altered by setting the parameters range1, range2, range3, and range 4.
*
* ( end auto-generated )
*
* @webref color:setting
* @usage web_application
* @param mode Either RGB or HSB, corresponding to Red/Green/Blue and Hue/Saturation/Brightness
* @see PGraphics#background(float)
* @see PGraphics#fill(float)
* @see PGraphics#stroke(float)
*/
public void colorMode(int mode) {
if (recorder != null) recorder.colorMode(mode);
g.colorMode(mode);
}
/**
* @param max range for all color elements
*/
public void colorMode(int mode, float max) {
if (recorder != null) recorder.colorMode(mode, max);
g.colorMode(mode, max);
}
/**
* @param max1 range for the red or hue depending on the current color mode
* @param max2 range for the green or saturation depending on the current color mode
* @param max3 range for the blue or brightness depending on the current color mode
*/
public void colorMode(int mode, float max1, float max2, float max3) {
if (recorder != null) recorder.colorMode(mode, max1, max2, max3);
g.colorMode(mode, max1, max2, max3);
}
/**
* @param maxA range for the alpha
*/
public void colorMode(int mode,
float max1, float max2, float max3, float maxA) {
if (recorder != null) recorder.colorMode(mode, max1, max2, max3, maxA);
g.colorMode(mode, max1, max2, max3, maxA);
}
/**
* ( begin auto-generated from alpha.xml )
*
* Extracts the alpha value from a color.
*
* ( end auto-generated )
* @webref color:creating_reading
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#red(int)
* @see PGraphics#green(int)
* @see PGraphics#blue(int)
* @see PGraphics#hue(int)
* @see PGraphics#saturation(int)
* @see PGraphics#brightness(int)
*/
public final float alpha(int rgb) {
return g.alpha(rgb);
}
/**
* ( begin auto-generated from red.xml )
*
* Extracts the red value from a color, scaled to match current
* <b>colorMode()</b>. This value is always returned as a float so be
* careful not to assign it to an int value.<br /><br />The red() function
* is easy to use and undestand, but is slower than another technique. To
* achieve the same results when working in <b>colorMode(RGB, 255)</b>, but
* with greater speed, use the >> (right shift) operator with a bit
* mask. For example, the following two lines of code are equivalent:<br
* /><pre>float r1 = red(myColor);<br />float r2 = myColor >> 16
* & 0xFF;</pre>
*
* ( end auto-generated )
*
* @webref color:creating_reading
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#green(int)
* @see PGraphics#blue(int)
* @see PGraphics#alpha(int)
* @see PGraphics#hue(int)
* @see PGraphics#saturation(int)
* @see PGraphics#brightness(int)
* @see_external rightshift
*/
public final float red(int rgb) {
return g.red(rgb);
}
/**
* ( begin auto-generated from green.xml )
*
* Extracts the green value from a color, scaled to match current
* <b>colorMode()</b>. This value is always returned as a float so be
* careful not to assign it to an int value.<br /><br />The <b>green()</b>
* function is easy to use and undestand, but is slower than another
* technique. To achieve the same results when working in <b>colorMode(RGB,
* 255)</b>, but with greater speed, use the >> (right shift)
* operator with a bit mask. For example, the following two lines of code
* are equivalent:<br /><pre>float r1 = green(myColor);<br />float r2 =
* myColor >> 8 & 0xFF;</pre>
*
* ( end auto-generated )
*
* @webref color:creating_reading
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#red(int)
* @see PGraphics#blue(int)
* @see PGraphics#alpha(int)
* @see PGraphics#hue(int)
* @see PGraphics#saturation(int)
* @see PGraphics#brightness(int)
* @see_external rightshift
*/
public final float green(int rgb) {
return g.green(rgb);
}
/**
* ( begin auto-generated from blue.xml )
*
* Extracts the blue value from a color, scaled to match current
* <b>colorMode()</b>. This value is always returned as a float so be
* careful not to assign it to an int value.<br /><br />The <b>blue()</b>
* function is easy to use and undestand, but is slower than another
* technique. To achieve the same results when working in <b>colorMode(RGB,
* 255)</b>, but with greater speed, use a bit mask to remove the other
* color components. For example, the following two lines of code are
* equivalent:<br /><pre>float r1 = blue(myColor);<br />float r2 = myColor
* & 0xFF;</pre>
*
* ( end auto-generated )
*
* @webref color:creating_reading
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#red(int)
* @see PGraphics#green(int)
* @see PGraphics#alpha(int)
* @see PGraphics#hue(int)
* @see PGraphics#saturation(int)
* @see PGraphics#brightness(int)
* @see_external rightshift
*/
public final float blue(int rgb) {
return g.blue(rgb);
}
/**
* ( begin auto-generated from hue.xml )
*
* Extracts the hue value from a color.
*
* ( end auto-generated )
* @webref color:creating_reading
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#red(int)
* @see PGraphics#green(int)
* @see PGraphics#blue(int)
* @see PGraphics#alpha(int)
* @see PGraphics#saturation(int)
* @see PGraphics#brightness(int)
*/
public final float hue(int rgb) {
return g.hue(rgb);
}
/**
* ( begin auto-generated from saturation.xml )
*
* Extracts the saturation value from a color.
*
* ( end auto-generated )
* @webref color:creating_reading
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#red(int)
* @see PGraphics#green(int)
* @see PGraphics#blue(int)
* @see PGraphics#alpha(int)
* @see PGraphics#hue(int)
* @see PGraphics#brightness(int)
*/
public final float saturation(int rgb) {
return g.saturation(rgb);
}
/**
* ( begin auto-generated from brightness.xml )
*
* Extracts the brightness value from a color.
*
* ( end auto-generated )
*
* @webref color:creating_reading
* @usage web_application
* @param rgb any value of the color datatype
* @see PGraphics#red(int)
* @see PGraphics#green(int)
* @see PGraphics#blue(int)
* @see PGraphics#alpha(int)
* @see PGraphics#hue(int)
* @see PGraphics#saturation(int)
*/
public final float brightness(int rgb) {
return g.brightness(rgb);
}
/**
* ( begin auto-generated from lerpColor.xml )
*
* Calculates a color or colors between two color at a specific increment.
* The <b>amt</b> parameter is the amount to interpolate between the two
* values where 0.0 equal to the first point, 0.1 is very near the first
* point, 0.5 is half-way in between, etc.
*
* ( end auto-generated )
*
* @webref color:creating_reading
* @usage web_application
* @param c1 interpolate from this color
* @param c2 interpolate to this color
* @param amt between 0.0 and 1.0
* @see PImage#blendColor(int, int, int)
* @see PGraphics#color(float, float, float, float)
*/
public int lerpColor(int c1, int c2, float amt) {
return g.lerpColor(c1, c2, amt);
}
/**
* @nowebref
* Interpolate between two colors. Like lerp(), but for the
* individual color components of a color supplied as an int value.
*/
static public int lerpColor(int c1, int c2, float amt, int mode) {
return PGraphics.lerpColor(c1, c2, amt, mode);
}
/**
* Display a warning that the specified method is only available with 3D.
* @param method The method name (no parentheses)
*/
static public void showDepthWarning(String method) {
PGraphics.showDepthWarning(method);
}
/**
* Display a warning that the specified method that takes x, y, z parameters
* can only be used with x and y parameters in this renderer.
* @param method The method name (no parentheses)
*/
static public void showDepthWarningXYZ(String method) {
PGraphics.showDepthWarningXYZ(method);
}
/**
* Display a warning that the specified method is simply unavailable.
*/
static public void showMethodWarning(String method) {
PGraphics.showMethodWarning(method);
}
/**
* Error that a particular variation of a method is unavailable (even though
* other variations are). For instance, if vertex(x, y, u, v) is not
* available, but vertex(x, y) is just fine.
*/
static public void showVariationWarning(String str) {
PGraphics.showVariationWarning(str);
}
/**
* Display a warning that the specified method is not implemented, meaning
* that it could be either a completely missing function, although other
* variations of it may still work properly.
*/
static public void showMissingWarning(String method) {
PGraphics.showMissingWarning(method);
}
/**
* Return true if this renderer should be drawn to the screen. Defaults to
* returning true, since nearly all renderers are on-screen beasts. But can
* be overridden for subclasses like PDF so that a window doesn't open up.
* <br/> <br/>
* A better name? showFrame, displayable, isVisible, visible, shouldDisplay,
* what to call this?
*/
public boolean displayable() {
return g.displayable();
}
/**
* Return true if this renderer does rendering through OpenGL. Defaults to false.
*/
public boolean isGL() {
return g.isGL();
}
/**
* ( begin auto-generated from PImage_get.xml )
*
* Reads the color of any pixel or grabs a section of an image. If no
* parameters are specified, the entire image is returned. Use the <b>x</b>
* and <b>y</b> parameters to get the value of one pixel. Get a section of
* the display window by specifying an additional <b>width</b> and
* <b>height</b> parameter. When getting an image, the <b>x</b> and
* <b>y</b> parameters define the coordinates for the upper-left corner of
* the image, regardless of the current <b>imageMode()</b>.<br />
* <br />
* If the pixel requested is outside of the image window, black is
* returned. The numbers returned are scaled according to the current color
* ranges, but only RGB values are returned by this function. For example,
* even though you may have drawn a shape with <b>colorMode(HSB)</b>, the
* numbers returned will be in RGB format.<br />
* <br />
* Getting the color of a single pixel with <b>get(x, y)</b> is easy, but
* not as fast as grabbing the data directly from <b>pixels[]</b>. The
* equivalent statement to <b>get(x, y)</b> using <b>pixels[]</b> is
* <b>pixels[y*width+x]</b>. See the reference for <b>pixels[]</b> for more information.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Returns an ARGB "color" type (a packed 32 bit int with the color.
* If the coordinate is outside the image, zero is returned
* (black, but completely transparent).
* <P>
* If the image is in RGB format (i.e. on a PVideo object),
* the value will get its high bits set, just to avoid cases where
* they haven't been set already.
* <P>
* If the image is in ALPHA format, this returns a white with its
* alpha value set.
* <P>
* This function is included primarily for beginners. It is quite
* slow because it has to check to see if the x, y that was provided
* is inside the bounds, and then has to check to see what image
* type it is. If you want things to be more efficient, access the
* pixels[] array directly.
*
* @webref image:pixels
* @brief Reads the color of any pixel or grabs a rectangle of pixels
* @usage web_application
* @param x x-coordinate of the pixel
* @param y y-coordinate of the pixel
* @see PApplet#set(int, int, int)
* @see PApplet#pixels
* @see PApplet#copy(PImage, int, int, int, int, int, int, int, int)
*/
public int get(int x, int y) {
return g.get(x, y);
}
/**
* @param w width of pixel rectangle to get
* @param h height of pixel rectangle to get
*/
public PImage get(int x, int y, int w, int h) {
return g.get(x, y, w, h);
}
/**
* Returns a copy of this PImage. Equivalent to get(0, 0, width, height).
*/
public PImage get() {
return g.get();
}
/**
* ( begin auto-generated from PImage_set.xml )
*
* Changes the color of any pixel or writes an image directly into the
* display window.<br />
* <br />
* The <b>x</b> and <b>y</b> parameters specify the pixel to change and the
* <b>color</b> parameter specifies the color value. The color parameter is
* affected by the current color mode (the default is RGB values from 0 to
* 255). When setting an image, the <b>x</b> and <b>y</b> parameters define
* the coordinates for the upper-left corner of the image, regardless of
* the current <b>imageMode()</b>.
* <br /><br />
* Setting the color of a single pixel with <b>set(x, y)</b> is easy, but
* not as fast as putting the data directly into <b>pixels[]</b>. The
* equivalent statement to <b>set(x, y, #000000)</b> using <b>pixels[]</b>
* is <b>pixels[y*width+x] = #000000</b>. See the reference for
* <b>pixels[]</b> for more information.
*
* ( end auto-generated )
*
* @webref image:pixels
* @brief writes a color to any pixel or writes an image into another
* @usage web_application
* @param x x-coordinate of the pixel
* @param y y-coordinate of the pixel
* @param c any value of the color datatype
* @see PImage#get(int, int, int, int)
* @see PImage#pixels
* @see PImage#copy(PImage, int, int, int, int, int, int, int, int)
*/
public void set(int x, int y, int c) {
if (recorder != null) recorder.set(x, y, c);
g.set(x, y, c);
}
/**
* <h3>Advanced</h3>
* Efficient method of drawing an image's pixels directly to this surface.
* No variations are employed, meaning that any scale, tint, or imageMode
* settings will be ignored.
*
* @param img image to draw on screen
*/
public void set(int x, int y, PImage img) {
if (recorder != null) recorder.set(x, y, img);
g.set(x, y, img);
}
/**
* ( begin auto-generated from PImage_mask.xml )
*
* Masks part of an image from displaying by loading another image and
* using it as an alpha channel. This mask image should only contain
* grayscale data, but only the blue color channel is used. The mask image
* needs to be the same size as the image to which it is applied.<br />
* <br />
* In addition to using a mask image, an integer array containing the alpha
* channel data can be specified directly. This method is useful for
* creating dynamically generated alpha masks. This array must be of the
* same length as the target image's pixels array and should contain only
* grayscale data of values between 0-255.
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
*
* Set alpha channel for an image. Black colors in the source
* image will make the destination image completely transparent,
* and white will make things fully opaque. Gray values will
* be in-between steps.
* <P>
* Strictly speaking the "blue" value from the source image is
* used as the alpha color. For a fully grayscale image, this
* is correct, but for a color image it's not 100% accurate.
* For a more accurate conversion, first use filter(GRAY)
* which will make the image into a "correct" grayscale by
* performing a proper luminance-based conversion.
*
* @webref pimage:method
* @usage web_application
* @brief Masks part of an image with another image as an alpha channel
* @param maskArray array of integers used as the alpha channel, needs to be the same length as the image's pixel array
*/
public void mask(PImage img) {
if (recorder != null) recorder.mask(img);
g.mask(img);
}
public void filter(int kind) {
if (recorder != null) recorder.filter(kind);
g.filter(kind);
}
/**
* ( begin auto-generated from PImage_filter.xml )
*
* Filters an image as defined by one of the following modes:<br /><br
* />THRESHOLD - converts the image to black and white pixels depending if
* they are above or below the threshold defined by the level parameter.
* The level must be between 0.0 (black) and 1.0(white). If no level is
* specified, 0.5 is used.<br />
* <br />
* GRAY - converts any colors in the image to grayscale equivalents<br />
* <br />
* INVERT - sets each pixel to its inverse value<br />
* <br />
* POSTERIZE - limits each channel of the image to the number of colors
* specified as the level parameter<br />
* <br />
* BLUR - executes a Guassian blur with the level parameter specifying the
* extent of the blurring. If no level parameter is used, the blur is
* equivalent to Guassian blur of radius 1<br />
* <br />
* OPAQUE - sets the alpha channel to entirely opaque<br />
* <br />
* ERODE - reduces the light areas with the amount defined by the level
* parameter<br />
* <br />
* DILATE - increases the light areas with the amount defined by the level parameter
*
* ( end auto-generated )
*
* <h3>Advanced</h3>
* Method to apply a variety of basic filters to this image.
* <P>
* <UL>
* <LI>filter(BLUR) provides a basic blur.
* <LI>filter(GRAY) converts the image to grayscale based on luminance.
* <LI>filter(INVERT) will invert the color components in the image.
* <LI>filter(OPAQUE) set all the high bits in the image to opaque
* <LI>filter(THRESHOLD) converts the image to black and white.
* <LI>filter(DILATE) grow white/light areas
* <LI>filter(ERODE) shrink white/light areas
* </UL>
* Luminance conversion code contributed by
* <A HREF="http://www.toxi.co.uk">toxi</A>
* <P/>
* Gaussian blur code contributed by
* <A HREF="http://incubator.quasimondo.com">Mario Klingemann</A>
*
* @webref image:pixels
* @brief Converts the image to grayscale or black and white
* @usage web_application
* @param kind Either THRESHOLD, GRAY, OPAQUE, INVERT, POSTERIZE, BLUR, ERODE, or DILATE
* @param param unique for each, see above
*/
public void filter(int kind, float param) {
if (recorder != null) recorder.filter(kind, param);
g.filter(kind, param);
}
/**
* ( begin auto-generated from PImage_copy.xml )
*
* Copies a region of pixels from one image into another. If the source and
* destination regions aren't the same size, it will automatically resize
* source pixels to fit the specified target region. No alpha information
* is used in the process, however if the source image has an alpha channel
* set, it will be copied as well.
* <br /><br />
* As of release 0149, this function ignores <b>imageMode()</b>.
*
* ( end auto-generated )
*
* @webref image:pixels
* @brief Copies the entire image
* @usage web_application
* @param sx X coordinate of the source's upper left corner
* @param sy Y coordinate of the source's upper left corner
* @param sw source image width
* @param sh source image height
* @param dx X coordinate of the destination's upper left corner
* @param dy Y coordinate of the destination's upper left corner
* @param dw destination image width
* @param dh destination image height
* @see PGraphics#alpha(int)
* @see PImage#blend(PImage, int, int, int, int, int, int, int, int, int)
*/
public void copy(int sx, int sy, int sw, int sh,
int dx, int dy, int dw, int dh) {
if (recorder != null) recorder.copy(sx, sy, sw, sh, dx, dy, dw, dh);
g.copy(sx, sy, sw, sh, dx, dy, dw, dh);
}
/**
* @param src an image variable referring to the source image.
*/
public void copy(PImage src,
int sx, int sy, int sw, int sh,
int dx, int dy, int dw, int dh) {
if (recorder != null) recorder.copy(src, sx, sy, sw, sh, dx, dy, dw, dh);
g.copy(src, sx, sy, sw, sh, dx, dy, dw, dh);
}
public void blend(int sx, int sy, int sw, int sh,
int dx, int dy, int dw, int dh, int mode) {
if (recorder != null) recorder.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode);
g.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode);
}
/**
* ( begin auto-generated from PImage_blend.xml )
*
* Blends a region of pixels into the image specified by the <b>img</b>
* parameter. These copies utilize full alpha channel support and a choice
* of the following modes to blend the colors of source pixels (A) with the
* ones of pixels in the destination image (B):<br />
* <br />
* BLEND - linear interpolation of colours: C = A*factor + B<br />
* <br />
* ADD - additive blending with white clip: C = min(A*factor + B, 255)<br />
* <br />
* SUBTRACT - subtractive blending with black clip: C = max(B - A*factor,
* 0)<br />
* <br />
* DARKEST - only the darkest colour succeeds: C = min(A*factor, B)<br />
* <br />
* LIGHTEST - only the lightest colour succeeds: C = max(A*factor, B)<br />
* <br />
* DIFFERENCE - subtract colors from underlying image.<br />
* <br />
* EXCLUSION - similar to DIFFERENCE, but less extreme.<br />
* <br />
* MULTIPLY - Multiply the colors, result will always be darker.<br />
* <br />
* SCREEN - Opposite multiply, uses inverse values of the colors.<br />
* <br />
* OVERLAY - A mix of MULTIPLY and SCREEN. Multiplies dark values,
* and screens light values.<br />
* <br />
* HARD_LIGHT - SCREEN when greater than 50% gray, MULTIPLY when lower.<br />
* <br />
* SOFT_LIGHT - Mix of DARKEST and LIGHTEST.
* Works like OVERLAY, but not as harsh.<br />
* <br />
* DODGE - Lightens light tones and increases contrast, ignores darks.
* Called "Color Dodge" in Illustrator and Photoshop.<br />
* <br />
* BURN - Darker areas are applied, increasing contrast, ignores lights.
* Called "Color Burn" in Illustrator and Photoshop.<br />
* <br />
* All modes use the alpha information (highest byte) of source image
* pixels as the blending factor. If the source and destination regions are
* different sizes, the image will be automatically resized to match the
* destination size. If the <b>srcImg</b> parameter is not used, the
* display window is used as the source image.<br />
* <br />
* As of release 0149, this function ignores <b>imageMode()</b>.
*
* ( end auto-generated )
*
* @webref image:pixels
* @brief Copies a pixel or rectangle of pixels using different blending modes
* @param src an image variable referring to the source image
* @param sx X coordinate of the source's upper left corner
* @param sy Y coordinate of the source's upper left corner
* @param sw source image width
* @param sh source image height
* @param dx X coordinate of the destinations's upper left corner
* @param dy Y coordinate of the destinations's upper left corner
* @param dw destination image width
* @param dh destination image height
* @param mode Either BLEND, ADD, SUBTRACT, LIGHTEST, DARKEST, DIFFERENCE, EXCLUSION, MULTIPLY, SCREEN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, BURN
*
* @see PApplet#alpha(int)
* @see PImage#copy(PImage, int, int, int, int, int, int, int, int)
* @see PImage#blendColor(int,int,int)
*/
public void blend(PImage src,
int sx, int sy, int sw, int sh,
int dx, int dy, int dw, int dh, int mode) {
if (recorder != null) recorder.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode);
g.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode);
}
}
|