diff
stringlengths 164
2.11M
| is_single_chunk
bool 2
classes | is_single_function
bool 2
classes | buggy_function
stringlengths 0
335k
⌀ | fixed_function
stringlengths 23
335k
⌀ |
---|---|---|---|---|
diff --git a/src/com/android/gallery3d/ingest/ui/MtpImageView.java b/src/com/android/gallery3d/ingest/ui/MtpImageView.java
index 9ab78628d..67414c6c4 100644
--- a/src/com/android/gallery3d/ingest/ui/MtpImageView.java
+++ b/src/com/android/gallery3d/ingest/ui/MtpImageView.java
@@ -1,224 +1,227 @@
/*
* Copyright (C) 2013 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.gallery3d.ingest.ui;
import android.content.Context;
import android.graphics.Matrix;
import android.mtp.MtpDevice;
import android.mtp.MtpObjectInfo;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.AttributeSet;
import android.widget.ImageView;
import com.android.gallery3d.ingest.data.BitmapWithMetadata;
import com.android.gallery3d.ingest.data.MtpBitmapFetch;
import java.lang.ref.WeakReference;
public class MtpImageView extends ImageView {
private int mObjectHandle;
private int mGeneration;
private WeakReference<MtpImageView> mWeakReference = new WeakReference<MtpImageView>(this);
private Object mFetchLock = new Object();
private boolean mFetchPending = false;
private MtpObjectInfo mFetchObjectInfo;
private MtpDevice mFetchDevice;
private Object mFetchResult;
private static final FetchImageHandler sFetchHandler = FetchImageHandler.createOnNewThread();
private static final ShowImageHandler sFetchCompleteHandler = new ShowImageHandler();
private void init() {
showPlaceholder();
}
public MtpImageView(Context context) {
super(context);
init();
}
public MtpImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MtpImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void showPlaceholder() {
setImageResource(android.R.color.transparent);
}
public void setMtpDeviceAndObjectInfo(MtpDevice device, MtpObjectInfo object, int gen) {
int handle = object.getObjectHandle();
if (handle == mObjectHandle && gen == mGeneration) {
return;
}
cancelLoadingAndClear();
showPlaceholder();
mGeneration = gen;
mObjectHandle = handle;
synchronized (mFetchLock) {
mFetchObjectInfo = object;
mFetchDevice = device;
if (mFetchPending) return;
mFetchPending = true;
sFetchHandler.sendMessage(
sFetchHandler.obtainMessage(0, mWeakReference));
}
}
protected Object fetchMtpImageDataFromDevice(MtpDevice device, MtpObjectInfo info) {
return MtpBitmapFetch.getFullsize(device, info);
}
private float mLastBitmapWidth;
private float mLastBitmapHeight;
private int mLastRotationDegrees;
private Matrix mDrawMatrix = new Matrix();
private void updateDrawMatrix() {
mDrawMatrix.reset();
float dwidth;
float dheight;
float vheight = getHeight();
float vwidth = getWidth();
float scale;
boolean rotated90 = (mLastRotationDegrees % 180 != 0);
if (rotated90) {
dwidth = mLastBitmapHeight;
dheight = mLastBitmapWidth;
} else {
dwidth = mLastBitmapWidth;
dheight = mLastBitmapHeight;
}
if (dwidth <= vwidth && dheight <= vheight) {
scale = 1.0f;
} else {
scale = Math.min(vwidth / dwidth, vheight / dheight);
}
mDrawMatrix.setScale(scale, scale);
if (rotated90) {
mDrawMatrix.postTranslate(-dheight * scale * 0.5f,
-dwidth * scale * 0.5f);
mDrawMatrix.postRotate(mLastRotationDegrees);
mDrawMatrix.postTranslate(dwidth * scale * 0.5f,
dheight * scale * 0.5f);
}
mDrawMatrix.postTranslate((vwidth - dwidth * scale) * 0.5f,
(vheight - dheight * scale) * 0.5f);
if (!rotated90 && mLastRotationDegrees > 0) {
// rotated by a multiple of 180
mDrawMatrix.postRotate(mLastRotationDegrees, vwidth / 2, vheight / 2);
}
setImageMatrix(mDrawMatrix);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (changed && getScaleType() == ScaleType.MATRIX) {
updateDrawMatrix();
}
}
protected void onMtpImageDataFetchedFromDevice(Object result) {
BitmapWithMetadata bitmapWithMetadata = (BitmapWithMetadata)result;
if (getScaleType() == ScaleType.MATRIX) {
mLastBitmapHeight = bitmapWithMetadata.bitmap.getHeight();
mLastBitmapWidth = bitmapWithMetadata.bitmap.getWidth();
mLastRotationDegrees = bitmapWithMetadata.rotationDegrees;
updateDrawMatrix();
} else {
setRotation(bitmapWithMetadata.rotationDegrees);
}
+ setAlpha(0f);
setImageBitmap(bitmapWithMetadata.bitmap);
+ animate().alpha(1f);
}
protected void cancelLoadingAndClear() {
synchronized (mFetchLock) {
mFetchDevice = null;
mFetchObjectInfo = null;
mFetchResult = null;
}
+ animate().cancel();
setImageResource(android.R.color.transparent);
}
@Override
public void onDetachedFromWindow() {
cancelLoadingAndClear();
super.onDetachedFromWindow();
}
private static class FetchImageHandler extends Handler {
public FetchImageHandler(Looper l) {
super(l);
}
public static FetchImageHandler createOnNewThread() {
HandlerThread t = new HandlerThread("MtpImageView Fetch");
t.start();
return new FetchImageHandler(t.getLooper());
}
@Override
public void handleMessage(Message msg) {
@SuppressWarnings("unchecked")
MtpImageView parent = ((WeakReference<MtpImageView>) msg.obj).get();
if (parent == null) return;
MtpObjectInfo objectInfo;
MtpDevice device;
synchronized (parent.mFetchLock) {
parent.mFetchPending = false;
device = parent.mFetchDevice;
objectInfo = parent.mFetchObjectInfo;
}
if (device == null) return;
Object result = parent.fetchMtpImageDataFromDevice(device, objectInfo);
if (result == null) return;
synchronized (parent.mFetchLock) {
if (parent.mFetchObjectInfo != objectInfo) return;
parent.mFetchResult = result;
parent.mFetchDevice = null;
parent.mFetchObjectInfo = null;
sFetchCompleteHandler.sendMessage(
sFetchCompleteHandler.obtainMessage(0, parent.mWeakReference));
}
}
}
private static class ShowImageHandler extends Handler {
@Override
public void handleMessage(Message msg) {
@SuppressWarnings("unchecked")
MtpImageView parent = ((WeakReference<MtpImageView>) msg.obj).get();
if (parent == null) return;
Object result;
synchronized (parent.mFetchLock) {
result = parent.mFetchResult;
}
if (result == null) return;
parent.onMtpImageDataFetchedFromDevice(result);
}
}
}
| false | false | null | null |
diff --git a/hudson-core/src/main/java/hudson/model/RunMap.java b/hudson-core/src/main/java/hudson/model/RunMap.java
index 346eff73..c40166c5 100644
--- a/hudson-core/src/main/java/hudson/model/RunMap.java
+++ b/hudson-core/src/main/java/hudson/model/RunMap.java
@@ -1,1668 +1,1668 @@
/*******************************************************************************
*
* Copyright (c) 2004-2013 Oracle Corporation.
*
* 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:
*
* Kohsuke Kawaguchi, Tom Huybrechts, Roy Varghese
*
*
*******************************************************************************/
package hudson.model;
import com.google.common.base.Function;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.XppReader;
import hudson.Extension;
import hudson.model.listeners.RunListener;
import hudson.tasks.test.AbstractTestResultAction;
import hudson.util.AtomicFileWriter;
import hudson.util.XStream2;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.lang.StringUtils;
/**
* {@link Map} from build number to {@link Run}.
*
* <p> This class is multi-thread safe by using copy-on-write technique, and it
* also updates the bi-directional links within {@link Run} accordingly.
*
* @author Kohsuke Kawaguchi
*/
public final class RunMap<J extends Job<J, R>, R extends Run<J, R>>
extends AbstractMap<Integer, R>
implements SortedMap<Integer, R>, BuildHistory<J,R> {
final public XStream2 xstream = new XStream2();
final private Function<RunValue<J,R>, Record<J,R>> RUNVALUE_TO_RECORD_TRANSFORMER =
new Function<RunValue<J,R>, Record<J,R>>() {
@Override
public Record<J, R> apply(RunValue<J, R> input) {
return input;
}
};
@Override
public Iterator<Record<J, R>> iterator() {
return Iterators.transform(builds.values().iterator(), RUNVALUE_TO_RECORD_TRANSFORMER);
}
@Override
public List<Record<J,R>> allRecords() {
return ImmutableList.copyOf(iterator());
}
private enum BuildMarker {
LAST_COMPLETED,
LAST_SUCCESSFUL,
LAST_UNSUCCESSFUL,
LAST_FAILED,
LAST_STABLE,
LAST_UNSTABLE,
}
private transient HashMap<BuildMarker, RunValue<J,R>>
buildMarkersCache = new HashMap<BuildMarker, RunValue<J,R>>();
// copy-on-write map
private SortedMap<Integer, RunValue<J,R>> builds;
// A cache of build objects
private final transient LazyRunValueCache runValueCache = new LazyRunValueCache();
private volatile Map<Integer, Long> buildsTimeMap = new HashMap<Integer, Long>();
private transient File persistenceFile;
// Marker to indicate if this objects need to be saved to disk
private transient volatile boolean dirty;
// Reference to parent job.
final private J parent;
public RunMap(J parent) {
this.parent = parent;
builds = new TreeMap<Integer, RunValue<J,R>>(BUILD_TIME_COMPARATOR);
// Initialize xstream
xstream.alias("buildHistory", RunMap.class);
xstream.alias("builds", SortedMap.class);
xstream.alias("build", LazyRunValue.class);
xstream.alias("build", EagerRunValue.class);
}
public Set<Entry<Integer, R>> entrySet() {
return Maps.transformValues(builds, RUNVALUE_TO_RUN_TRANSFORMER).entrySet();
}
public synchronized R put(R value) {
return put(value.getNumber(), value);
}
@Override
public synchronized R put(Integer key, R value) {
// copy-on-write update
TreeMap<Integer, RunValue<J,R>> m = new TreeMap<Integer, RunValue<J,R>>(builds);
buildsTimeMap.put(key, value.getTimeInMillis());
final EagerRunValue erv = new EagerRunValue(this, value);
RunValue<J,R> r = update(m, key, erv);
// Save the build, so that we can reload it later.
// For now, the way to figure out if its saved is to check if the config file
// exists.
if ( !buildXmlExists(erv.buildDir())) {
try {
value.save();
} catch (IOException ex) {
LOGGER.warning("Unable to save build.xml to " + erv.buildDir().getPath());
// Not fatal, unless build object reference is released by
// Hudson, in which case it won't be loaded again unless
// it has actually started running.
}
}
setBuilds(Collections.unmodifiableSortedMap(m));
return r!= null? r.getBuild(): null;
}
private static boolean buildXmlExists(File buildDir) {
return new File(buildDir, "build.xml").exists();
}
@Override
public synchronized void putAll(Map<? extends Integer, ? extends R> rhs) {
throw new UnsupportedOperationException("Not implemented");
}
private synchronized void setBuilds(SortedMap<Integer, RunValue<J,R>> map) {
this.builds = map;
recalcMarkers();
saveToRunMapXml();
}
private synchronized void recalcMarkers() {
recalcLastSuccessful();
recalcLastUnsuccessful();
recalcLastCompleted();
recalcLastFailed();
recalcLastStable();
recalcLastUnstable();
}
private synchronized void putAllRunValues(SortedMap<Integer, RunValue<J,R>> lhs,
SortedMap<Integer, RunValue<J,R>> rhs) {
TreeMap<Integer, RunValue<J,R>> m = new TreeMap<Integer, RunValue<J,R>>(lhs);
buildsTimeMap.clear();
for (Map.Entry<Integer, RunValue<J,R>> e : rhs.entrySet()) {
RunValue<J,R> runValue = e.getValue();
buildsTimeMap.put(e.getKey(), runValue.timeInMillis);
update(m, e.getKey(), runValue);
}
setBuilds(Collections.unmodifiableSortedMap(m));
}
private RunValue<J,R> update(TreeMap<Integer, RunValue<J,R>> m, Integer key, RunValue<J,R> value) {
assert value != null;
// things are bit tricky because this map is order so that the newest one comes first,
// yet 'nextBuild' refers to the newer build.
RunValue<J,R> first = m.isEmpty() ? null : m.get(m.firstKey());
RunValue<J,R> runValue = m.put(key, value);
// R r = runValue != null? runValue.get(): null;
SortedMap<Integer, RunValue<J,R>> head = m.headMap(key);
if (!head.isEmpty()) {
if(m.containsKey(head.lastKey())) {
RunValue<J,R> prev = m.get(head.lastKey());
value.setPrevious(prev.getPrevious());
value.setNext(prev);
if (m.containsValue(value.getPrevious())) {
value.getPrevious().setNext(value);
}
prev.setPrevious( value);
}
} else {
value.setPrevious( first);
value.setNext(null);
if (m.containsValue(first)) {
first.setNext( value);
}
}
return runValue;
}
public synchronized boolean remove(R run) {
Integer buildNumber = run.getNumber();
RunValue<J,R> runValue = builds.get(buildNumber);
if ( runValue == null ) {
return false;
}
final RunValue<J,R> next = runValue.getNext();
if ( next != null) {
next.setPrevious( runValue.getPrevious());
}
final RunValue<J,R> prev = runValue.getPrevious();
if ( prev != null) {
prev.setNext( runValue.getNext());
}
// copy-on-write update
// This block is not thread safe
TreeMap<Integer, RunValue<J,R>> m = new TreeMap<Integer, RunValue<J,R>>(builds);
buildsTimeMap.remove(buildNumber);
RunValue<J,R> r = m.remove(buildNumber);
if ( r instanceof BuildNavigable) {
((BuildNavigable)run).setBuildNavigator(null);
}
setBuilds(Collections.unmodifiableSortedMap(m));
return r != null;
}
public synchronized void reset(TreeMap<Integer, RunValue<J,R>> map) {
putAllRunValues(builds, map);
}
/**
* Gets the read-only view of this map.
*/
public SortedMap<Integer, R> getView() {
return Maps.transformValues(builds, RUNVALUE_TO_RUN_TRANSFORMER);
}
//
// SortedMap delegation
//
public Comparator<? super Integer> comparator() {
return builds.comparator();
}
public SortedMap<Integer, R> subMap(Integer fromKey, Integer toKey) {
return Maps.transformValues(builds.subMap(fromKey, toKey), RUNVALUE_TO_RUN_TRANSFORMER);
// return new ReadonlySortedMap<J,R>(builds.subMap(fromKey, toKey));
}
public SortedMap<Integer, R> headMap(Integer toKey) {
return Maps.transformValues(builds.headMap(toKey), RUNVALUE_TO_RUN_TRANSFORMER);
// return new ReadonlySortedMap<J,R>((builds.headMap(toKey)));
}
public SortedMap<Integer, R> tailMap(Integer fromKey) {
return Maps.transformValues(builds.tailMap(fromKey), RUNVALUE_TO_RUN_TRANSFORMER);
// return new ReadonlySortedMap<J,R>(builds.tailMap(fromKey));
}
public Integer firstKey() {
return builds.firstKey();
}
public Integer lastKey() {
return builds.lastKey();
}
public static final Comparator<Comparable> COMPARATOR = new Comparator<Comparable>() {
public int compare(Comparable o1, Comparable o2) {
return -o1.compareTo(o2);
}
};
/**
* Compare Build by timestamp
*/
private Comparator<Integer> BUILD_TIME_COMPARATOR = new Comparator<Integer>() {
public int compare(Integer i1, Integer i2) {
Long date1 = buildsTimeMap.get(i1);
Long date2 = buildsTimeMap.get(i2);
if (null == date1 || null == date2) {
return COMPARATOR.compare(i1, i2);
}
return -date1.compareTo(date2);
}
};
@Override
public RunValue<J,R> getFirst() {
try {
return builds.get(builds.lastKey());
}
catch (NoSuchElementException ex) {
return null;
}
}
@Override
public RunValue<J,R> getLast() {
try {
return builds.get(builds.firstKey());
}
catch (NoSuchElementException ex) {
return null;
}
}
@Override
public R getLastBuild() {
final RunValue<J,R> runValue = getLast();
return runValue != null? runValue.getBuild(): null;
}
@Override
public R getFirstBuild() {
final RunValue<J,R> runValue = builds.get(builds.lastKey());
return runValue != null? runValue.getBuild(): null;
}
private void recalcLastSuccessful() {
RunValue<J,R> r = getLast();
while (r != null &&
(r.isBuilding() ||
r.getResult() == null ||
r.getResult().isWorseThan(Result.UNSTABLE))) {
r = r.getPrevious();
}
RunValue<J,R> old = buildMarkersCache.put(BuildMarker.LAST_SUCCESSFUL, r);
if ( r != old) {
markDirty(true);
}
}
@Override
public RunValue<J,R> getLastSuccessful() {
return buildMarkersCache.get(BuildMarker.LAST_SUCCESSFUL);
}
@Override
public R getLastSuccessfulBuild() {
RunValue<J,R> r = getLastSuccessful();
return r !=null? r.getBuild(): null;
}
private void recalcLastUnsuccessful() {
RunValue<J,R> r = getLast();
while (r != null
&& (r.isBuilding() || r.getResult() == Result.SUCCESS)) {
r = r.getPrevious();
}
RunValue<J,R> old = buildMarkersCache.put(BuildMarker.LAST_UNSUCCESSFUL, r);
if ( old != r) {
markDirty(true);
}
}
@Override
public RunValue<J,R> getLastUnsuccessful() {
return buildMarkersCache.get(BuildMarker.LAST_UNSUCCESSFUL);
}
@Override
public R getLastUnsuccessfulBuild() {
RunValue<J,R> r = getLastUnsuccessful();
return r!= null? r.getBuild(): null;
}
private void recalcLastUnstable() {
RunValue<J,R> r = getLast();
while (r != null
&& (r.isBuilding() || r.getResult() != Result.UNSTABLE)) {
r = r.getPrevious();
}
RunValue<J,R> old = buildMarkersCache.put(BuildMarker.LAST_UNSTABLE,r);
if ( old != r ) {
markDirty(true);
}
}
@Override
public RunValue<J,R> getLastUnstable() {
return buildMarkersCache.get(BuildMarker.LAST_UNSTABLE);
}
@Override
public R getLastUnstableBuild() {
RunValue<J,R> r = getLastUnstable();
return r != null? r.getBuild(): null;
}
private void recalcLastStable() {
RunValue<J,R> r = getLast();
while (r != null &&
(r.isBuilding() ||
r.getResult().isWorseThan(Result.SUCCESS))) {
r = r.getPrevious();
}
RunValue<J,R> old = buildMarkersCache.put(BuildMarker.LAST_STABLE,r);
if ( old != r ) {
markDirty(true);
}
}
@Override
public RunValue<J,R> getLastStable() {
return buildMarkersCache.get(BuildMarker.LAST_STABLE);
}
@Override
public R getLastStableBuild() {
RunValue<J,R> r = getLastStable();
return r != null? r.getBuild(): null;
}
private void recalcLastFailed() {
RunValue<J,R> r = getLast();
while (r != null && (r.isBuilding() || r.getResult() != Result.FAILURE)) {
r = r.getPrevious();
}
RunValue<J,R> old = buildMarkersCache.put(BuildMarker.LAST_FAILED, r);
if (old != r) {
markDirty(true);
}
}
@Override
public RunValue<J,R> getLastFailed() {
return buildMarkersCache.get(BuildMarker.LAST_FAILED);
}
@Override
public R getLastFailedBuild() {
RunValue<J,R> r = getLastFailed();
return r != null? r.getBuild(): null;
}
private void recalcLastCompleted() {
RunValue<J,R> r = getLast();
while (r != null && r.isBuilding()) {
r = r.getPrevious();
}
RunValue<J,R> old = buildMarkersCache.put(BuildMarker.LAST_COMPLETED, r);
if (old != r) {
markDirty(true);
}
}
@Override
public RunValue<J,R> getLastCompleted() {
return buildMarkersCache.get(BuildMarker.LAST_COMPLETED);
}
@Override
public R getLastCompletedBuild() {
RunValue<J,R> r = getLastCompleted();
return r != null? r.getBuild(): null;
}
@Override
public List<R> getLastBuildsOverThreshold(int numberOfBuilds, Result threshold) {
final List<Record<J,R>> records = getLastRecordsOverThreshold(numberOfBuilds, threshold);
return Lists.transform(records, new Function<Record<J,R>, R>() {
@Override
public R apply(Record<J, R> input) {
return input.getBuild();
}
});
}
@Override
public List<Record<J, R>> getLastRecordsOverThreshold(int numberOfRecords, Result threshold) {
List<Record<J,R>> result = new ArrayList<Record<J,R>>(numberOfRecords);
RunValue<J,R> r = getLast();
while (r != null && result.size() < numberOfRecords) {
if (!r.isBuilding() &&
(r.getResult() != null &&
r.getResult().isBetterOrEqualTo(threshold))) {
result.add(r);
}
r = r.getPrevious();
}
return result;
}
/**
* {@link Run} factory.
*/
public interface Constructor<R extends Run<?, R>> {
R create(File dir) throws IOException;
}
/**
* Fills in {@link RunMap} by loading build records from the file system.
*
* @param job Job that owns this map.
* @param cons Used to create new instance of {@link Run}.
*/
public synchronized void load(J job, Constructor<R> cons) {
// If saved Runmap exists, load from that.
File buildDir = job.getBuildDir();
persistenceFile = new java.io.File(buildDir, "_runmap.xml");
if ( !loadFromRunMapXml(job, cons)) {
final SimpleDateFormat formatter = Run.ID_FORMATTER.get();
TreeMap<Integer, RunValue<J,R>> m = new TreeMap<Integer, RunValue<J,R>>(BUILD_TIME_COMPARATOR);
buildDir.mkdirs();
String[] buildDirs = buildDir.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
// HUDSON-1461 sometimes create bogus data directories with impossible dates, such as year 0, April 31st,
// or August 0th. Date object doesn't roundtrip those, so we eventually fail to load this data.
// Don't even bother trying.
if (!isCorrectDate(name)) {
LOGGER.fine("Skipping " + new File(dir, name));
return false;
}
return !name.startsWith("0000") && new File(dir, name).isDirectory();
}
private boolean isCorrectDate(String name) {
try {
if (formatter.format(formatter.parse(name)).equals(name)) {
return true;
}
} catch (ParseException e) {
// fall through
}
return false;
}
});
for (String build : buildDirs) {
if (buildXmlExists(buildDir)) {
// if the build result file isn't in the directory, ignore it.
try {
RunValue<J,R> lzRunValue = new LazyRunValue<J,R>(this, buildDir, build, cons);
R b = lzRunValue.getBuild();
long timeInMillis = b.getTimeInMillis();
buildsTimeMap.put(b.getNumber(), timeInMillis);
lzRunValue.timeInMillis = timeInMillis;
m.put(b.getNumber(), lzRunValue);
} catch (InstantiationError e) {
e.printStackTrace();
}
}
}
reset(m);
}
}
private synchronized void markDirty(boolean value) {
this.dirty = value;
if ( !dirty ) {
// mark down
for (RunValue rv: builds.values()) {
rv.markDirty(false);
}
}
}
private boolean isDirty() {
return dirty;
}
private synchronized void saveToRunMapXml() {
if (!isDirty() || persistenceFile == null) {
return;
}
AtomicFileWriter w = null;
try {
w = new AtomicFileWriter(persistenceFile);
w.write("<?xml version='1.0' encoding='UTF-8'?>\n");
xstream.toXML(this, w);
w.commit();
markDirty(false);
} catch (Exception ex) {
LOGGER.log(Level.SEVERE, "Cannot write RunMap.xml", ex);
} finally {
if ( w != null) {
try { w.abort();} catch (IOException ex) {};
}
}
}
private synchronized boolean loadFromRunMapXml(J job, Constructor<R> cons) {
assert persistenceFile != null;
Reader r = null;
if ( persistenceFile.exists()) {
try {
r = new BufferedReader(new InputStreamReader(new FileInputStream(persistenceFile), "UTF-8"));
xstream.unmarshal(new XppReader(r), this);
// Fix up all the parent and constructor references
File buildDir = persistenceFile.getParentFile();
boolean wasBuilding = false;
for (RunValue<J,R> rv: builds.values()) {
assert rv instanceof LazyRunValue;
LazyRunValue<J,R> lrv = (LazyRunValue<J,R>) rv;
lrv.key.ctor = cons;
if ( lrv.isBuilding()) {
lrv.sync();
wasBuilding = true;
}
}
// If any builds were still building when file was last persisted
// update runMap with new status and save the file again.
if ( wasBuilding ) {
recalcMarkers();
saveToRunMapXml();
}
return true;
} catch (FileNotFoundException ex) {
LOGGER.log(Level.SEVERE, "Cannot read _runmap.xml", ex);
} catch (UnsupportedEncodingException ex) {
LOGGER.log(Level.SEVERE, "Cannot read _runmap.xml", ex);
persistenceFile.delete();
}
finally {
if ( r != null ) {
try { r.close(); } catch (Exception e) {}
}
}
}
return false;
}
private LazyRunValueCache runValueCache() {
return this.runValueCache;
}
private static class LazyRunValueCache {
final private LoadingCache<LazyRunValue.Key, Run> cache;
final static int EVICT_BUILD_IN_SECONDS = 60;
final static int MAX_ENTRIES = 10000;
private LazyRunValueCache() {
- cache = CacheBuilder.<LazyRunValue.Key, RunValue>newBuilder()
+ cache = CacheBuilder.newBuilder()
.expireAfterAccess(EVICT_BUILD_IN_SECONDS, TimeUnit.SECONDS)
.initialCapacity(1024)
.maximumSize(MAX_ENTRIES)
.softValues()
.build( new CacheLoader<LazyRunValue.Key, Run>() {
@Override
public Run load(LazyRunValue.Key key) throws Exception {
LazyRunValue.Key k = (LazyRunValue.Key)key;
Run r = k.ctor.create(k.referenced.buildDir());
if ( r instanceof BuildNavigable) {
((BuildNavigable)r).setBuildNavigator(k.referenced);
}
// Cannot call onLoad() here, it will try
// to query a mutating cache. So just mark it
// for refresh.
k.refreshed = true;
return r;
}
});
}
private Run get(LazyRunValue.Key key) {
try {
return cache.get(key);
} catch (ExecutionException ex) {
LOGGER.log(Level.SEVERE,"Unable to load build", ex);
return null;
}
}
}
static abstract class RunValue<J extends Job<J,R>, R extends Run<J,R>>
implements BuildHistory.Record<J,R> {
private transient RunMap<J,R> runMap;
long timeInMillis;
long duration;
String fullDisplayName;
String displayName;
String url;
String builtOnStr;
private RunValue<J,R> previous;
private RunValue<J,R> next;
boolean isBuilding;
boolean isLogUpdated;
Result result;
Run.State state;
private transient boolean dirty;
int buildNumber;
RunValue() {
}
protected void sync() {
R build = getBuild();
if ( build == null ) {
return;
}
setBuildNumber( build.getNumber());
setResult( build.getResult());
setState( build.getState());
setBuilding( build.isBuilding());
setLogUpdated( build.isLogUpdated());
setTimeInMillis( build.getTimeInMillis());
setDisplayName( build.getDisplayName());
setDuration( build.getDuration());
if ( build instanceof AbstractBuild) {
setBuiltOnNodeName(((AbstractBuild)build).getBuiltOnStr());
setFullDisplayName( build.getFullDisplayName());
setUrl( build.getUrl());
}
}
abstract File buildDir();
String relativeBuildDir(File buildsDir) {
return buildsDir.toURI().relativize(buildDir().toURI()).getPath();
}
public void setBuildNumber(int number) {
this.buildNumber = number;
}
public void setRunMap(RunMap runMap) {
this.runMap = runMap;
}
protected RunMap runMap() {
return runMap;
}
void setTimeInMillis(long millis) {
if ( this.timeInMillis == millis) {
return;
}
this.timeInMillis = millis;
markDirty(true);
}
void setDuration(long duration) {
if ( this.duration == duration) {
return;
}
this.duration = duration;
markDirty(true);
}
void setDisplayName(String name) {
if ( StringUtils.equals(this.displayName, name)) {
return;
}
this.displayName = name;
markDirty(true);
}
void setFullDisplayName(String name) {
if ( StringUtils.equals(this.fullDisplayName, name)) {
return;
}
this.fullDisplayName = name;
markDirty(true);
}
void setUrl(String url) {
if ( StringUtils.equals(this.url, url)) {
return;
}
this.url = url;
markDirty(true);
}
void setBuiltOnNodeName(String builtOn) {
if ( StringUtils.equals(this.builtOnStr, builtOn)) {
return;
}
this.builtOnStr = builtOn;
markDirty(true);
}
private void markDirty(boolean dirty) {
this.dirty = dirty;
if ( dirty ) {
// Dirty up
runMap.markDirty(true);
}
}
private boolean isDirty() {
return dirty;
}
void setResult(Result result) {
if ( result == this.result) {
return;
}
this.result = result;
markDirty(true);
}
void setState(Run.State state) {
if ( state == this.state) {
return;
}
this.state = state;
markDirty(true);
}
void setLogUpdated(boolean value) {
if (this.isLogUpdated == value) {
return;
}
this.isLogUpdated = value;
markDirty(true);
}
void setBuilding(boolean value) {
if (this.isBuilding == value) {
return;
}
this.isBuilding = value;
markDirty(true);
}
void setPrevious(RunValue<J,R> previousRunValue) {
if (this.previous == previousRunValue) {
return;
}
this.previous = previousRunValue;
markDirty(true);
}
void setNext(RunValue<J,R> nextRunvalue) {
if (this.next == nextRunvalue) {
return;
}
this.next = nextRunvalue;
markDirty(true);
}
@Override
public int getNumber() {
return buildNumber;
}
@Override
public String getDisplayName() {
return displayName;
}
@Override
public long getTimeInMillis() {
return timeInMillis;
}
@Override
public Calendar getTimestamp() {
GregorianCalendar c = new GregorianCalendar();
c.setTimeInMillis(getTimeInMillis());
return c;
}
@Override
public Date getTime() {
return new Date(getTimeInMillis());
}
@Override
public long getDuration() {
return duration;
}
@Override
public String getUrl() {
return url;
}
@Override
public String getFullDisplayName() {
return fullDisplayName;
}
@Override
public String getBuiltOnNodeName() {
return builtOnStr;
}
@Override
public RunValue<J,R> getPrevious() {
return previous;
}
@Override
public RunValue<J,R> getNext() {
return next;
}
@Override
public Result getResult() {
return result;
}
@Override
public J getParent() {
return runMap.parent;
}
@Override
public R getPreviousBuild() {
RunValue<J,R> v = getPrevious();
return v != null? v.getBuild(): null;
}
@Override
public R getNextBuild() {
RunValue<J,R> v = getNext();
return v != null? v.getBuild(): null;
}
public boolean isBuilding() {
return isBuilding;
}
public boolean isLogUpdated() {
return isLogUpdated;
}
@Override
public R getPreviousCompletedBuild() {
RunValue<J,R> v = getPreviousCompleted();
return v != null? v.getBuild(): null;
}
@Override
public RunValue<J,R> getPreviousCompleted() {
RunValue<J,R> v = getPrevious();
while (v != null && v.isBuilding()) {
v = v.getPrevious();
}
return v;
}
@Override
public R getPreviousBuildInProgress() {
RunValue<J,R> v = getPreviousInProgress();
return v != null? v.getBuild(): null;
}
@Override
public RunValue<J,R> getPreviousInProgress() {
RunValue<J,R> v = getPrevious();
while ( v != null && !v.isBuilding()) {
v = v.getPrevious();
}
return v;
}
@Override
public R getPreviousBuiltBuild() {
RunValue<J,R> v = getPreviousBuilt();
return v != null? v.getBuild(): null;
}
@Override
public RunValue<J,R> getPreviousBuilt() {
RunValue<J,R> v = getPrevious();
// in certain situations (aborted m2 builds) v.getResult() can still be null, although it should theoretically never happen
while (v != null && (v.getResult() == null || v.getResult() == Result.NOT_BUILT)) {
v = v.getPrevious();
}
return v;
}
@Override
public R getPreviousNotFailedBuild() {
RunValue<J,R> v = getPreviousNotFailed();
return v!= null? v.getBuild(): null;
}
@Override
public RunValue<J,R> getPreviousNotFailed() {
RunValue<J,R> v = getPrevious();
while (v != null && v.getResult() == Result.FAILURE) {
v = v.getPrevious();
}
return v;
}
@Override
public R getPreviousFailedBuild() {
RunValue<J,R> v = getPreviousFailed();
return v != null? v.getBuild(): null;
}
@Override
public RunValue<J,R> getPreviousFailed() {
RunValue<J,R> v = getPrevious();
while (v != null && v.getResult() != Result.FAILURE) {
v = v.getPrevious();
}
return v;
}
@Override
public R getPreviousSuccessfulBuild() {
RunValue<J,R> v = getPreviousSuccessful();
return v != null? v.getBuild(): null;
}
@Override
public RunValue<J,R> getPreviousSuccessful() {
RunValue<J,R> v = getPrevious();
while (v != null && v.getResult() != Result.SUCCESS) {
v = v.getPrevious();
}
return v;
}
@Override
public List<BuildHistory.Record<J,R>> getPreviousOverThreshold(int numberOfBuilds, Result threshold) {
List<BuildHistory.Record<J,R>> builds = new ArrayList<BuildHistory.Record<J,R>>(numberOfBuilds);
RunValue<J,R> r = getPrevious();
while (r != null && builds.size() < numberOfBuilds) {
if (!r.isBuilding()
&& (r.getResult() != null && r.getResult().isBetterOrEqualTo(threshold))) {
builds.add(r);
}
r = r.getPrevious();
}
return builds;
}
@Override
public List<R> getPreviousBuildsOverThreshold(int numberOfBuilds, Result threshold) {
return Lists.transform(getPreviousOverThreshold(numberOfBuilds, threshold),
new Function<BuildHistory.Record<J,R>, R>() {
@Override
public R apply(BuildHistory.Record<J,R> f) {
return f != null? f.getBuild(): null;
}
});
}
@Override
public Run.State getState() {
return state;
}
@Override
public BallColor getIconColor() {
if (!isBuilding()) {
// already built
return getResult().color;
}
// a new build is in progress
BallColor baseColor;
if (getPrevious() == null) {
baseColor = BallColor.GREY;
} else {
baseColor = getPrevious().getIconColor();
}
return baseColor.anime();
}
@Override
public String getBuildStatusUrl() {
return getIconColor().getImage();
}
@Override
public Run.Summary getBuildStatusSummary() {
Record<J,R> prev = getPrevious();
if (getResult() == Result.SUCCESS) {
if (prev == null || prev.getResult() == Result.SUCCESS) {
return new Run.Summary(false, Messages.Run_Summary_Stable());
} else {
return new Run.Summary(false, Messages.Run_Summary_BackToNormal());
}
}
if (getResult() == Result.FAILURE) {
Record<J,R> since = getPreviousNotFailed();
if (since == null) {
return new Run.Summary(false, Messages.Run_Summary_BrokenForALongTime());
}
if (since == prev) {
return new Run.Summary(true, Messages.Run_Summary_BrokenSinceThisBuild());
}
Record<J,R> failedBuild = since.getNext();
return new Run.Summary(false, Messages.Run_Summary_BrokenSince(failedBuild.getBuild().getDisplayName()));
}
if (getResult() == Result.ABORTED) {
return new Run.Summary(false, Messages.Run_Summary_Aborted());
}
if (getResult() == Result.UNSTABLE) {
R run = this.getBuild();
AbstractTestResultAction trN = ((AbstractBuild) run).getTestResultAction();
AbstractTestResultAction trP = prev == null ? null : ((AbstractBuild) prev.getBuild()).getTestResultAction();
if (trP == null) {
if (trN != null && trN.getFailCount() > 0) {
return new Run.Summary(false, Messages.Run_Summary_TestFailures(trN.getFailCount()));
} else // ???
{
return new Run.Summary(false, Messages.Run_Summary_Unstable());
}
}
if (trP.getFailCount() == 0) {
return new Run.Summary(true, Messages.Run_Summary_TestsStartedToFail(trN.getFailCount()));
}
if (trP.getFailCount() < trN.getFailCount()) {
return new Run.Summary(true, Messages.Run_Summary_MoreTestsFailing(trN.getFailCount() - trP.getFailCount(), trN.getFailCount()));
}
if (trP.getFailCount() > trN.getFailCount()) {
return new Run.Summary(false, Messages.Run_Summary_LessTestsFailing(trP.getFailCount() - trN.getFailCount(), trN.getFailCount()));
}
return new Run.Summary(false, Messages.Run_Summary_TestsStillFailing(trN.getFailCount()));
}
return new Run.Summary(false, Messages.Run_Summary_Unknown());
}
@Override
public String toString() {
return String.format("RunValue(number=%d,displayName=%s,buildDir=%s,state=%s,result=%s)",
buildNumber, displayName, buildDir(), state, result);
}
public static class ConverterImpl implements Converter {
final File buildsDir;
final RunMap runMap;
ConverterImpl(RunMap runMap) {
this.runMap = runMap;
this.buildsDir = runMap.persistenceFile.getParentFile();
}
@Override
public void marshal(Object o, HierarchicalStreamWriter writer, MarshallingContext mc) {
// TODO - turn element names sinto constants.
RunValue current = (RunValue) o;
writer.startNode("build");
writer.startNode("number");
writer.setValue(String.valueOf(current.buildNumber));
writer.endNode();
if ( current.displayName != null) {
writer.startNode("displayName");
writer.setValue(current.displayName);
writer.endNode();
}
if ( current.fullDisplayName != null) {
writer.startNode("fullDisplayName");
writer.setValue(current.fullDisplayName);
writer.endNode();
}
writer.startNode("buildDir");
writer.setValue( current.relativeBuildDir(buildsDir));
writer.endNode();
writer.startNode("state");
writer.setValue( current.state.toString());
writer.endNode();
if ( current.result != null) {
writer.startNode("result");
writer.setValue( current.result.toString());
writer.endNode();
}
writer.startNode("building");
writer.setValue( Boolean.toString( current.isBuilding));
writer.endNode();
writer.startNode("logUpdated");
writer.setValue( Boolean.toString( current.isLogUpdated()));
writer.endNode();
writer.startNode("timestamp");
writer.setValue( String.valueOf( current.timeInMillis));
writer.endNode();
writer.startNode("duration");
writer.setValue( String.valueOf( current.duration));
writer.endNode();
if ( current.url != null ) {
writer.startNode("url");
writer.setValue( current.url);
writer.endNode();
}
if ( current.builtOnStr != null) {
writer.startNode("builtOn");
writer.setValue( current.builtOnStr);
writer.endNode();
}
writer.endNode();
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext uc) {
LazyRunValue rv = new LazyRunValue(runMap);
assert "build".equals(reader.getNodeName());
while (reader.hasMoreChildren()) {
reader.moveDown();
String name = reader.getNodeName();
if ( "number".equals(name) ) {
rv.buildNumber = Integer.parseInt(reader.getValue());
}
else if ( "displayName".equals(name)) {
rv.displayName = reader.getValue();
}
else if ( "fullDisplayName".equals(name)) {
rv.fullDisplayName = reader.getValue();
}
else if ( "buildDir".equals(name)) {
rv.key.buildsDir = this.buildsDir;
rv.key.buildDir = reader.getValue();
}
else if ( "state".equals(name)) {
rv.state = Run.State.valueOf(reader.getValue());
}
else if ( "result".equals(name)) {
String resultValue = reader.getValue();
rv.result = resultValue.length() > 0? Result.fromString( resultValue ): null;
}
else if ( "building".equals(name)) {
rv.isBuilding = Boolean.parseBoolean(reader.getValue());
}
else if ( "logUpdated".equals(name)) {
rv.isLogUpdated = Boolean.parseBoolean(reader.getValue());
}
else if ( "timestamp".equals(name)) {
rv.timeInMillis = Long.parseLong(reader.getValue());
}
else if ( "duration".equals(name)) {
rv.duration = Long.parseLong(reader.getValue());
}
else if ("url".equals(name)) {
rv.url = reader.getValue();
if ( rv.url.length() == 0) {
rv = null;
}
}
else if ("builtOn".equals(name)) {
rv.builtOnStr = reader.getValue();
if ( rv.builtOnStr.length() == 0) {
rv.builtOnStr = null;
}
}
reader.moveUp();
}
return rv;
}
@Override
public boolean canConvert(Class type) {
return RunValue.class.isAssignableFrom(type);
}
}
}
/**
* Hold onto the Constructor and {@literal config} directory and re-instantiate on
* demand.
*/
static class LazyRunValue<J extends Job<J,R>, R extends Run<J,R>>
extends RunValue<J,R> {
private static class Key {
private String buildDir;
private File buildsDir;
private transient RunMap.Constructor ctor;
private final LazyRunValue referenced;
private volatile boolean refreshed;
Key(File buildsDir, String buildDir, RunMap.Constructor ctor, LazyRunValue ref) {
this.buildsDir = buildsDir;
this.buildDir = buildDir;
this.ctor = ctor;
this.referenced = ref;
}
@Override
public boolean equals(Object o) {
boolean equal = false;
if ( o instanceof Key) {
Key other = (Key)o;
equal = buildDir.equals(other.buildDir) &&
buildsDir.getPath().equals(other.buildsDir.getPath()) &&
ctor.equals(other.ctor);
}
return equal;
}
@Override
public int hashCode() {
return buildDir.hashCode();
}
}
private final Key key;
private LazyRunValue(RunMap runMap) {
// Used when loaded from file
this.key = new Key(null, null, null, this);
setRunMap(runMap);
}
private LazyRunValue( RunMap runMap, File buildsDir, String buildDir, RunMap.Constructor ctor) {
this.key = new Key(buildsDir, buildDir, ctor, this);
setRunMap(runMap);
sync();
}
@Override
File buildDir() {
return new File(key.buildsDir, key.buildDir);
}
@Override
public R getBuild() {
R v= (R) runMap().runValueCache().get(key);
if ( key.refreshed ) {
// key.refreshed is true if item has been loaded from disk
// for the first time by the cache.
key.refreshed = false;
v.onLoad();
}
return v;
}
}
/**
* No Lazy stuff here, just hold onto the instance since we do not
* know how to reconstruct it.
*/
private static class EagerRunValue<J extends Job<J,R>, R extends Run<J,R>> extends RunValue<J,R> {
private R referenced;
EagerRunValue(RunMap runMap, R r) {
setRunMap(runMap);
this.referenced = r;
if ( r instanceof BuildNavigable) {
((BuildNavigable)r).setBuildNavigator(this);
}
sync();
}
@Override
public R getBuild() {
return this.referenced;
}
@Override
File buildDir() {
return getBuild().getRootDir();
}
}
private static class RunEntry<J extends Job<J,R>, R extends Run<J,R> & BuildNavigable> implements Map.Entry<Integer, R> {
private Integer key;
private RunValue<J,R> value;
private RunEntry(Integer key, RunValue<J,R> value) {
this.key = key;
this.value = value;
}
@Override
public Integer getKey() {
return key;
}
@Override
public R getValue() {
return value.getBuild();
}
@Override
public R setValue(R value) {
throw new UnsupportedOperationException("Not implemented");
}
}
/**
* This is a global listener that is called for all types of builds, so
* does not have any type-arguments, but it only operates on AbstractProjects.
*/
@Extension
public static class RunValueUpdater extends RunListener<Run> {
private void update(Run run) {
// Updates a RunValue with the latest information from Run
final Object job = run.getParent();
if (job instanceof AbstractProject) {
final AbstractProject p = (AbstractProject) job;
RunValue rv = (RunValue) p.builds.builds.get(run.getNumber());
rv.sync();
p.builds.recalcMarkers();
p.builds.saveToRunMapXml();
}
}
@Override
public void onCompleted(Run r, TaskListener listener) {
update(r);
}
@Override
public void onFinalized(Run r) {
update(r);
}
@Override
public void onStarted(Run r, TaskListener listener) {
update(r);
}
@Override
public void onDeleted(Run r) {
update(r);
}
}
public static class ConverterImpl implements Converter {
@Override
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext mc) {
final RunMap runMap = (RunMap) source;
writer.startNode("builds");
RunValue rv = runMap.getFirst();
while ( rv != null) {
mc.convertAnother(rv, new RunValue.ConverterImpl(runMap));
rv = rv.getNext();
}
writer.endNode();
writer.startNode("markers");
for (Object bm: runMap.buildMarkersCache.keySet()) {
RunValue mbrv = (RunValue) runMap.buildMarkersCache.get(bm);
if ( mbrv != null) {
writer.startNode(((BuildMarker)bm).name());
writer.setValue(String.valueOf(mbrv.buildNumber));
writer.endNode();
}
}
writer.endNode();
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext uc) {
final RunMap runMap = (RunMap)uc.currentObject();
runMap.builds.clear();
runMap.buildsTimeMap.clear();
runMap.buildMarkersCache.clear();
while (reader.hasMoreChildren()) {
reader.moveDown();
if ( "builds".equals(reader.getNodeName())) {
RunValue prev = null;
while (reader.hasMoreChildren()) {
reader.moveDown();
RunValue rv = (RunValue) uc.convertAnother(runMap, RunValue.class,
new RunValue.ConverterImpl(runMap));
rv.setPrevious(prev);
runMap.builds.put(rv.getNumber(), rv);
runMap.buildsTimeMap.put(rv.getNumber(), rv.timeInMillis);
if ( prev != null ) {
prev.setNext(rv);
}
prev = rv;
reader.moveUp();
}
}
else if ("markers".equals(reader.getNodeName())) {
while (reader.hasMoreChildren()) {
reader.moveDown();
BuildMarker bm = BuildMarker.valueOf(reader.getNodeName());
Integer buildNumber = Integer.parseInt(reader.getValue());
RunValue bmrv = (RunValue) runMap.builds.get(buildNumber);
runMap.buildMarkersCache.put(bm, bmrv);
reader.moveUp();
}
}
reader.moveUp();
}
return runMap;
}
@Override
public boolean canConvert(Class type) {
return type == RunMap.class;
}
}
private final Function<RunValue<J,R>, R> RUNVALUE_TO_RUN_TRANSFORMER =
new Function<RunValue<J,R>,R>() {
@Override
public R apply(RunValue<J,R> input) {
final R build = input.getBuild();
return build;
}
};
private static final Logger LOGGER = Logger.getLogger(RunMap.class.getName());
}
diff --git a/hudson-core/src/main/java/hudson/model/TopLevelItemsCache.java b/hudson-core/src/main/java/hudson/model/TopLevelItemsCache.java
index 5f79df37..3c9a20c6 100644
--- a/hudson-core/src/main/java/hudson/model/TopLevelItemsCache.java
+++ b/hudson-core/src/main/java/hudson/model/TopLevelItemsCache.java
@@ -1,90 +1,90 @@
/*
* Copyright (c) 2013 Hudson.
* 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:
* Hudson - initial API and implementation and/or initial documentation
*/
package hudson.model;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A cache for {@link TopLevelItems} object that are directly held by
* the {@link Hudson} instance.
*
* This class is package private.
*
* @author Roy Varghese
*/
class TopLevelItemsCache {
// Cache parameters
private final static int EVICT_IN_SECONDS = 60;
private final static int INITIAL_CAPACITY = 1024;
private final static int MAX_ENTRIES = 1000;
final LoadingCache<LazyTopLevelItem.Key, TopLevelItem> cache;
TopLevelItemsCache() {
- cache = CacheBuilder.<LazyTopLevelItem.Key,TopLevelItem>newBuilder()
+ cache = CacheBuilder.newBuilder()
.initialCapacity(INITIAL_CAPACITY)
.expireAfterAccess(EVICT_IN_SECONDS, TimeUnit.SECONDS)
.maximumSize(MAX_ENTRIES)
.softValues()
.removalListener(new RemovalListener<LazyTopLevelItem.Key, TopLevelItem>() {
@Override
public void onRemoval(RemovalNotification<LazyTopLevelItem.Key, TopLevelItem> notification) {
// System.out.println("*** Removed from cache " + notification.getKey().name );
}
})
.build(new CacheLoader<LazyTopLevelItem.Key, TopLevelItem>() {
Map<String, Integer> map = new HashMap<String, Integer>();
@Override
public TopLevelItem load(LazyTopLevelItem.Key key) throws Exception {
TopLevelItem item = (TopLevelItem) key.configFile.read();
item.onLoad(key.parent, key.name);
return item;
}
});
}
TopLevelItem get(LazyTopLevelItem.Key key) {
try {
return cache.get(key);
} catch (ExecutionException ex) {
Logger.getLogger(TopLevelItemsCache.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
void put(LazyTopLevelItem.Key key, TopLevelItem item) {
cache.put(key, item);
}
}
| false | false | null | null |
diff --git a/app/in/partake/model/daofacade/EventDAOFacade.java b/app/in/partake/model/daofacade/EventDAOFacade.java
index 0b7f0d2..9941a34 100644
--- a/app/in/partake/model/daofacade/EventDAOFacade.java
+++ b/app/in/partake/model/daofacade/EventDAOFacade.java
@@ -1,229 +1,229 @@
package in.partake.model.daofacade;
import in.partake.base.TimeUtil;
import in.partake.base.Util;
import in.partake.model.EventCommentEx;
import in.partake.model.EventEx;
import in.partake.model.IPartakeDAOs;
import in.partake.model.UserEx;
import in.partake.model.dao.DAOException;
import in.partake.model.dao.DataIterator;
import in.partake.model.dao.PartakeConnection;
import in.partake.model.dao.access.IEventActivityAccess;
import in.partake.model.dto.Event;
import in.partake.model.dto.EventActivity;
import in.partake.model.dto.EventComment;
import in.partake.model.dto.EventFeed;
import in.partake.model.dto.EventTicket;
import in.partake.model.dto.MessageEnvelope;
import in.partake.model.dto.TwitterMessage;
import in.partake.model.dto.User;
import in.partake.model.dto.UserTwitterLink;
import in.partake.model.dto.auxiliary.MessageDelivery;
import in.partake.resource.PartakeProperties;
import in.partake.service.EventSearchServiceException;
import in.partake.service.IEventSearchService;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
public class EventDAOFacade {
private static final Logger logger = Logger.getLogger(EventDAOFacade.class);
public static EventEx getEventEx(PartakeConnection con, IPartakeDAOs daos, String eventId) throws DAOException {
Event event = daos.getEventAccess().find(con, eventId);
if (event == null) { return null; }
UserEx owner = UserDAOFacade.getUserEx(con, daos, event.getOwnerId());
if (owner == null) { return null; }
String feedId = daos.getEventFeedAccess().findByEventId(con, eventId);
List<EventTicket> tickets = daos.getEventTicketAccess().findEventTicketsByEventId(con, eventId);
List<User> editors = new ArrayList<User>();
if (event.getEditorIds() != null) {
for (String editorId : event.getEditorIds()) {
User editor = daos.getUserAccess().find(con, editorId);
if (editor != null)
editors.add(editor);
}
}
List<Event> relatedEvents = new ArrayList<Event>();
if (event.getRelatedEventIds() != null) {
for (String relatedEventId : event.getRelatedEventIds()) {
if (!Util.isUUID(relatedEventId))
continue;
Event relatedEvent = daos.getEventAccess().find(con, relatedEventId);
if (relatedEvent != null)
relatedEvents.add(relatedEvent);
}
}
return new EventEx(event, owner, feedId, tickets, editors, relatedEvents);
}
/**
* event をデータベースに保持します。
* @return event id
*/
public static String create(PartakeConnection con, IPartakeDAOs daos, Event eventEmbryo) throws DAOException {
String eventId = daos.getEventAccess().getFreshId(con);
eventEmbryo.setId(eventId);
daos.getEventAccess().put(con, eventEmbryo);
// Feed Dao にも挿入。
String feedId = daos.getEventFeedAccess().findByEventId(con, eventId);
if (feedId == null) {
feedId = daos.getEventFeedAccess().getFreshId(con);
daos.getEventFeedAccess().put(con, new EventFeed(feedId, eventId));
}
// Event Activity にも挿入
{
IEventActivityAccess eaa = daos.getEventActivityAccess();
EventActivity activity = new EventActivity(eaa.getFreshId(con), eventEmbryo.getId(), "イベントが登録されました : " + eventEmbryo.getTitle(), eventEmbryo.getDescription(), eventEmbryo.getCreatedAt());
eaa.put(con, activity);
}
// さらに、twitter bot がつぶやく (private の場合はつぶやかない)
if (eventEmbryo.isSearchable())
tweetNewEventArrival(con, daos, eventEmbryo);
return eventEmbryo.getId();
}
public static String copy(PartakeConnection con, IPartakeDAOs daos, UserEx user, Event event) throws DAOException {
// --- copy event.
Event newEvent = new Event(event);
newEvent.setId(null);
newEvent.setTitle(Util.shorten("コピー -- " + event.getTitle(), 100));
newEvent.setDraft(true);
newEvent.setOwnerId(user.getId());
String newEventId = EventDAOFacade.create(con, daos, newEvent);
newEvent.setId(newEventId);
// --- copy ticket.
List<EventTicket> tickets = daos.getEventTicketAccess().findEventTicketsByEventId(con, event.getId());
for (EventTicket ticket : tickets) {
EventTicket newTicket = new EventTicket(ticket);
newTicket.setId(daos.getEventTicketAccess().getFreshId(con));
newTicket.setEventId(newEventId);
daos.getEventTicketAccess().put(con, newTicket);
}
return newEventId;
}
public static void modify(PartakeConnection con, IPartakeDAOs daos, Event eventEmbryo) throws DAOException {
assert eventEmbryo != null;
assert eventEmbryo.getId() != null;
// master を update
daos.getEventAccess().put(con, eventEmbryo);
// Event Activity にも挿入
{
IEventActivityAccess eaa = daos.getEventActivityAccess();
EventActivity activity = new EventActivity(eaa.getFreshId(con), eventEmbryo.getId(), "イベントが更新されました : " + eventEmbryo.getTitle(), eventEmbryo.getDescription(), eventEmbryo.getCreatedAt());
eaa.put(con, activity);
}
// TODO: twitter bot が更新をつぶやいてもいいような気がする。
}
public static void recreateEventIndex(PartakeConnection con, IPartakeDAOs daos, IEventSearchService searchService) throws DAOException, EventSearchServiceException {
searchService.truncate();
DataIterator<Event> it = daos.getEventAccess().getIterator(con);
try {
while (it.hasNext()) {
Event event = it.next();
if (event == null) { continue; }
List<EventTicket> tickets = daos.getEventTicketAccess().findEventTicketsByEventId(con, event.getId());
if (!event.isSearchable())
searchService.remove(event.getId());
else if (searchService.hasIndexed(event.getId()))
searchService.update(event, tickets);
else
searchService.create(event, tickets);
}
} finally {
it.close();
}
}
// ----------------------------------------------------------------------
// Comments
public static EventCommentEx getCommentEx(PartakeConnection con, IPartakeDAOs daos, String commentId) throws DAOException {
EventComment comment = daos.getCommentAccess().find(con, commentId);
if (comment == null) { return null; }
UserEx user = UserDAOFacade.getUserEx(con, daos, comment.getUserId());
if (user == null) { return null; }
return new EventCommentEx(comment, user);
}
public static List<EventCommentEx> getCommentsExByEvent(PartakeConnection con, IPartakeDAOs daos, String eventId) throws DAOException {
List<EventCommentEx> result = new ArrayList<EventCommentEx>();
con.beginTransaction();
DataIterator<EventComment> iterator = daos.getCommentAccess().getCommentsByEvent(con, eventId);
try {
if (iterator == null) { return result; }
while (iterator.hasNext()) {
EventComment comment = iterator.next();
if (comment == null) { continue; }
String commentId = comment.getId();
if (commentId == null) { continue; }
EventCommentEx commentEx = getCommentEx(con, daos, commentId);
if (commentEx == null) { continue; }
result.add(commentEx);
}
} finally {
iterator.close();
}
return result;
}
public static void tweetNewEventArrival(PartakeConnection con, IPartakeDAOs daos, Event event) throws DAOException {
String hashTag = event.getHashTag() != null ? event.getHashTag() : "";
String messagePrefix = "[PARTAKE] 新しいイベントが追加されました :";
- String eventURL = event.getUrl(); // always 20
+ String eventURL = event.getEventURL(); // Always 20
int length = (messagePrefix.length() + 1) + (20 + 1) + (hashTag.length() + 1);
String title = Util.shorten(event.getTitle(), 140 - length);
String message = messagePrefix + " " + title + " " + eventURL + " " + hashTag;
long twitterId = PartakeProperties.get().getTwitterBotTwitterId();
if (twitterId < 0) {
logger.info("No bot id.");
return;
}
UserTwitterLink linkage = daos.getTwitterLinkageAccess().findByTwitterId(con, twitterId);
if (linkage == null) {
logger.info("twitter bot does have partake user id. Login using the account once to create the user id.");
return;
}
String userId = linkage.getUserId();
if (userId == null) {
logger.info("twitter bot does have partake user id. Login using the account once to create the user id.");
return;
}
String twitterMessageId = daos.getTwitterMessageAccess().getFreshId(con);
- TwitterMessage twitterMessage = new TwitterMessage(twitterMessageId, userId, twitterMessageId, MessageDelivery.INQUEUE, TimeUtil.getCurrentDateTime(), null);
+ TwitterMessage twitterMessage = new TwitterMessage(twitterMessageId, userId, message, MessageDelivery.INQUEUE, TimeUtil.getCurrentDateTime(), null);
daos.getTwitterMessageAccess().put(con, twitterMessage);
String envelopeId = daos.getMessageEnvelopeAccess().getFreshId(con);
MessageEnvelope envelope = MessageEnvelope.createForTwitterMessage(envelopeId, twitterMessageId, null);
daos.getMessageEnvelopeAccess().put(con, envelope);
logger.info("bot will tweet: " + message);
}
}
| false | true | public static void tweetNewEventArrival(PartakeConnection con, IPartakeDAOs daos, Event event) throws DAOException {
String hashTag = event.getHashTag() != null ? event.getHashTag() : "";
String messagePrefix = "[PARTAKE] 新しいイベントが追加されました :";
String eventURL = event.getUrl(); // always 20
int length = (messagePrefix.length() + 1) + (20 + 1) + (hashTag.length() + 1);
String title = Util.shorten(event.getTitle(), 140 - length);
String message = messagePrefix + " " + title + " " + eventURL + " " + hashTag;
long twitterId = PartakeProperties.get().getTwitterBotTwitterId();
if (twitterId < 0) {
logger.info("No bot id.");
return;
}
UserTwitterLink linkage = daos.getTwitterLinkageAccess().findByTwitterId(con, twitterId);
if (linkage == null) {
logger.info("twitter bot does have partake user id. Login using the account once to create the user id.");
return;
}
String userId = linkage.getUserId();
if (userId == null) {
logger.info("twitter bot does have partake user id. Login using the account once to create the user id.");
return;
}
String twitterMessageId = daos.getTwitterMessageAccess().getFreshId(con);
TwitterMessage twitterMessage = new TwitterMessage(twitterMessageId, userId, twitterMessageId, MessageDelivery.INQUEUE, TimeUtil.getCurrentDateTime(), null);
daos.getTwitterMessageAccess().put(con, twitterMessage);
String envelopeId = daos.getMessageEnvelopeAccess().getFreshId(con);
MessageEnvelope envelope = MessageEnvelope.createForTwitterMessage(envelopeId, twitterMessageId, null);
daos.getMessageEnvelopeAccess().put(con, envelope);
logger.info("bot will tweet: " + message);
}
| public static void tweetNewEventArrival(PartakeConnection con, IPartakeDAOs daos, Event event) throws DAOException {
String hashTag = event.getHashTag() != null ? event.getHashTag() : "";
String messagePrefix = "[PARTAKE] 新しいイベントが追加されました :";
String eventURL = event.getEventURL(); // Always 20
int length = (messagePrefix.length() + 1) + (20 + 1) + (hashTag.length() + 1);
String title = Util.shorten(event.getTitle(), 140 - length);
String message = messagePrefix + " " + title + " " + eventURL + " " + hashTag;
long twitterId = PartakeProperties.get().getTwitterBotTwitterId();
if (twitterId < 0) {
logger.info("No bot id.");
return;
}
UserTwitterLink linkage = daos.getTwitterLinkageAccess().findByTwitterId(con, twitterId);
if (linkage == null) {
logger.info("twitter bot does have partake user id. Login using the account once to create the user id.");
return;
}
String userId = linkage.getUserId();
if (userId == null) {
logger.info("twitter bot does have partake user id. Login using the account once to create the user id.");
return;
}
String twitterMessageId = daos.getTwitterMessageAccess().getFreshId(con);
TwitterMessage twitterMessage = new TwitterMessage(twitterMessageId, userId, message, MessageDelivery.INQUEUE, TimeUtil.getCurrentDateTime(), null);
daos.getTwitterMessageAccess().put(con, twitterMessage);
String envelopeId = daos.getMessageEnvelopeAccess().getFreshId(con);
MessageEnvelope envelope = MessageEnvelope.createForTwitterMessage(envelopeId, twitterMessageId, null);
daos.getMessageEnvelopeAccess().put(con, envelope);
logger.info("bot will tweet: " + message);
}
|
diff --git a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java
index a4dfe1c04..a57dafc92 100644
--- a/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java
+++ b/src/nativewindow/classes/com/jogamp/nativewindow/awt/JAWTWindow.java
@@ -1,771 +1,782 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Copyright (c) 2010 JogAmp Community. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution 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 Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
* INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN
* MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR
* ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
* DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR
* ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR
* DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE
* DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY,
* ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF
* SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use
* in the design, construction, operation or maintenance of any nuclear
* facility.
*/
package com.jogamp.nativewindow.awt;
import com.jogamp.common.os.Platform;
import com.jogamp.common.util.awt.AWTEDTExecutor;
import com.jogamp.common.util.locks.LockFactory;
import com.jogamp.common.util.locks.RecursiveLock;
import com.jogamp.nativewindow.MutableGraphicsConfiguration;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Window;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.applet.Applet;
import javax.media.nativewindow.AbstractGraphicsConfiguration;
import javax.media.nativewindow.AbstractGraphicsDevice;
import javax.media.nativewindow.CapabilitiesImmutable;
import javax.media.nativewindow.NativeSurface;
import javax.media.nativewindow.NativeWindow;
import javax.media.nativewindow.NativeWindowException;
import javax.media.nativewindow.OffscreenLayerOption;
import javax.media.nativewindow.OffscreenLayerSurface;
import javax.media.nativewindow.SurfaceUpdatedListener;
import javax.media.nativewindow.util.Insets;
import javax.media.nativewindow.util.InsetsImmutable;
import javax.media.nativewindow.util.PixelRectangle;
import javax.media.nativewindow.util.Point;
import javax.media.nativewindow.util.PointImmutable;
import javax.media.nativewindow.util.Rectangle;
import javax.media.nativewindow.util.RectangleImmutable;
import jogamp.nativewindow.SurfaceUpdatedHelper;
import jogamp.nativewindow.awt.AWTMisc;
import jogamp.nativewindow.jawt.JAWT;
import jogamp.nativewindow.jawt.JAWTUtil;
import jogamp.nativewindow.jawt.JAWT_Rectangle;
public abstract class JAWTWindow implements NativeWindow, OffscreenLayerSurface, OffscreenLayerOption {
protected static final boolean DEBUG = JAWTUtil.DEBUG;
// user properties
protected boolean shallUseOffscreenLayer = false;
// lifetime: forever
protected final Component component;
private final AWTGraphicsConfiguration config; // control access due to delegation
private final SurfaceUpdatedHelper surfaceUpdatedHelper = new SurfaceUpdatedHelper();
private final RecursiveLock surfaceLock = LockFactory.createRecursiveLock();
private final JAWTComponentListener jawtComponentListener;
// lifetime: valid after lock but may change with each 1st lock, purges after invalidate
private boolean isApplet;
private JAWT jawt;
private boolean isOffscreenLayerSurface;
protected long drawable;
protected Rectangle bounds;
protected Insets insets;
private volatile long offscreenSurfaceLayer;
private long drawable_old;
/**
* Constructed by {@link jogamp.nativewindow.NativeWindowFactoryImpl#getNativeWindow(Object, AbstractGraphicsConfiguration)}
* via this platform's specialization (X11, OSX, Windows, ..).
*
* @param comp
* @param config
*/
protected JAWTWindow(Object comp, AbstractGraphicsConfiguration config) {
if (config == null) {
throw new NativeWindowException("Error: AbstractGraphicsConfiguration is null");
}
if(! ( config instanceof AWTGraphicsConfiguration ) ) {
throw new NativeWindowException("Error: AbstractGraphicsConfiguration is not an AWTGraphicsConfiguration: "+config);
}
this.component = (Component)comp;
this.config = (AWTGraphicsConfiguration) config;
this.jawtComponentListener = new JAWTComponentListener();
invalidate();
this.isApplet = false;
this.offscreenSurfaceLayer = 0;
}
private static String id(Object obj) { return "0x" + ( null!=obj ? Integer.toHexString(obj.hashCode()) : "nil" ); }
private String jawtStr() { return "JAWTWindow["+id(JAWTWindow.this)+"]"; }
private class JAWTComponentListener implements ComponentListener, HierarchyListener {
private boolean isShowing;
private String str(final Object obj) {
if( null == obj ) {
return "0xnil: null";
} else if( obj instanceof Component ) {
final Component c = (Component)obj;
return id(obj)+": "+c.getClass().getSimpleName()+"[visible "+c.isVisible()+", showing "+c.isShowing()+", valid "+c.isValid()+
", displayable "+c.isDisplayable()+", "+c.getX()+"/"+c.getY()+" "+c.getWidth()+"x"+c.getHeight()+"]";
} else {
return id(obj)+": "+obj.getClass().getSimpleName()+"[..]";
}
}
private String s(final ComponentEvent e) {
return "visible[isShowing "+isShowing+"],"+Platform.getNewline()+
" ** COMP "+str(e.getComponent())+Platform.getNewline()+
" ** SOURCE "+str(e.getSource())+Platform.getNewline()+
" ** THIS "+str(component)+Platform.getNewline()+
" ** THREAD "+getThreadName();
}
private String s(final HierarchyEvent e) {
return "visible[isShowing "+isShowing+"], changeBits 0x"+Long.toHexString(e.getChangeFlags())+Platform.getNewline()+
" ** COMP "+str(e.getComponent())+Platform.getNewline()+
" ** SOURCE "+str(e.getSource())+Platform.getNewline()+
" ** CHANGED "+str(e.getChanged())+Platform.getNewline()+
" ** CHANGEDPARENT "+str(e.getChangedParent())+Platform.getNewline()+
" ** THIS "+str(component)+Platform.getNewline()+
" ** THREAD "+getThreadName();
}
@Override
public final String toString() {
return "visible[isShowing "+isShowing+"],"+Platform.getNewline()+
" ** THIS "+str(component)+Platform.getNewline()+
" ** THREAD "+getThreadName();
}
private JAWTComponentListener() {
isShowing = component.isShowing();
- if(DEBUG) {
- System.err.println(jawtStr()+".attach @ Thread "+getThreadName()+": "+toString());
- }
- component.addComponentListener(this);
- component.addHierarchyListener(this);
+ AWTEDTExecutor.singleton.invoke(false, new Runnable() { // Bug 952: Avoid deadlock via AWTTreeLock acquisition ..
+ @Override
+ public void run() {
+ if(DEBUG) {
+ System.err.println(jawtStr()+".attach @ Thread "+getThreadName()+": "+JAWTComponentListener.this.toString());
+ }
+ component.addComponentListener(JAWTComponentListener.this);
+ component.addHierarchyListener(JAWTComponentListener.this);
+ } } );
}
private final void detach() {
- if(DEBUG) {
- System.err.println(jawtStr()+".detach @ Thread "+getThreadName()+": "+toString());
- }
- component.removeComponentListener(this);
- component.removeHierarchyListener(this);
+ AWTEDTExecutor.singleton.invoke(false, new Runnable() { // Bug 952: Avoid deadlock via AWTTreeLock acquisition ..
+ @Override
+ public void run() {
+ if(DEBUG) {
+ System.err.println(jawtStr()+".detach @ Thread "+getThreadName()+": "+JAWTComponentListener.this.toString());
+ }
+ component.removeComponentListener(JAWTComponentListener.this);
+ component.removeHierarchyListener(JAWTComponentListener.this);
+ } } );
}
@Override
public final void componentResized(ComponentEvent e) {
if(DEBUG) {
System.err.println(jawtStr()+".componentResized: "+s(e));
}
layoutSurfaceLayerIfEnabled(isShowing);
}
@Override
public final void componentMoved(ComponentEvent e) {
if(DEBUG) {
System.err.println(jawtStr()+".componentMoved: "+s(e));
}
layoutSurfaceLayerIfEnabled(isShowing);
}
@Override
public final void componentShown(ComponentEvent e) {
if(DEBUG) {
System.err.println(jawtStr()+".componentShown: "+s(e));
}
layoutSurfaceLayerIfEnabled(isShowing);
}
@Override
public final void componentHidden(ComponentEvent e) {
if(DEBUG) {
System.err.println(jawtStr()+".componentHidden: "+s(e));
}
layoutSurfaceLayerIfEnabled(isShowing);
}
@Override
public final void hierarchyChanged(HierarchyEvent e) {
final boolean wasShowing = isShowing;
isShowing = component.isShowing();
int action = 0;
if( 0 != ( java.awt.event.HierarchyEvent.SHOWING_CHANGED & e.getChangeFlags() ) ) {
if( e.getChanged() != component && wasShowing != isShowing ) {
// A parent component changed and caused a 'showing' state change,
// propagate to offscreen-layer!
layoutSurfaceLayerIfEnabled(isShowing);
action = 1;
}
}
if(DEBUG) {
final java.awt.Component changed = e.getChanged();
final boolean displayable = changed.isDisplayable();
final boolean showing = changed.isShowing();
System.err.println(jawtStr()+".hierarchyChanged: action "+action+", displayable "+displayable+", showing [changed "+showing+", comp "+isShowing+"], "+s(e));
}
}
}
private static String getThreadName() { return Thread.currentThread().getName(); }
protected synchronized void invalidate() {
if(DEBUG) {
System.err.println(jawtStr()+".invalidate() - "+jawtComponentListener.toString());
if( isSurfaceLayerAttached() ) {
System.err.println("OffscreenSurfaceLayer still attached: 0x"+Long.toHexString(offscreenSurfaceLayer));
}
// Thread.dumpStack();
}
invalidateNative();
jawt = null;
isOffscreenLayerSurface = false;
drawable= 0;
drawable_old = 0;
bounds = new Rectangle();
insets = new Insets();
}
protected abstract void invalidateNative();
protected final boolean updateBounds(JAWT_Rectangle jawtBounds) {
final Rectangle jb = new Rectangle(jawtBounds.getX(), jawtBounds.getY(), jawtBounds.getWidth(), jawtBounds.getHeight());
final boolean changed = !bounds.equals(jb);
if(changed) {
if(DEBUG) {
System.err.println("JAWTWindow.updateBounds: "+bounds+" -> "+jb);
// Thread.dumpStack();
}
bounds.set(jawtBounds.getX(), jawtBounds.getY(), jawtBounds.getWidth(), jawtBounds.getHeight());
if(component instanceof Container) {
final java.awt.Insets contInsets = ((Container)component).getInsets();
insets.set(contInsets.left, contInsets.right, contInsets.top, contInsets.bottom);
}
}
return changed;
}
/** @return the JAWT_DrawingSurfaceInfo's (JAWT_Rectangle) bounds, updated with lock */
public final RectangleImmutable getBounds() { return bounds; }
@Override
public final InsetsImmutable getInsets() { return insets; }
public final Component getAWTComponent() {
return component;
}
/**
* Returns true if the AWT component is parented to an {@link java.applet.Applet},
* otherwise false. This information is valid only after {@link #lockSurface()}.
*/
public final boolean isApplet() {
return isApplet;
}
/** Returns the underlying JAWT instance created @ {@link #lockSurface()}. */
public final JAWT getJAWT() {
return jawt;
}
//
// OffscreenLayerOption
//
@Override
public void setShallUseOffscreenLayer(boolean v) {
shallUseOffscreenLayer = v;
}
@Override
public final boolean getShallUseOffscreenLayer() {
return shallUseOffscreenLayer;
}
@Override
public final boolean isOffscreenLayerSurfaceEnabled() {
return isOffscreenLayerSurface;
}
//
// OffscreenLayerSurface
//
@Override
public final void attachSurfaceLayer(final long layerHandle) throws NativeWindowException {
if( !isOffscreenLayerSurfaceEnabled() ) {
throw new NativeWindowException("Not an offscreen layer surface");
}
attachSurfaceLayerImpl(layerHandle);
offscreenSurfaceLayer = layerHandle;
component.repaint();
}
protected void attachSurfaceLayerImpl(final long layerHandle) {
throw new UnsupportedOperationException("offscreen layer not supported");
}
/**
* Layout the offscreen layer according to the implementing class's constraints.
* <p>
* This method allows triggering a re-layout of the offscreen surface
* in case the implementation requires it.
* </p>
* <p>
* Call this method if any parent or ancestor's layout has been changed,
* which could affects the layout of this surface.
* </p>
* @see #isOffscreenLayerSurfaceEnabled()
* @throws NativeWindowException if {@link #isOffscreenLayerSurfaceEnabled()} == false
*/
protected void layoutSurfaceLayerImpl(long layerHandle, boolean visible) {}
private final void layoutSurfaceLayerIfEnabled(boolean visible) throws NativeWindowException {
if( isOffscreenLayerSurfaceEnabled() && 0 != offscreenSurfaceLayer ) {
layoutSurfaceLayerImpl(offscreenSurfaceLayer, visible);
}
}
@Override
public final void detachSurfaceLayer() throws NativeWindowException {
if( 0 == offscreenSurfaceLayer) {
throw new NativeWindowException("No offscreen layer attached: "+this);
}
if(DEBUG) {
System.err.println("JAWTWindow.detachSurfaceHandle(): osh "+toHexString(offscreenSurfaceLayer));
}
detachSurfaceLayerImpl(offscreenSurfaceLayer, detachSurfaceLayerNotify);
}
private final Runnable detachSurfaceLayerNotify = new Runnable() {
@Override
public void run() {
offscreenSurfaceLayer = 0;
}
};
/**
* @param detachNotify Runnable to be called before native detachment
*/
protected void detachSurfaceLayerImpl(final long layerHandle, final Runnable detachNotify) {
throw new UnsupportedOperationException("offscreen layer not supported");
}
@Override
public final long getAttachedSurfaceLayer() {
return offscreenSurfaceLayer;
}
@Override
public final boolean isSurfaceLayerAttached() {
return 0 != offscreenSurfaceLayer;
}
@Override
public final void setChosenCapabilities(CapabilitiesImmutable caps) {
((MutableGraphicsConfiguration)getGraphicsConfiguration()).setChosenCapabilities(caps);
config.setChosenCapabilities(caps);
}
@Override
public final RecursiveLock getLock() {
return surfaceLock;
}
@Override
public final boolean setCursor(final PixelRectangle pixelrect, final PointImmutable hotSpot) {
AWTEDTExecutor.singleton.invoke(false, new Runnable() {
public void run() {
Cursor c = null;
if( null == pixelrect || null == hotSpot ) {
c = Cursor.getDefaultCursor();
} else {
final java.awt.Point awtHotspot = new java.awt.Point(hotSpot.getX(), hotSpot.getY());
try {
c = AWTMisc.getCursor(pixelrect, awtHotspot);
} catch (Exception e) {
e.printStackTrace();
}
}
if( null != c ) {
component.setCursor(c);
}
} } );
return true;
}
@Override
public final boolean hideCursor() {
AWTEDTExecutor.singleton.invoke(false, new Runnable() {
public void run() {
component.setCursor(AWTMisc.getNullCursor());
} } );
return true;
}
//
// SurfaceUpdateListener
//
@Override
public void addSurfaceUpdatedListener(SurfaceUpdatedListener l) {
surfaceUpdatedHelper.addSurfaceUpdatedListener(l);
}
@Override
public void addSurfaceUpdatedListener(int index, SurfaceUpdatedListener l) throws IndexOutOfBoundsException {
surfaceUpdatedHelper.addSurfaceUpdatedListener(index, l);
}
@Override
public void removeSurfaceUpdatedListener(SurfaceUpdatedListener l) {
surfaceUpdatedHelper.removeSurfaceUpdatedListener(l);
}
@Override
public void surfaceUpdated(Object updater, NativeSurface ns, long when) {
surfaceUpdatedHelper.surfaceUpdated(updater, ns, when);
}
//
// NativeSurface
//
private void determineIfApplet() {
Component c = component;
while(!isApplet && null != c) {
isApplet = c instanceof Applet;
c = c.getParent();
}
}
/**
* If JAWT offscreen layer is supported,
* implementation shall respect {@link #getShallUseOffscreenLayer()}
* and may respect {@link #isApplet()}.
*
* @return The JAWT instance reflecting offscreen layer support, etc.
*
* @throws NativeWindowException
*/
protected abstract JAWT fetchJAWTImpl() throws NativeWindowException;
protected abstract int lockSurfaceImpl() throws NativeWindowException;
protected void dumpJAWTInfo() {
System.err.println(jawt2String(null).toString());
// Thread.dumpStack();
}
@Override
public final int lockSurface() throws NativeWindowException, RuntimeException {
surfaceLock.lock();
int res = surfaceLock.getHoldCount() == 1 ? LOCK_SURFACE_NOT_READY : LOCK_SUCCESS; // new lock ?
if ( LOCK_SURFACE_NOT_READY == res ) {
if( !component.isDisplayable() ) {
// W/o native peer, we cannot utilize JAWT for locking.
surfaceLock.unlock();
if(DEBUG) {
System.err.println("JAWTWindow: Can't lock surface, component peer n/a. Component displayable "+component.isDisplayable()+", "+component);
Thread.dumpStack();
}
} else {
determineIfApplet();
try {
final AbstractGraphicsDevice adevice = getGraphicsConfiguration().getScreen().getDevice();
adevice.lock();
try {
if(null == jawt) { // no need to re-fetch for each frame
jawt = fetchJAWTImpl();
isOffscreenLayerSurface = JAWTUtil.isJAWTUsingOffscreenLayer(jawt);
}
res = lockSurfaceImpl();
if(LOCK_SUCCESS == res && drawable_old != drawable) {
res = LOCK_SURFACE_CHANGED;
if(DEBUG) {
System.err.println("JAWTWindow: surface change "+toHexString(drawable_old)+" -> "+toHexString(drawable));
// Thread.dumpStack();
}
}
} finally {
if (LOCK_SURFACE_NOT_READY >= res) {
adevice.unlock();
}
}
} finally {
if (LOCK_SURFACE_NOT_READY >= res) {
surfaceLock.unlock();
}
}
}
}
return res;
}
protected abstract void unlockSurfaceImpl() throws NativeWindowException;
@Override
public final void unlockSurface() {
surfaceLock.validateLocked();
drawable_old = drawable;
if (surfaceLock.getHoldCount() == 1) {
final AbstractGraphicsDevice adevice = getGraphicsConfiguration().getScreen().getDevice();
try {
if(null != jawt) {
unlockSurfaceImpl();
}
} finally {
adevice.unlock();
}
}
surfaceLock.unlock();
}
@Override
public final boolean isSurfaceLockedByOtherThread() {
return surfaceLock.isLockedByOtherThread();
}
@Override
public final Thread getSurfaceLockOwner() {
return surfaceLock.getOwner();
}
@Override
public boolean surfaceSwap() {
return false;
}
@Override
public long getSurfaceHandle() {
return drawable;
}
@Override
public final AbstractGraphicsConfiguration getGraphicsConfiguration() {
return config.getNativeGraphicsConfiguration();
}
@Override
public final long getDisplayHandle() {
return getGraphicsConfiguration().getScreen().getDevice().getHandle();
}
@Override
public final int getScreenIndex() {
return getGraphicsConfiguration().getScreen().getIndex();
}
@Override
public final int getWidth() {
return component.getWidth();
}
@Override
public final int getHeight() {
return component.getHeight();
}
//
// NativeWindow
//
@Override
public void destroy() {
surfaceLock.lock();
try {
+ if(DEBUG) {
+ System.err.println(jawtStr()+".destroy @ Thread "+getThreadName());
+ }
jawtComponentListener.detach();
invalidate();
} finally {
surfaceLock.unlock();
}
}
@Override
public final NativeWindow getParent() {
return null;
}
@Override
public long getWindowHandle() {
return drawable;
}
@Override
public final int getX() {
return component.getX();
}
@Override
public final int getY() {
return component.getY();
}
/**
* {@inheritDoc}
*
* <p>
* This JAWT default implementation is currently still using
* a blocking implementation. It first attempts to retrieve the location
* via a native implementation. If this fails, it tries the blocking AWT implementation.
* If the latter fails due to an external AWT tree-lock, the non block
* implementation {@link #getLocationOnScreenNonBlocking(Point, Component)} is being used.
* The latter simply traverse up to the AWT component tree and sums the rel. position.
* We have to determine whether the latter is good enough for all cases,
* currently only OS X utilizes the non blocking method per default.
* </p>
*/
@Override
public Point getLocationOnScreen(Point storage) {
Point los = getLocationOnScreenNative(storage);
if(null == los) {
if(!Thread.holdsLock(component.getTreeLock())) {
// avoid deadlock ..
if(DEBUG) {
System.err.println("Warning: JAWT Lock hold, but not the AWT tree lock: "+this);
Thread.dumpStack();
}
if( null == storage ) {
storage = new Point();
}
getLocationOnScreenNonBlocking(storage, component);
return storage;
}
java.awt.Point awtLOS = component.getLocationOnScreen();
if(null!=storage) {
los = storage.translate(awtLOS.x, awtLOS.y);
} else {
los = new Point(awtLOS.x, awtLOS.y);
}
}
return los;
}
protected Point getLocationOnScreenNative(Point storage) {
int lockRes = lockSurface();
if(LOCK_SURFACE_NOT_READY == lockRes) {
if(DEBUG) {
System.err.println("Warning: JAWT Lock couldn't be acquired: "+this);
Thread.dumpStack();
}
return null;
}
try {
Point d = getLocationOnScreenNativeImpl(0, 0);
if(null!=d) {
if(null!=storage) {
storage.translate(d.getX(),d.getY());
return storage;
}
}
return d;
} finally {
unlockSurface();
}
}
protected abstract Point getLocationOnScreenNativeImpl(int x, int y);
protected static Component getLocationOnScreenNonBlocking(Point storage, Component comp) {
final java.awt.Insets insets = new java.awt.Insets(0, 0, 0, 0); // DEBUG
Component last = null;
while(null != comp) {
final int dx = comp.getX();
final int dy = comp.getY();
if( DEBUG ) {
final java.awt.Insets ins = AWTMisc.getInsets(comp, false);
if( null != ins ) {
insets.bottom += ins.bottom;
insets.top += ins.top;
insets.left += ins.left;
insets.right += ins.right;
}
System.err.print("LOS: "+storage+" + "+comp.getClass().getName()+"["+dx+"/"+dy+", vis "+comp.isVisible()+", ins "+ins+" -> "+insets+"] -> ");
}
storage.translate(dx, dy);
if( DEBUG ) {
System.err.println(storage);
}
last = comp;
if( comp instanceof Window ) { // top-level heavy-weight ?
break;
}
comp = comp.getParent();
}
return last;
}
@Override
public boolean hasFocus() {
return component.hasFocus();
}
protected StringBuilder jawt2String(StringBuilder sb) {
if( null == sb ) {
sb = new StringBuilder();
}
sb.append("JVM version: ").append(Platform.JAVA_VERSION).append(" (").
append(Platform.JAVA_VERSION_NUMBER).
append(" update ").append(Platform.JAVA_VERSION_UPDATE).append(")").append(Platform.getNewline());
if(null != jawt) {
sb.append("JAWT version: 0x").append(Integer.toHexString(jawt.getCachedVersion())).
append(", CA_LAYER: ").append(JAWTUtil.isJAWTUsingOffscreenLayer(jawt)).
append(", isLayeredSurface ").append(isOffscreenLayerSurfaceEnabled()).append(", bounds ").append(bounds).append(", insets ").append(insets);
} else {
sb.append("JAWT n/a, bounds ").append(bounds).append(", insets ").append(insets);
}
return sb;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(jawtStr()+"[");
jawt2String(sb);
sb.append( ", shallUseOffscreenLayer "+shallUseOffscreenLayer+", isOffscreenLayerSurface "+isOffscreenLayerSurface+
", attachedSurfaceLayer "+toHexString(getAttachedSurfaceLayer())+
", windowHandle "+toHexString(getWindowHandle())+
", surfaceHandle "+toHexString(getSurfaceHandle())+
", bounds "+bounds+", insets "+insets
);
sb.append(", pos "+getX()+"/"+getY()+", size "+getWidth()+"x"+getHeight()+
", visible "+component.isVisible());
sb.append(", lockedExt "+isSurfaceLockedByOtherThread()+
",\n\tconfig "+config+
",\n\tawtComponent "+getAWTComponent()+
",\n\tsurfaceLock "+surfaceLock+"]");
return sb.toString();
}
protected final String toHexString(long l) {
return "0x"+Long.toHexString(l);
}
}
| false | false | null | null |
diff --git a/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java b/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java
index e99e956e2..38025e8e4 100644
--- a/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java
+++ b/java/src/com/android/inputmethod/keyboard/KeyboardSwitcher.java
@@ -1,407 +1,409 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.android.inputmethod.keyboard;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import com.android.inputmethod.accessibility.AccessibleKeyboardViewProxy;
import com.android.inputmethod.keyboard.KeyboardLayoutSet.KeyboardLayoutSetException;
import com.android.inputmethod.keyboard.PointerTracker.TimerProxy;
import com.android.inputmethod.keyboard.internal.KeyboardState;
import com.android.inputmethod.latin.DebugSettings;
import com.android.inputmethod.latin.ImfUtils;
import com.android.inputmethod.latin.InputView;
import com.android.inputmethod.latin.LatinIME;
import com.android.inputmethod.latin.LatinImeLogger;
import com.android.inputmethod.latin.R;
import com.android.inputmethod.latin.SettingsValues;
import com.android.inputmethod.latin.SubtypeSwitcher;
import com.android.inputmethod.latin.WordComposer;
public final class KeyboardSwitcher implements KeyboardState.SwitchActions {
private static final String TAG = KeyboardSwitcher.class.getSimpleName();
public static final String PREF_KEYBOARD_LAYOUT = "pref_keyboard_layout_20110916";
static final class KeyboardTheme {
public final int mThemeId;
public final int mStyleId;
// Note: The themeId should be aligned with "themeId" attribute of Keyboard style
// in values/style.xml.
public KeyboardTheme(int themeId, int styleId) {
mThemeId = themeId;
mStyleId = styleId;
}
}
private static final KeyboardTheme[] KEYBOARD_THEMES = {
new KeyboardTheme(0, R.style.KeyboardTheme),
new KeyboardTheme(1, R.style.KeyboardTheme_HighContrast),
new KeyboardTheme(6, R.style.KeyboardTheme_Stone),
new KeyboardTheme(7, R.style.KeyboardTheme_Stone_Bold),
new KeyboardTheme(8, R.style.KeyboardTheme_Gingerbread),
new KeyboardTheme(5, R.style.KeyboardTheme_IceCreamSandwich),
};
private SubtypeSwitcher mSubtypeSwitcher;
private SharedPreferences mPrefs;
private boolean mForceNonDistinctMultitouch;
private InputView mCurrentInputView;
private MainKeyboardView mKeyboardView;
private LatinIME mLatinIME;
private Resources mResources;
private KeyboardState mState;
private KeyboardLayoutSet mKeyboardLayoutSet;
/** mIsAutoCorrectionActive indicates that auto corrected word will be input instead of
* what user actually typed. */
private boolean mIsAutoCorrectionActive;
private KeyboardTheme mKeyboardTheme = KEYBOARD_THEMES[0];
private Context mThemeContext;
private static final KeyboardSwitcher sInstance = new KeyboardSwitcher();
public static KeyboardSwitcher getInstance() {
return sInstance;
}
private KeyboardSwitcher() {
// Intentional empty constructor for singleton.
}
public static void init(LatinIME latinIme, SharedPreferences prefs) {
sInstance.initInternal(latinIme, prefs);
}
private void initInternal(LatinIME latinIme, SharedPreferences prefs) {
mLatinIME = latinIme;
mResources = latinIme.getResources();
mPrefs = prefs;
mSubtypeSwitcher = SubtypeSwitcher.getInstance();
mState = new KeyboardState(this);
setContextThemeWrapper(latinIme, getKeyboardTheme(latinIme, prefs));
mForceNonDistinctMultitouch = prefs.getBoolean(
DebugSettings.FORCE_NON_DISTINCT_MULTITOUCH_KEY, false);
}
private static KeyboardTheme getKeyboardTheme(Context context, SharedPreferences prefs) {
final String defaultIndex = context.getString(R.string.config_default_keyboard_theme_index);
final String themeIndex = prefs.getString(PREF_KEYBOARD_LAYOUT, defaultIndex);
try {
final int index = Integer.valueOf(themeIndex);
if (index >= 0 && index < KEYBOARD_THEMES.length) {
return KEYBOARD_THEMES[index];
}
} catch (NumberFormatException e) {
// Format error, keyboard theme is default to 0.
}
Log.w(TAG, "Illegal keyboard theme in preference: " + themeIndex + ", default to 0");
return KEYBOARD_THEMES[0];
}
private void setContextThemeWrapper(Context context, KeyboardTheme keyboardTheme) {
if (mKeyboardTheme.mThemeId != keyboardTheme.mThemeId) {
mKeyboardTheme = keyboardTheme;
mThemeContext = new ContextThemeWrapper(context, keyboardTheme.mStyleId);
KeyboardLayoutSet.clearKeyboardCache();
}
}
public void loadKeyboard(EditorInfo editorInfo, SettingsValues settingsValues) {
final KeyboardLayoutSet.Builder builder = new KeyboardLayoutSet.Builder(
mThemeContext, editorInfo);
final Resources res = mThemeContext.getResources();
builder.setScreenGeometry(res.getInteger(R.integer.config_device_form_factor),
res.getConfiguration().orientation, res.getDisplayMetrics().widthPixels);
builder.setSubtype(mSubtypeSwitcher.getCurrentSubtype());
builder.setOptions(
settingsValues.isVoiceKeyEnabled(editorInfo),
settingsValues.isVoiceKeyOnMain(),
settingsValues.isLanguageSwitchKeyEnabled(mThemeContext));
mKeyboardLayoutSet = builder.build();
try {
mState.onLoadKeyboard(mResources.getString(R.string.layout_switch_back_symbols));
} catch (KeyboardLayoutSetException e) {
Log.w(TAG, "loading keyboard failed: " + e.mKeyboardId, e.getCause());
LatinImeLogger.logOnException(e.mKeyboardId.toString(), e.getCause());
return;
}
}
public void saveKeyboardState() {
if (getKeyboard() != null) {
mState.onSaveKeyboardState();
}
}
public void onFinishInputView() {
mIsAutoCorrectionActive = false;
}
public void onHideWindow() {
mIsAutoCorrectionActive = false;
}
private void setKeyboard(final Keyboard keyboard) {
final MainKeyboardView keyboardView = mKeyboardView;
final Keyboard oldKeyboard = keyboardView.getKeyboard();
keyboardView.setKeyboard(keyboard);
mCurrentInputView.setKeyboardGeometry(keyboard.mTopPadding);
keyboardView.setKeyPreviewPopupEnabled(
SettingsValues.isKeyPreviewPopupEnabled(mPrefs, mResources),
SettingsValues.getKeyPreviewPopupDismissDelay(mPrefs, mResources));
keyboardView.updateAutoCorrectionState(mIsAutoCorrectionActive);
keyboardView.updateShortcutKey(mSubtypeSwitcher.isShortcutImeReady());
final boolean subtypeChanged = (oldKeyboard == null)
|| !keyboard.mId.mLocale.equals(oldKeyboard.mId.mLocale);
final boolean needsToDisplayLanguage = mSubtypeSwitcher.needsToDisplayLanguage(
keyboard.mId.mLocale);
keyboardView.startDisplayLanguageOnSpacebar(subtypeChanged, needsToDisplayLanguage,
ImfUtils.hasMultipleEnabledIMEsOrSubtypes(mLatinIME, true));
}
public Keyboard getKeyboard() {
if (mKeyboardView != null) {
return mKeyboardView.getKeyboard();
}
return null;
}
/**
* Update keyboard shift state triggered by connected EditText status change.
*/
public void updateShiftState() {
mState.onUpdateShiftState(mLatinIME.getCurrentAutoCapsState());
}
public void onPressKey(int code) {
if (isVibrateAndSoundFeedbackRequired()) {
mLatinIME.hapticAndAudioFeedback(code);
}
mState.onPressKey(code, isSinglePointer(), mLatinIME.getCurrentAutoCapsState());
}
public void onReleaseKey(int code, boolean withSliding) {
mState.onReleaseKey(code, withSliding);
}
public void onCancelInput() {
mState.onCancelInput(isSinglePointer());
}
// Implements {@link KeyboardState.SwitchActions}.
@Override
public void setAlphabetKeyboard() {
setKeyboard(mKeyboardLayoutSet.getKeyboard(KeyboardId.ELEMENT_ALPHABET));
}
// Implements {@link KeyboardState.SwitchActions}.
@Override
public void setAlphabetManualShiftedKeyboard() {
setKeyboard(mKeyboardLayoutSet.getKeyboard(KeyboardId.ELEMENT_ALPHABET_MANUAL_SHIFTED));
}
// Implements {@link KeyboardState.SwitchActions}.
@Override
public void setAlphabetAutomaticShiftedKeyboard() {
setKeyboard(mKeyboardLayoutSet.getKeyboard(KeyboardId.ELEMENT_ALPHABET_AUTOMATIC_SHIFTED));
}
// Implements {@link KeyboardState.SwitchActions}.
@Override
public void setAlphabetShiftLockedKeyboard() {
setKeyboard(mKeyboardLayoutSet.getKeyboard(KeyboardId.ELEMENT_ALPHABET_SHIFT_LOCKED));
}
// Implements {@link KeyboardState.SwitchActions}.
@Override
public void setAlphabetShiftLockShiftedKeyboard() {
setKeyboard(mKeyboardLayoutSet.getKeyboard(KeyboardId.ELEMENT_ALPHABET_SHIFT_LOCK_SHIFTED));
}
// Implements {@link KeyboardState.SwitchActions}.
@Override
public void setSymbolsKeyboard() {
setKeyboard(mKeyboardLayoutSet.getKeyboard(KeyboardId.ELEMENT_SYMBOLS));
}
// Implements {@link KeyboardState.SwitchActions}.
@Override
public void setSymbolsShiftedKeyboard() {
setKeyboard(mKeyboardLayoutSet.getKeyboard(KeyboardId.ELEMENT_SYMBOLS_SHIFTED));
}
// Implements {@link KeyboardState.SwitchActions}.
@Override
public void requestUpdatingShiftState() {
mState.onUpdateShiftState(mLatinIME.getCurrentAutoCapsState());
}
// Implements {@link KeyboardState.SwitchActions}.
@Override
public void startDoubleTapTimer() {
final MainKeyboardView keyboardView = getMainKeyboardView();
if (keyboardView != null) {
final TimerProxy timer = keyboardView.getTimerProxy();
timer.startDoubleTapTimer();
}
}
// Implements {@link KeyboardState.SwitchActions}.
@Override
public void cancelDoubleTapTimer() {
final MainKeyboardView keyboardView = getMainKeyboardView();
if (keyboardView != null) {
final TimerProxy timer = keyboardView.getTimerProxy();
timer.cancelDoubleTapTimer();
}
}
// Implements {@link KeyboardState.SwitchActions}.
@Override
public boolean isInDoubleTapTimeout() {
final MainKeyboardView keyboardView = getMainKeyboardView();
return (keyboardView != null)
? keyboardView.getTimerProxy().isInDoubleTapTimeout() : false;
}
// Implements {@link KeyboardState.SwitchActions}.
@Override
public void startLongPressTimer(int code) {
final MainKeyboardView keyboardView = getMainKeyboardView();
if (keyboardView != null) {
final TimerProxy timer = keyboardView.getTimerProxy();
timer.startLongPressTimer(code);
}
}
// Implements {@link KeyboardState.SwitchActions}.
@Override
public void cancelLongPressTimer() {
final MainKeyboardView keyboardView = getMainKeyboardView();
if (keyboardView != null) {
final TimerProxy timer = keyboardView.getTimerProxy();
timer.cancelLongPressTimer();
}
}
// Implements {@link KeyboardState.SwitchActions}.
@Override
public void hapticAndAudioFeedback(int code) {
mLatinIME.hapticAndAudioFeedback(code);
}
public void onLongPressTimeout(int code) {
mState.onLongPressTimeout(code);
}
public boolean isInMomentarySwitchState() {
return mState.isInMomentarySwitchState();
}
private boolean isVibrateAndSoundFeedbackRequired() {
return mKeyboardView != null && !mKeyboardView.isInSlidingKeyInput();
}
private boolean isSinglePointer() {
return mKeyboardView != null && mKeyboardView.getPointerCount() == 1;
}
public boolean hasDistinctMultitouch() {
return mKeyboardView != null && mKeyboardView.hasDistinctMultitouch();
}
/**
* Updates state machine to figure out when to automatically switch back to the previous mode.
*/
public void onCodeInput(int code) {
mState.onCodeInput(code, isSinglePointer(), mLatinIME.getCurrentAutoCapsState());
}
public MainKeyboardView getMainKeyboardView() {
return mKeyboardView;
}
public View onCreateInputView(boolean isHardwareAcceleratedDrawingEnabled) {
if (mKeyboardView != null) {
mKeyboardView.closing();
}
setContextThemeWrapper(mLatinIME, mKeyboardTheme);
mCurrentInputView = (InputView)LayoutInflater.from(mThemeContext).inflate(
R.layout.input_view, null);
mKeyboardView = (MainKeyboardView) mCurrentInputView.findViewById(R.id.keyboard_view);
if (isHardwareAcceleratedDrawingEnabled) {
mKeyboardView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
// TODO: Should use LAYER_TYPE_SOFTWARE when hardware acceleration is off?
}
mKeyboardView.setKeyboardActionListener(mLatinIME);
if (mForceNonDistinctMultitouch) {
mKeyboardView.setDistinctMultitouch(false);
}
// This always needs to be set since the accessibility state can
// potentially change without the input view being re-created.
AccessibleKeyboardViewProxy.getInstance().setView(mKeyboardView);
return mCurrentInputView;
}
public void onNetworkStateChanged() {
if (mKeyboardView != null) {
mKeyboardView.updateShortcutKey(mSubtypeSwitcher.isShortcutImeReady());
}
}
public void onAutoCorrectionStateChanged(boolean isAutoCorrection) {
if (mIsAutoCorrectionActive != isAutoCorrection) {
mIsAutoCorrectionActive = isAutoCorrection;
if (mKeyboardView != null) {
mKeyboardView.updateAutoCorrectionState(isAutoCorrection);
}
}
}
- public int getManualCapsMode() {
+ public int getKeyboardShiftMode() {
final Keyboard keyboard = getKeyboard();
if (keyboard == null) {
return WordComposer.CAPS_MODE_OFF;
}
switch (keyboard.mId.mElementId) {
case KeyboardId.ELEMENT_ALPHABET_SHIFT_LOCKED:
case KeyboardId.ELEMENT_ALPHABET_SHIFT_LOCK_SHIFTED:
return WordComposer.CAPS_MODE_MANUAL_SHIFT_LOCKED;
case KeyboardId.ELEMENT_ALPHABET_MANUAL_SHIFTED:
return WordComposer.CAPS_MODE_MANUAL_SHIFTED;
+ case KeyboardId.ELEMENT_ALPHABET_AUTOMATIC_SHIFTED:
+ return WordComposer.CAPS_MODE_AUTO_SHIFTED;
default:
return WordComposer.CAPS_MODE_OFF;
}
}
}
diff --git a/java/src/com/android/inputmethod/latin/LatinIME.java b/java/src/com/android/inputmethod/latin/LatinIME.java
index d98966e96..cd20ba3a3 100644
--- a/java/src/com/android/inputmethod/latin/LatinIME.java
+++ b/java/src/com/android/inputmethod/latin/LatinIME.java
@@ -1,2414 +1,2414 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.android.inputmethod.latin;
import static com.android.inputmethod.latin.Constants.ImeOption.FORCE_ASCII;
import static com.android.inputmethod.latin.Constants.ImeOption.NO_MICROPHONE;
import static com.android.inputmethod.latin.Constants.ImeOption.NO_MICROPHONE_COMPAT;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Rect;
import android.inputmethodservice.InputMethodService;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.os.Debug;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.util.PrintWriterPrinter;
import android.util.Printer;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.CompletionInfo;
import android.view.inputmethod.CorrectionInfo;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodSubtype;
import com.android.inputmethod.accessibility.AccessibilityUtils;
import com.android.inputmethod.accessibility.AccessibleKeyboardViewProxy;
import com.android.inputmethod.compat.CompatUtils;
import com.android.inputmethod.compat.InputMethodManagerCompatWrapper;
import com.android.inputmethod.compat.InputMethodServiceCompatUtils;
import com.android.inputmethod.compat.SuggestionSpanUtils;
import com.android.inputmethod.keyboard.KeyDetector;
import com.android.inputmethod.keyboard.Keyboard;
import com.android.inputmethod.keyboard.KeyboardActionListener;
import com.android.inputmethod.keyboard.KeyboardId;
import com.android.inputmethod.keyboard.KeyboardSwitcher;
import com.android.inputmethod.keyboard.KeyboardView;
import com.android.inputmethod.keyboard.MainKeyboardView;
import com.android.inputmethod.latin.LocaleUtils.RunInLocale;
import com.android.inputmethod.latin.Utils.Stats;
import com.android.inputmethod.latin.define.ProductionFlag;
import com.android.inputmethod.latin.suggestions.SuggestionStripView;
import com.android.inputmethod.research.ResearchLogger;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Locale;
/**
* Input method implementation for Qwerty'ish keyboard.
*/
public final class LatinIME extends InputMethodService implements KeyboardActionListener,
SuggestionStripView.Listener, TargetApplicationGetter.OnTargetApplicationKnownListener,
Suggest.SuggestInitializationListener {
private static final String TAG = LatinIME.class.getSimpleName();
private static final boolean TRACE = false;
private static boolean DEBUG;
private static final int EXTENDED_TOUCHABLE_REGION_HEIGHT = 100;
// How many continuous deletes at which to start deleting at a higher speed.
private static final int DELETE_ACCELERATE_AT = 20;
// Key events coming any faster than this are long-presses.
private static final int QUICK_PRESS = 200;
private static final int PENDING_IMS_CALLBACK_DURATION = 800;
/**
* The name of the scheme used by the Package Manager to warn of a new package installation,
* replacement or removal.
*/
private static final String SCHEME_PACKAGE = "package";
private static final int SPACE_STATE_NONE = 0;
// Double space: the state where the user pressed space twice quickly, which LatinIME
// resolved as period-space. Undoing this converts the period to a space.
private static final int SPACE_STATE_DOUBLE = 1;
// Swap punctuation: the state where a weak space and a punctuation from the suggestion strip
// have just been swapped. Undoing this swaps them back; the space is still considered weak.
private static final int SPACE_STATE_SWAP_PUNCTUATION = 2;
// Weak space: a space that should be swapped only by suggestion strip punctuation. Weak
// spaces happen when the user presses space, accepting the current suggestion (whether
// it's an auto-correction or not).
private static final int SPACE_STATE_WEAK = 3;
// Phantom space: a not-yet-inserted space that should get inserted on the next input,
// character provided it's not a separator. If it's a separator, the phantom space is dropped.
// Phantom spaces happen when a user chooses a word from the suggestion strip.
private static final int SPACE_STATE_PHANTOM = 4;
// Current space state of the input method. This can be any of the above constants.
private int mSpaceState;
private SettingsValues mCurrentSettings;
private View mExtractArea;
private View mKeyPreviewBackingView;
private View mSuggestionsContainer;
private SuggestionStripView mSuggestionStripView;
/* package for tests */ Suggest mSuggest;
private CompletionInfo[] mApplicationSpecifiedCompletions;
private ApplicationInfo mTargetApplicationInfo;
private InputMethodManagerCompatWrapper mImm;
private Resources mResources;
private SharedPreferences mPrefs;
/* package for tests */ final KeyboardSwitcher mKeyboardSwitcher;
private final SubtypeSwitcher mSubtypeSwitcher;
private boolean mShouldSwitchToLastSubtype = true;
private boolean mIsMainDictionaryAvailable;
private UserBinaryDictionary mUserDictionary;
private UserHistoryDictionary mUserHistoryDictionary;
private boolean mIsUserDictionaryAvailable;
private LastComposedWord mLastComposedWord = LastComposedWord.NOT_A_COMPOSED_WORD;
private final WordComposer mWordComposer = new WordComposer();
private RichInputConnection mConnection = new RichInputConnection(this);
// Keep track of the last selection range to decide if we need to show word alternatives
private static final int NOT_A_CURSOR_POSITION = -1;
private int mLastSelectionStart = NOT_A_CURSOR_POSITION;
private int mLastSelectionEnd = NOT_A_CURSOR_POSITION;
// Whether we are expecting an onUpdateSelection event to fire. If it does when we don't
// "expect" it, it means the user actually moved the cursor.
private boolean mExpectingUpdateSelection;
private int mDeleteCount;
private long mLastKeyTime;
private AudioAndHapticFeedbackManager mFeedbackManager;
// Member variables for remembering the current device orientation.
private int mDisplayOrientation;
// Object for reacting to adding/removing a dictionary pack.
private BroadcastReceiver mDictionaryPackInstallReceiver =
new DictionaryPackInstallBroadcastReceiver(this);
// Keeps track of most recently inserted text (multi-character key) for reverting
private CharSequence mEnteredText;
private boolean mIsAutoCorrectionIndicatorOn;
private AlertDialog mOptionsDialog;
private final boolean mIsHardwareAcceleratedDrawingEnabled;
public final UIHandler mHandler = new UIHandler(this);
public static final class UIHandler extends StaticInnerHandlerWrapper<LatinIME> {
private static final int MSG_UPDATE_SHIFT_STATE = 0;
private static final int MSG_PENDING_IMS_CALLBACK = 1;
private static final int MSG_UPDATE_SUGGESTION_STRIP = 2;
private static final int MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP = 3;
private static final int ARG1_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT = 1;
private int mDelayUpdateSuggestions;
private int mDelayUpdateShiftState;
private long mDoubleSpacesTurnIntoPeriodTimeout;
private long mDoubleSpaceTimerStart;
public UIHandler(final LatinIME outerInstance) {
super(outerInstance);
}
public void onCreate() {
final Resources res = getOuterInstance().getResources();
mDelayUpdateSuggestions =
res.getInteger(R.integer.config_delay_update_suggestions);
mDelayUpdateShiftState =
res.getInteger(R.integer.config_delay_update_shift_state);
mDoubleSpacesTurnIntoPeriodTimeout = res.getInteger(
R.integer.config_double_spaces_turn_into_period_timeout);
}
@Override
public void handleMessage(final Message msg) {
final LatinIME latinIme = getOuterInstance();
final KeyboardSwitcher switcher = latinIme.mKeyboardSwitcher;
switch (msg.what) {
case MSG_UPDATE_SUGGESTION_STRIP:
latinIme.updateSuggestionStrip();
break;
case MSG_UPDATE_SHIFT_STATE:
switcher.updateShiftState();
break;
case MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP:
latinIme.showGesturePreviewAndSuggestionStrip((SuggestedWords)msg.obj,
msg.arg1 == ARG1_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT);
break;
}
}
public void postUpdateSuggestionStrip() {
sendMessageDelayed(obtainMessage(MSG_UPDATE_SUGGESTION_STRIP), mDelayUpdateSuggestions);
}
public void cancelUpdateSuggestionStrip() {
removeMessages(MSG_UPDATE_SUGGESTION_STRIP);
}
public boolean hasPendingUpdateSuggestions() {
return hasMessages(MSG_UPDATE_SUGGESTION_STRIP);
}
public void postUpdateShiftState() {
removeMessages(MSG_UPDATE_SHIFT_STATE);
sendMessageDelayed(obtainMessage(MSG_UPDATE_SHIFT_STATE), mDelayUpdateShiftState);
}
public void cancelUpdateShiftState() {
removeMessages(MSG_UPDATE_SHIFT_STATE);
}
public void showGesturePreviewAndSuggestionStrip(final SuggestedWords suggestedWords,
final boolean dismissGestureFloatingPreviewText) {
removeMessages(MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP);
final int arg1 = dismissGestureFloatingPreviewText
? ARG1_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT : 0;
obtainMessage(MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP, arg1, 0, suggestedWords)
.sendToTarget();
}
public void startDoubleSpacesTimer() {
mDoubleSpaceTimerStart = SystemClock.uptimeMillis();
}
public void cancelDoubleSpacesTimer() {
mDoubleSpaceTimerStart = 0;
}
public boolean isAcceptingDoubleSpaces() {
return SystemClock.uptimeMillis() - mDoubleSpaceTimerStart
< mDoubleSpacesTurnIntoPeriodTimeout;
}
// Working variables for the following methods.
private boolean mIsOrientationChanging;
private boolean mPendingSuccessiveImsCallback;
private boolean mHasPendingStartInput;
private boolean mHasPendingFinishInputView;
private boolean mHasPendingFinishInput;
private EditorInfo mAppliedEditorInfo;
public void startOrientationChanging() {
removeMessages(MSG_PENDING_IMS_CALLBACK);
resetPendingImsCallback();
mIsOrientationChanging = true;
final LatinIME latinIme = getOuterInstance();
if (latinIme.isInputViewShown()) {
latinIme.mKeyboardSwitcher.saveKeyboardState();
}
}
private void resetPendingImsCallback() {
mHasPendingFinishInputView = false;
mHasPendingFinishInput = false;
mHasPendingStartInput = false;
}
private void executePendingImsCallback(final LatinIME latinIme, final EditorInfo editorInfo,
boolean restarting) {
if (mHasPendingFinishInputView)
latinIme.onFinishInputViewInternal(mHasPendingFinishInput);
if (mHasPendingFinishInput)
latinIme.onFinishInputInternal();
if (mHasPendingStartInput)
latinIme.onStartInputInternal(editorInfo, restarting);
resetPendingImsCallback();
}
public void onStartInput(final EditorInfo editorInfo, final boolean restarting) {
if (hasMessages(MSG_PENDING_IMS_CALLBACK)) {
// Typically this is the second onStartInput after orientation changed.
mHasPendingStartInput = true;
} else {
if (mIsOrientationChanging && restarting) {
// This is the first onStartInput after orientation changed.
mIsOrientationChanging = false;
mPendingSuccessiveImsCallback = true;
}
final LatinIME latinIme = getOuterInstance();
executePendingImsCallback(latinIme, editorInfo, restarting);
latinIme.onStartInputInternal(editorInfo, restarting);
}
}
public void onStartInputView(final EditorInfo editorInfo, final boolean restarting) {
if (hasMessages(MSG_PENDING_IMS_CALLBACK)
&& KeyboardId.equivalentEditorInfoForKeyboard(editorInfo, mAppliedEditorInfo)) {
// Typically this is the second onStartInputView after orientation changed.
resetPendingImsCallback();
} else {
if (mPendingSuccessiveImsCallback) {
// This is the first onStartInputView after orientation changed.
mPendingSuccessiveImsCallback = false;
resetPendingImsCallback();
sendMessageDelayed(obtainMessage(MSG_PENDING_IMS_CALLBACK),
PENDING_IMS_CALLBACK_DURATION);
}
final LatinIME latinIme = getOuterInstance();
executePendingImsCallback(latinIme, editorInfo, restarting);
latinIme.onStartInputViewInternal(editorInfo, restarting);
mAppliedEditorInfo = editorInfo;
}
}
public void onFinishInputView(final boolean finishingInput) {
if (hasMessages(MSG_PENDING_IMS_CALLBACK)) {
// Typically this is the first onFinishInputView after orientation changed.
mHasPendingFinishInputView = true;
} else {
final LatinIME latinIme = getOuterInstance();
latinIme.onFinishInputViewInternal(finishingInput);
mAppliedEditorInfo = null;
}
}
public void onFinishInput() {
if (hasMessages(MSG_PENDING_IMS_CALLBACK)) {
// Typically this is the first onFinishInput after orientation changed.
mHasPendingFinishInput = true;
} else {
final LatinIME latinIme = getOuterInstance();
executePendingImsCallback(latinIme, null, false);
latinIme.onFinishInputInternal();
}
}
}
public LatinIME() {
super();
mSubtypeSwitcher = SubtypeSwitcher.getInstance();
mKeyboardSwitcher = KeyboardSwitcher.getInstance();
mIsHardwareAcceleratedDrawingEnabled =
InputMethodServiceCompatUtils.enableHardwareAcceleration(this);
Log.i(TAG, "Hardware accelerated drawing: " + mIsHardwareAcceleratedDrawingEnabled);
}
@Override
public void onCreate() {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
mPrefs = prefs;
LatinImeLogger.init(this, prefs);
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.getInstance().init(this, prefs);
}
InputMethodManagerCompatWrapper.init(this);
SubtypeSwitcher.init(this);
KeyboardSwitcher.init(this, prefs);
AccessibilityUtils.init(this);
super.onCreate();
mImm = InputMethodManagerCompatWrapper.getInstance();
mHandler.onCreate();
DEBUG = LatinImeLogger.sDBG;
final Resources res = getResources();
mResources = res;
loadSettings();
ImfUtils.setAdditionalInputMethodSubtypes(this, mCurrentSettings.getAdditionalSubtypes());
initSuggest();
mDisplayOrientation = res.getConfiguration().orientation;
// Register to receive ringer mode change and network state change.
// Also receive installation and removal of a dictionary pack.
final IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
filter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION);
registerReceiver(mReceiver, filter);
final IntentFilter packageFilter = new IntentFilter();
packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
packageFilter.addDataScheme(SCHEME_PACKAGE);
registerReceiver(mDictionaryPackInstallReceiver, packageFilter);
final IntentFilter newDictFilter = new IntentFilter();
newDictFilter.addAction(
DictionaryPackInstallBroadcastReceiver.NEW_DICTIONARY_INTENT_ACTION);
registerReceiver(mDictionaryPackInstallReceiver, newDictFilter);
}
// Has to be package-visible for unit tests
/* package for test */
void loadSettings() {
// Note that the calling sequence of onCreate() and onCurrentInputMethodSubtypeChanged()
// is not guaranteed. It may even be called at the same time on a different thread.
if (null == mPrefs) mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
final InputAttributes inputAttributes =
new InputAttributes(getCurrentInputEditorInfo(), isFullscreenMode());
final RunInLocale<SettingsValues> job = new RunInLocale<SettingsValues>() {
@Override
protected SettingsValues job(Resources res) {
return new SettingsValues(mPrefs, inputAttributes, LatinIME.this);
}
};
mCurrentSettings = job.runInLocale(mResources, mSubtypeSwitcher.getCurrentSubtypeLocale());
mFeedbackManager = new AudioAndHapticFeedbackManager(this, mCurrentSettings);
resetContactsDictionary(null == mSuggest ? null : mSuggest.getContactsDictionary());
}
// Note that this method is called from a non-UI thread.
@Override
public void onUpdateMainDictionaryAvailability(final boolean isMainDictionaryAvailable) {
mIsMainDictionaryAvailable = isMainDictionaryAvailable;
final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
if (mainKeyboardView != null) {
mainKeyboardView.setMainDictionaryAvailability(isMainDictionaryAvailable);
}
}
private void initSuggest() {
final Locale subtypeLocale = mSubtypeSwitcher.getCurrentSubtypeLocale();
final String localeStr = subtypeLocale.toString();
final ContactsBinaryDictionary oldContactsDictionary;
if (mSuggest != null) {
oldContactsDictionary = mSuggest.getContactsDictionary();
mSuggest.close();
} else {
oldContactsDictionary = null;
}
mSuggest = new Suggest(this /* Context */, subtypeLocale,
this /* SuggestInitializationListener */);
if (mCurrentSettings.mCorrectionEnabled) {
mSuggest.setAutoCorrectionThreshold(mCurrentSettings.mAutoCorrectionThreshold);
}
mIsMainDictionaryAvailable = DictionaryFactory.isDictionaryAvailable(this, subtypeLocale);
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.getInstance().initSuggest(mSuggest);
}
mUserDictionary = new UserBinaryDictionary(this, localeStr);
mIsUserDictionaryAvailable = mUserDictionary.isEnabled();
mSuggest.setUserDictionary(mUserDictionary);
resetContactsDictionary(oldContactsDictionary);
// Note that the calling sequence of onCreate() and onCurrentInputMethodSubtypeChanged()
// is not guaranteed. It may even be called at the same time on a different thread.
if (null == mPrefs) mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
mUserHistoryDictionary = UserHistoryDictionary.getInstance(this, localeStr, mPrefs);
mSuggest.setUserHistoryDictionary(mUserHistoryDictionary);
}
/**
* Resets the contacts dictionary in mSuggest according to the user settings.
*
* This method takes an optional contacts dictionary to use when the locale hasn't changed
* since the contacts dictionary can be opened or closed as necessary depending on the settings.
*
* @param oldContactsDictionary an optional dictionary to use, or null
*/
private void resetContactsDictionary(final ContactsBinaryDictionary oldContactsDictionary) {
final boolean shouldSetDictionary = (null != mSuggest && mCurrentSettings.mUseContactsDict);
final ContactsBinaryDictionary dictionaryToUse;
if (!shouldSetDictionary) {
// Make sure the dictionary is closed. If it is already closed, this is a no-op,
// so it's safe to call it anyways.
if (null != oldContactsDictionary) oldContactsDictionary.close();
dictionaryToUse = null;
} else {
final Locale locale = mSubtypeSwitcher.getCurrentSubtypeLocale();
if (null != oldContactsDictionary) {
if (!oldContactsDictionary.mLocale.equals(locale)) {
// If the locale has changed then recreate the contacts dictionary. This
// allows locale dependent rules for handling bigram name predictions.
oldContactsDictionary.close();
dictionaryToUse = new ContactsBinaryDictionary(this, locale);
} else {
// Make sure the old contacts dictionary is opened. If it is already open,
// this is a no-op, so it's safe to call it anyways.
oldContactsDictionary.reopen(this);
dictionaryToUse = oldContactsDictionary;
}
} else {
dictionaryToUse = new ContactsBinaryDictionary(this, locale);
}
}
if (null != mSuggest) {
mSuggest.setContactsDictionary(dictionaryToUse);
}
}
/* package private */ void resetSuggestMainDict() {
final Locale subtypeLocale = mSubtypeSwitcher.getCurrentSubtypeLocale();
mSuggest.resetMainDict(this, subtypeLocale, this /* SuggestInitializationListener */);
mIsMainDictionaryAvailable = DictionaryFactory.isDictionaryAvailable(this, subtypeLocale);
}
@Override
public void onDestroy() {
if (mSuggest != null) {
mSuggest.close();
mSuggest = null;
}
unregisterReceiver(mReceiver);
unregisterReceiver(mDictionaryPackInstallReceiver);
LatinImeLogger.commit();
LatinImeLogger.onDestroy();
super.onDestroy();
}
@Override
public void onConfigurationChanged(final Configuration conf) {
// System locale has been changed. Needs to reload keyboard.
if (mSubtypeSwitcher.onConfigurationChanged(conf, this)) {
loadKeyboard();
}
// If orientation changed while predicting, commit the change
if (mDisplayOrientation != conf.orientation) {
mDisplayOrientation = conf.orientation;
mHandler.startOrientationChanging();
mConnection.beginBatchEdit();
commitTyped(LastComposedWord.NOT_A_SEPARATOR);
mConnection.finishComposingText();
mConnection.endBatchEdit();
if (isShowingOptionDialog()) {
mOptionsDialog.dismiss();
}
}
super.onConfigurationChanged(conf);
}
@Override
public View onCreateInputView() {
return mKeyboardSwitcher.onCreateInputView(mIsHardwareAcceleratedDrawingEnabled);
}
@Override
public void setInputView(final View view) {
super.setInputView(view);
mExtractArea = getWindow().getWindow().getDecorView()
.findViewById(android.R.id.extractArea);
mKeyPreviewBackingView = view.findViewById(R.id.key_preview_backing);
mSuggestionsContainer = view.findViewById(R.id.suggestions_container);
mSuggestionStripView = (SuggestionStripView)view.findViewById(R.id.suggestion_strip_view);
if (mSuggestionStripView != null)
mSuggestionStripView.setListener(this, view);
if (LatinImeLogger.sVISUALDEBUG) {
mKeyPreviewBackingView.setBackgroundColor(0x10FF0000);
}
}
@Override
public void setCandidatesView(final View view) {
// To ensure that CandidatesView will never be set.
return;
}
@Override
public void onStartInput(final EditorInfo editorInfo, final boolean restarting) {
mHandler.onStartInput(editorInfo, restarting);
}
@Override
public void onStartInputView(final EditorInfo editorInfo, final boolean restarting) {
mHandler.onStartInputView(editorInfo, restarting);
}
@Override
public void onFinishInputView(final boolean finishingInput) {
mHandler.onFinishInputView(finishingInput);
}
@Override
public void onFinishInput() {
mHandler.onFinishInput();
}
@Override
public void onCurrentInputMethodSubtypeChanged(final InputMethodSubtype subtype) {
// Note that the calling sequence of onCreate() and onCurrentInputMethodSubtypeChanged()
// is not guaranteed. It may even be called at the same time on a different thread.
mSubtypeSwitcher.updateSubtype(subtype);
loadKeyboard();
}
private void onStartInputInternal(final EditorInfo editorInfo, final boolean restarting) {
super.onStartInput(editorInfo, restarting);
}
@SuppressWarnings("deprecation")
private void onStartInputViewInternal(final EditorInfo editorInfo, final boolean restarting) {
super.onStartInputView(editorInfo, restarting);
final KeyboardSwitcher switcher = mKeyboardSwitcher;
final MainKeyboardView mainKeyboardView = switcher.getMainKeyboardView();
if (editorInfo == null) {
Log.e(TAG, "Null EditorInfo in onStartInputView()");
if (LatinImeLogger.sDBG) {
throw new NullPointerException("Null EditorInfo in onStartInputView()");
}
return;
}
if (DEBUG) {
Log.d(TAG, "onStartInputView: editorInfo:"
+ String.format("inputType=0x%08x imeOptions=0x%08x",
editorInfo.inputType, editorInfo.imeOptions));
Log.d(TAG, "All caps = "
+ ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS) != 0)
+ ", sentence caps = "
+ ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_SENTENCES) != 0)
+ ", word caps = "
+ ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_WORDS) != 0));
}
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_onStartInputViewInternal(editorInfo, mPrefs);
}
if (InputAttributes.inPrivateImeOptions(null, NO_MICROPHONE_COMPAT, editorInfo)) {
Log.w(TAG, "Deprecated private IME option specified: "
+ editorInfo.privateImeOptions);
Log.w(TAG, "Use " + getPackageName() + "." + NO_MICROPHONE + " instead");
}
if (InputAttributes.inPrivateImeOptions(getPackageName(), FORCE_ASCII, editorInfo)) {
Log.w(TAG, "Deprecated private IME option specified: "
+ editorInfo.privateImeOptions);
Log.w(TAG, "Use EditorInfo.IME_FLAG_FORCE_ASCII flag instead");
}
mTargetApplicationInfo =
TargetApplicationGetter.getCachedApplicationInfo(editorInfo.packageName);
if (null == mTargetApplicationInfo) {
new TargetApplicationGetter(this /* context */, this /* listener */)
.execute(editorInfo.packageName);
}
LatinImeLogger.onStartInputView(editorInfo);
// In landscape mode, this method gets called without the input view being created.
if (mainKeyboardView == null) {
return;
}
// Forward this event to the accessibility utilities, if enabled.
final AccessibilityUtils accessUtils = AccessibilityUtils.getInstance();
if (accessUtils.isTouchExplorationEnabled()) {
accessUtils.onStartInputViewInternal(mainKeyboardView, editorInfo, restarting);
}
final boolean selectionChanged = mLastSelectionStart != editorInfo.initialSelStart
|| mLastSelectionEnd != editorInfo.initialSelEnd;
final boolean inputTypeChanged = !mCurrentSettings.isSameInputType(editorInfo);
final boolean isDifferentTextField = !restarting || inputTypeChanged;
if (isDifferentTextField) {
final boolean currentSubtypeEnabled = mSubtypeSwitcher
.updateParametersOnStartInputViewAndReturnIfCurrentSubtypeEnabled();
if (!currentSubtypeEnabled) {
// Current subtype is disabled. Needs to update subtype and keyboard.
final InputMethodSubtype newSubtype = ImfUtils.getCurrentInputMethodSubtype(
this, mSubtypeSwitcher.getNoLanguageSubtype());
mSubtypeSwitcher.updateSubtype(newSubtype);
loadKeyboard();
}
}
// The EditorInfo might have a flag that affects fullscreen mode.
// Note: This call should be done by InputMethodService?
updateFullscreenMode();
mApplicationSpecifiedCompletions = null;
if (isDifferentTextField || selectionChanged) {
// If the selection changed, we reset the input state. Essentially, we come here with
// restarting == true when the app called setText() or similar. We should reset the
// state if the app set the text to something else, but keep it if it set a suggestion
// or something.
mEnteredText = null;
resetComposingState(true /* alsoResetLastComposedWord */);
mDeleteCount = 0;
mSpaceState = SPACE_STATE_NONE;
if (mSuggestionStripView != null) {
// This will set the punctuation suggestions if next word suggestion is off;
// otherwise it will clear the suggestion strip.
setPunctuationSuggestions();
}
}
mConnection.resetCachesUponCursorMove(editorInfo.initialSelStart);
if (isDifferentTextField) {
mainKeyboardView.closing();
loadSettings();
if (mSuggest != null && mCurrentSettings.mCorrectionEnabled) {
mSuggest.setAutoCorrectionThreshold(mCurrentSettings.mAutoCorrectionThreshold);
}
switcher.loadKeyboard(editorInfo, mCurrentSettings);
}
setSuggestionStripShownInternal(
isSuggestionsStripVisible(), /* needsInputViewShown */ false);
mLastSelectionStart = editorInfo.initialSelStart;
mLastSelectionEnd = editorInfo.initialSelEnd;
// If we come here something in the text state is very likely to have changed.
// We should update the shift state regardless of whether we are restarting or not, because
// this is not perceived as a layout change that may be disruptive like we may have with
// switcher.loadKeyboard; in apps like Talk, we come here when the text is sent and the
// field gets emptied and we need to re-evaluate the shift state, but not the whole layout
// which would be disruptive.
// Space state must be updated before calling updateShiftState
mKeyboardSwitcher.updateShiftState();
mHandler.cancelUpdateSuggestionStrip();
mHandler.cancelDoubleSpacesTimer();
mainKeyboardView.setMainDictionaryAvailability(mIsMainDictionaryAvailable);
mainKeyboardView.setKeyPreviewPopupEnabled(mCurrentSettings.mKeyPreviewPopupOn,
mCurrentSettings.mKeyPreviewPopupDismissDelay);
mainKeyboardView.setGestureHandlingEnabledByUser(mCurrentSettings.mGestureInputEnabled);
mainKeyboardView.setGesturePreviewMode(mCurrentSettings.mGesturePreviewTrailEnabled,
mCurrentSettings.mGestureFloatingPreviewTextEnabled);
if (TRACE) Debug.startMethodTracing("/data/trace/latinime");
}
// Callback for the TargetApplicationGetter
@Override
public void onTargetApplicationKnown(final ApplicationInfo info) {
mTargetApplicationInfo = info;
}
@Override
public void onWindowHidden() {
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_onWindowHidden(mLastSelectionStart, mLastSelectionEnd,
getCurrentInputConnection());
}
super.onWindowHidden();
final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
if (mainKeyboardView != null) {
mainKeyboardView.closing();
}
}
private void onFinishInputInternal() {
super.onFinishInput();
LatinImeLogger.commit();
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.getInstance().latinIME_onFinishInputInternal();
}
final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
if (mainKeyboardView != null) {
mainKeyboardView.closing();
}
}
private void onFinishInputViewInternal(final boolean finishingInput) {
super.onFinishInputView(finishingInput);
mKeyboardSwitcher.onFinishInputView();
final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
if (mainKeyboardView != null) {
mainKeyboardView.cancelAllMessages();
}
// Remove pending messages related to update suggestions
mHandler.cancelUpdateSuggestionStrip();
}
@Override
public void onUpdateSelection(final int oldSelStart, final int oldSelEnd,
final int newSelStart, final int newSelEnd,
final int composingSpanStart, final int composingSpanEnd) {
super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd,
composingSpanStart, composingSpanEnd);
if (DEBUG) {
Log.i(TAG, "onUpdateSelection: oss=" + oldSelStart
+ ", ose=" + oldSelEnd
+ ", lss=" + mLastSelectionStart
+ ", lse=" + mLastSelectionEnd
+ ", nss=" + newSelStart
+ ", nse=" + newSelEnd
+ ", cs=" + composingSpanStart
+ ", ce=" + composingSpanEnd);
}
if (ProductionFlag.IS_EXPERIMENTAL) {
final boolean expectingUpdateSelectionFromLogger =
ResearchLogger.getAndClearLatinIMEExpectingUpdateSelection();
ResearchLogger.latinIME_onUpdateSelection(mLastSelectionStart, mLastSelectionEnd,
oldSelStart, oldSelEnd, newSelStart, newSelEnd, composingSpanStart,
composingSpanEnd, mExpectingUpdateSelection,
expectingUpdateSelectionFromLogger, mConnection);
if (expectingUpdateSelectionFromLogger) {
// TODO: Investigate. Quitting now sounds wrong - we won't do the resetting work
return;
}
}
// TODO: refactor the following code to be less contrived.
// "newSelStart != composingSpanEnd" || "newSelEnd != composingSpanEnd" means
// that the cursor is not at the end of the composing span, or there is a selection.
// "mLastSelectionStart != newSelStart" means that the cursor is not in the same place
// as last time we were called (if there is a selection, it means the start hasn't
// changed, so it's the end that did).
final boolean selectionChanged = (newSelStart != composingSpanEnd
|| newSelEnd != composingSpanEnd) && mLastSelectionStart != newSelStart;
// if composingSpanStart and composingSpanEnd are -1, it means there is no composing
// span in the view - we can use that to narrow down whether the cursor was moved
// by us or not. If we are composing a word but there is no composing span, then
// we know for sure the cursor moved while we were composing and we should reset
// the state.
final boolean noComposingSpan = composingSpanStart == -1 && composingSpanEnd == -1;
if (!mExpectingUpdateSelection
&& !mConnection.isBelatedExpectedUpdate(oldSelStart, newSelStart)) {
// TAKE CARE: there is a race condition when we enter this test even when the user
// did not explicitly move the cursor. This happens when typing fast, where two keys
// turn this flag on in succession and both onUpdateSelection() calls arrive after
// the second one - the first call successfully avoids this test, but the second one
// enters. For the moment we rely on noComposingSpan to further reduce the impact.
// TODO: the following is probably better done in resetEntireInputState().
// it should only happen when the cursor moved, and the very purpose of the
// test below is to narrow down whether this happened or not. Likewise with
// the call to updateShiftState.
// We set this to NONE because after a cursor move, we don't want the space
// state-related special processing to kick in.
mSpaceState = SPACE_STATE_NONE;
if ((!mWordComposer.isComposingWord()) || selectionChanged || noComposingSpan) {
// If we are composing a word and moving the cursor, we would want to set a
// suggestion span for recorrection to work correctly. Unfortunately, that
// would involve the keyboard committing some new text, which would move the
// cursor back to where it was. Latin IME could then fix the position of the cursor
// again, but the asynchronous nature of the calls results in this wreaking havoc
// with selection on double tap and the like.
// Another option would be to send suggestions each time we set the composing
// text, but that is probably too expensive to do, so we decided to leave things
// as is.
resetEntireInputState(newSelStart);
}
mKeyboardSwitcher.updateShiftState();
}
mExpectingUpdateSelection = false;
// TODO: Decide to call restartSuggestionsOnWordBeforeCursorIfAtEndOfWord() or not
// here. It would probably be too expensive to call directly here but we may want to post a
// message to delay it. The point would be to unify behavior between backspace to the
// end of a word and manually put the pointer at the end of the word.
// Make a note of the cursor position
mLastSelectionStart = newSelStart;
mLastSelectionEnd = newSelEnd;
}
/**
* This is called when the user has clicked on the extracted text view,
* when running in fullscreen mode. The default implementation hides
* the suggestions view when this happens, but only if the extracted text
* editor has a vertical scroll bar because its text doesn't fit.
* Here we override the behavior due to the possibility that a re-correction could
* cause the suggestions strip to disappear and re-appear.
*/
@Override
public void onExtractedTextClicked() {
if (mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) return;
super.onExtractedTextClicked();
}
/**
* This is called when the user has performed a cursor movement in the
* extracted text view, when it is running in fullscreen mode. The default
* implementation hides the suggestions view when a vertical movement
* happens, but only if the extracted text editor has a vertical scroll bar
* because its text doesn't fit.
* Here we override the behavior due to the possibility that a re-correction could
* cause the suggestions strip to disappear and re-appear.
*/
@Override
public void onExtractedCursorMovement(final int dx, final int dy) {
if (mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) return;
super.onExtractedCursorMovement(dx, dy);
}
@Override
public void hideWindow() {
LatinImeLogger.commit();
mKeyboardSwitcher.onHideWindow();
if (TRACE) Debug.stopMethodTracing();
if (mOptionsDialog != null && mOptionsDialog.isShowing()) {
mOptionsDialog.dismiss();
mOptionsDialog = null;
}
super.hideWindow();
}
@Override
public void onDisplayCompletions(final CompletionInfo[] applicationSpecifiedCompletions) {
if (DEBUG) {
Log.i(TAG, "Received completions:");
if (applicationSpecifiedCompletions != null) {
for (int i = 0; i < applicationSpecifiedCompletions.length; i++) {
Log.i(TAG, " #" + i + ": " + applicationSpecifiedCompletions[i]);
}
}
}
if (!mCurrentSettings.isApplicationSpecifiedCompletionsOn()) return;
mApplicationSpecifiedCompletions = applicationSpecifiedCompletions;
if (applicationSpecifiedCompletions == null) {
clearSuggestionStrip();
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_onDisplayCompletions(null);
}
return;
}
final ArrayList<SuggestedWords.SuggestedWordInfo> applicationSuggestedWords =
SuggestedWords.getFromApplicationSpecifiedCompletions(
applicationSpecifiedCompletions);
final SuggestedWords suggestedWords = new SuggestedWords(
applicationSuggestedWords,
false /* typedWordValid */,
false /* hasAutoCorrectionCandidate */,
false /* isPunctuationSuggestions */,
false /* isObsoleteSuggestions */,
false /* isPrediction */);
// When in fullscreen mode, show completions generated by the application
final boolean isAutoCorrection = false;
setSuggestionStrip(suggestedWords, isAutoCorrection);
setAutoCorrectionIndicator(isAutoCorrection);
// TODO: is this the right thing to do? What should we auto-correct to in
// this case? This says to keep whatever the user typed.
mWordComposer.setAutoCorrection(mWordComposer.getTypedWord());
setSuggestionStripShown(true);
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_onDisplayCompletions(applicationSpecifiedCompletions);
}
}
private void setSuggestionStripShownInternal(final boolean shown,
final boolean needsInputViewShown) {
// TODO: Modify this if we support suggestions with hard keyboard
if (onEvaluateInputViewShown() && mSuggestionsContainer != null) {
final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
final boolean inputViewShown = (mainKeyboardView != null)
? mainKeyboardView.isShown() : false;
final boolean shouldShowSuggestions = shown
&& (needsInputViewShown ? inputViewShown : true);
if (isFullscreenMode()) {
mSuggestionsContainer.setVisibility(
shouldShowSuggestions ? View.VISIBLE : View.GONE);
} else {
mSuggestionsContainer.setVisibility(
shouldShowSuggestions ? View.VISIBLE : View.INVISIBLE);
}
}
}
private void setSuggestionStripShown(final boolean shown) {
setSuggestionStripShownInternal(shown, /* needsInputViewShown */true);
}
private int getAdjustedBackingViewHeight() {
final int currentHeight = mKeyPreviewBackingView.getHeight();
if (currentHeight > 0) {
return currentHeight;
}
final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
if (mainKeyboardView == null) {
return 0;
}
final int keyboardHeight = mainKeyboardView.getHeight();
final int suggestionsHeight = mSuggestionsContainer.getHeight();
final int displayHeight = mResources.getDisplayMetrics().heightPixels;
final Rect rect = new Rect();
mKeyPreviewBackingView.getWindowVisibleDisplayFrame(rect);
final int notificationBarHeight = rect.top;
final int remainingHeight = displayHeight - notificationBarHeight - suggestionsHeight
- keyboardHeight;
final LayoutParams params = mKeyPreviewBackingView.getLayoutParams();
params.height = mSuggestionStripView.setMoreSuggestionsHeight(remainingHeight);
mKeyPreviewBackingView.setLayoutParams(params);
return params.height;
}
@Override
public void onComputeInsets(final InputMethodService.Insets outInsets) {
super.onComputeInsets(outInsets);
final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
if (mainKeyboardView == null || mSuggestionsContainer == null) {
return;
}
final int adjustedBackingHeight = getAdjustedBackingViewHeight();
final boolean backingGone = (mKeyPreviewBackingView.getVisibility() == View.GONE);
final int backingHeight = backingGone ? 0 : adjustedBackingHeight;
// In fullscreen mode, the height of the extract area managed by InputMethodService should
// be considered.
// See {@link android.inputmethodservice.InputMethodService#onComputeInsets}.
final int extractHeight = isFullscreenMode() ? mExtractArea.getHeight() : 0;
final int suggestionsHeight = (mSuggestionsContainer.getVisibility() == View.GONE) ? 0
: mSuggestionsContainer.getHeight();
final int extraHeight = extractHeight + backingHeight + suggestionsHeight;
int touchY = extraHeight;
// Need to set touchable region only if input view is being shown
if (mainKeyboardView.isShown()) {
if (mSuggestionsContainer.getVisibility() == View.VISIBLE) {
touchY -= suggestionsHeight;
}
final int touchWidth = mainKeyboardView.getWidth();
final int touchHeight = mainKeyboardView.getHeight() + extraHeight
// Extend touchable region below the keyboard.
+ EXTENDED_TOUCHABLE_REGION_HEIGHT;
outInsets.touchableInsets = InputMethodService.Insets.TOUCHABLE_INSETS_REGION;
outInsets.touchableRegion.set(0, touchY, touchWidth, touchHeight);
}
outInsets.contentTopInsets = touchY;
outInsets.visibleTopInsets = touchY;
}
@Override
public boolean onEvaluateFullscreenMode() {
// Reread resource value here, because this method is called by framework anytime as needed.
final boolean isFullscreenModeAllowed =
mCurrentSettings.isFullscreenModeAllowed(getResources());
return super.onEvaluateFullscreenMode() && isFullscreenModeAllowed;
}
@Override
public void updateFullscreenMode() {
super.updateFullscreenMode();
if (mKeyPreviewBackingView == null) return;
// In fullscreen mode, no need to have extra space to show the key preview.
// If not, we should have extra space above the keyboard to show the key preview.
mKeyPreviewBackingView.setVisibility(isFullscreenMode() ? View.GONE : View.VISIBLE);
}
// This will reset the whole input state to the starting state. It will clear
// the composing word, reset the last composed word, tell the inputconnection about it.
private void resetEntireInputState(final int newCursorPosition) {
resetComposingState(true /* alsoResetLastComposedWord */);
if (mCurrentSettings.mBigramPredictionEnabled) {
clearSuggestionStrip();
} else {
setSuggestionStrip(mCurrentSettings.mSuggestPuncList, false);
}
mConnection.resetCachesUponCursorMove(newCursorPosition);
}
private void resetComposingState(final boolean alsoResetLastComposedWord) {
mWordComposer.reset();
if (alsoResetLastComposedWord)
mLastComposedWord = LastComposedWord.NOT_A_COMPOSED_WORD;
}
private void commitTyped(final String separatorString) {
if (!mWordComposer.isComposingWord()) return;
final CharSequence typedWord = mWordComposer.getTypedWord();
if (typedWord.length() > 0) {
commitChosenWord(typedWord, LastComposedWord.COMMIT_TYPE_USER_TYPED_WORD,
separatorString);
}
}
// Called from the KeyboardSwitcher which needs to know auto caps state to display
// the right layout.
public int getCurrentAutoCapsState() {
if (!mCurrentSettings.mAutoCap) return Constants.TextUtils.CAP_MODE_OFF;
final EditorInfo ei = getCurrentInputEditorInfo();
if (ei == null) return Constants.TextUtils.CAP_MODE_OFF;
final int inputType = ei.inputType;
// Warning: this depends on mSpaceState, which may not be the most current value. If
// mSpaceState gets updated later, whoever called this may need to be told about it.
return mConnection.getCursorCapsMode(inputType, mSubtypeSwitcher.getCurrentSubtypeLocale(),
SPACE_STATE_PHANTOM == mSpaceState);
}
// Factor in auto-caps and manual caps and compute the current caps mode.
private int getActualCapsMode() {
- final int manual = mKeyboardSwitcher.getManualCapsMode();
- if (manual != WordComposer.CAPS_MODE_OFF) return manual;
+ final int keyboardShiftMode = mKeyboardSwitcher.getKeyboardShiftMode();
+ if (keyboardShiftMode != WordComposer.CAPS_MODE_AUTO_SHIFTED) return keyboardShiftMode;
final int auto = getCurrentAutoCapsState();
if (0 != (auto & TextUtils.CAP_MODE_CHARACTERS)) {
return WordComposer.CAPS_MODE_AUTO_SHIFT_LOCKED;
}
if (0 != auto) return WordComposer.CAPS_MODE_AUTO_SHIFTED;
return WordComposer.CAPS_MODE_OFF;
}
private void swapSwapperAndSpace() {
CharSequence lastTwo = mConnection.getTextBeforeCursor(2, 0);
// It is guaranteed lastTwo.charAt(1) is a swapper - else this method is not called.
if (lastTwo != null && lastTwo.length() == 2
&& lastTwo.charAt(0) == Keyboard.CODE_SPACE) {
mConnection.deleteSurroundingText(2, 0);
mConnection.commitText(lastTwo.charAt(1) + " ", 1);
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_swapSwapperAndSpace();
}
mKeyboardSwitcher.updateShiftState();
}
}
private boolean maybeDoubleSpace() {
if (!mCurrentSettings.mCorrectionEnabled) return false;
if (!mHandler.isAcceptingDoubleSpaces()) return false;
final CharSequence lastThree = mConnection.getTextBeforeCursor(3, 0);
if (lastThree != null && lastThree.length() == 3
&& canBeFollowedByPeriod(lastThree.charAt(0))
&& lastThree.charAt(1) == Keyboard.CODE_SPACE
&& lastThree.charAt(2) == Keyboard.CODE_SPACE) {
mHandler.cancelDoubleSpacesTimer();
mConnection.deleteSurroundingText(2, 0);
mConnection.commitText(". ", 1);
mKeyboardSwitcher.updateShiftState();
return true;
}
return false;
}
private static boolean canBeFollowedByPeriod(final int codePoint) {
// TODO: Check again whether there really ain't a better way to check this.
// TODO: This should probably be language-dependant...
return Character.isLetterOrDigit(codePoint)
|| codePoint == Keyboard.CODE_SINGLE_QUOTE
|| codePoint == Keyboard.CODE_DOUBLE_QUOTE
|| codePoint == Keyboard.CODE_CLOSING_PARENTHESIS
|| codePoint == Keyboard.CODE_CLOSING_SQUARE_BRACKET
|| codePoint == Keyboard.CODE_CLOSING_CURLY_BRACKET
|| codePoint == Keyboard.CODE_CLOSING_ANGLE_BRACKET;
}
// Callback for the {@link SuggestionStripView}, to call when the "add to dictionary" hint is
// pressed.
@Override
public boolean addWordToUserDictionary(final String word) {
mUserDictionary.addWordToUserDictionary(word, 128);
return true;
}
private static boolean isAlphabet(final int code) {
return Character.isLetter(code);
}
private void onSettingsKeyPressed() {
if (isShowingOptionDialog()) return;
showSubtypeSelectorAndSettings();
}
// Virtual codes representing custom requests. These are used in onCustomRequest() below.
public static final int CODE_SHOW_INPUT_METHOD_PICKER = 1;
@Override
public boolean onCustomRequest(final int requestCode) {
if (isShowingOptionDialog()) return false;
switch (requestCode) {
case CODE_SHOW_INPUT_METHOD_PICKER:
if (ImfUtils.hasMultipleEnabledIMEsOrSubtypes(
this, true /* include aux subtypes */)) {
mImm.showInputMethodPicker();
return true;
}
return false;
}
return false;
}
private boolean isShowingOptionDialog() {
return mOptionsDialog != null && mOptionsDialog.isShowing();
}
private static int getActionId(final Keyboard keyboard) {
return keyboard != null ? keyboard.mId.imeActionId() : EditorInfo.IME_ACTION_NONE;
}
private void performEditorAction(final int actionId) {
mConnection.performEditorAction(actionId);
}
// TODO: Revise the language switch key behavior to make it much smarter and more reasonable.
private void handleLanguageSwitchKey() {
final IBinder token = getWindow().getWindow().getAttributes().token;
if (mCurrentSettings.mIncludesOtherImesInLanguageSwitchList) {
mImm.switchToNextInputMethod(token, false /* onlyCurrentIme */);
return;
}
if (mShouldSwitchToLastSubtype) {
final InputMethodSubtype lastSubtype = mImm.getLastInputMethodSubtype();
final boolean lastSubtypeBelongsToThisIme =
ImfUtils.checkIfSubtypeBelongsToThisImeAndEnabled(this, lastSubtype);
if (lastSubtypeBelongsToThisIme && mImm.switchToLastInputMethod(token)) {
mShouldSwitchToLastSubtype = false;
} else {
mImm.switchToNextInputMethod(token, true /* onlyCurrentIme */);
mShouldSwitchToLastSubtype = true;
}
} else {
mImm.switchToNextInputMethod(token, true /* onlyCurrentIme */);
}
}
private void sendDownUpKeyEventForBackwardCompatibility(final int code) {
final long eventTime = SystemClock.uptimeMillis();
mConnection.sendKeyEvent(new KeyEvent(eventTime, eventTime,
KeyEvent.ACTION_DOWN, code, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0,
KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE));
mConnection.sendKeyEvent(new KeyEvent(SystemClock.uptimeMillis(), eventTime,
KeyEvent.ACTION_UP, code, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0,
KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE));
}
private void sendKeyCodePoint(final int code) {
// TODO: Remove this special handling of digit letters.
// For backward compatibility. See {@link InputMethodService#sendKeyChar(char)}.
if (code >= '0' && code <= '9') {
sendDownUpKeyEventForBackwardCompatibility(code - '0' + KeyEvent.KEYCODE_0);
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_sendKeyCodePoint(code);
}
return;
}
// 16 is android.os.Build.VERSION_CODES.JELLY_BEAN but we can't write it because
// we want to be able to compile against the Ice Cream Sandwich SDK.
if (Keyboard.CODE_ENTER == code && mTargetApplicationInfo != null
&& mTargetApplicationInfo.targetSdkVersion < 16) {
// Backward compatibility mode. Before Jelly bean, the keyboard would simulate
// a hardware keyboard event on pressing enter or delete. This is bad for many
// reasons (there are race conditions with commits) but some applications are
// relying on this behavior so we continue to support it for older apps.
sendDownUpKeyEventForBackwardCompatibility(KeyEvent.KEYCODE_ENTER);
} else {
final String text = new String(new int[] { code }, 0, 1);
mConnection.commitText(text, text.length());
}
}
// Implementation of {@link KeyboardActionListener}.
@Override
public void onCodeInput(final int primaryCode, final int x, final int y) {
final long when = SystemClock.uptimeMillis();
if (primaryCode != Keyboard.CODE_DELETE || when > mLastKeyTime + QUICK_PRESS) {
mDeleteCount = 0;
}
mLastKeyTime = when;
mConnection.beginBatchEdit();
final KeyboardSwitcher switcher = mKeyboardSwitcher;
// The space state depends only on the last character pressed and its own previous
// state. Here, we revert the space state to neutral if the key is actually modifying
// the input contents (any non-shift key), which is what we should do for
// all inputs that do not result in a special state. Each character handling is then
// free to override the state as they see fit.
final int spaceState = mSpaceState;
if (!mWordComposer.isComposingWord()) mIsAutoCorrectionIndicatorOn = false;
// TODO: Consolidate the double space timer, mLastKeyTime, and the space state.
if (primaryCode != Keyboard.CODE_SPACE) {
mHandler.cancelDoubleSpacesTimer();
}
boolean didAutoCorrect = false;
switch (primaryCode) {
case Keyboard.CODE_DELETE:
mSpaceState = SPACE_STATE_NONE;
handleBackspace(spaceState);
mDeleteCount++;
mExpectingUpdateSelection = true;
mShouldSwitchToLastSubtype = true;
LatinImeLogger.logOnDelete(x, y);
break;
case Keyboard.CODE_SHIFT:
case Keyboard.CODE_SWITCH_ALPHA_SYMBOL:
// Shift and symbol key is handled in onPressKey() and onReleaseKey().
break;
case Keyboard.CODE_SETTINGS:
onSettingsKeyPressed();
break;
case Keyboard.CODE_SHORTCUT:
mSubtypeSwitcher.switchToShortcutIME(this);
break;
case Keyboard.CODE_ACTION_ENTER:
performEditorAction(getActionId(switcher.getKeyboard()));
break;
case Keyboard.CODE_ACTION_NEXT:
performEditorAction(EditorInfo.IME_ACTION_NEXT);
break;
case Keyboard.CODE_ACTION_PREVIOUS:
performEditorAction(EditorInfo.IME_ACTION_PREVIOUS);
break;
case Keyboard.CODE_LANGUAGE_SWITCH:
handleLanguageSwitchKey();
break;
case Keyboard.CODE_RESEARCH:
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.getInstance().onResearchKeySelected(this);
}
break;
default:
mSpaceState = SPACE_STATE_NONE;
if (mCurrentSettings.isWordSeparator(primaryCode)) {
didAutoCorrect = handleSeparator(primaryCode, x, y, spaceState);
} else {
if (SPACE_STATE_PHANTOM == spaceState) {
if (ProductionFlag.IS_INTERNAL) {
if (mWordComposer.isComposingWord() && mWordComposer.isBatchMode()) {
Stats.onAutoCorrection(
"", mWordComposer.getTypedWord(), " ", mWordComposer);
}
}
commitTyped(LastComposedWord.NOT_A_SEPARATOR);
}
final int keyX, keyY;
final Keyboard keyboard = mKeyboardSwitcher.getKeyboard();
if (keyboard != null && keyboard.hasProximityCharsCorrection(primaryCode)) {
keyX = x;
keyY = y;
} else {
keyX = Constants.NOT_A_COORDINATE;
keyY = Constants.NOT_A_COORDINATE;
}
handleCharacter(primaryCode, keyX, keyY, spaceState);
}
mExpectingUpdateSelection = true;
mShouldSwitchToLastSubtype = true;
break;
}
switcher.onCodeInput(primaryCode);
// Reset after any single keystroke, except shift and symbol-shift
if (!didAutoCorrect && primaryCode != Keyboard.CODE_SHIFT
&& primaryCode != Keyboard.CODE_SWITCH_ALPHA_SYMBOL)
mLastComposedWord.deactivate();
if (Keyboard.CODE_DELETE != primaryCode) {
mEnteredText = null;
}
mConnection.endBatchEdit();
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_onCodeInput(primaryCode, x, y);
}
}
// Called from PointerTracker through the KeyboardActionListener interface
@Override
public void onTextInput(final CharSequence rawText) {
mConnection.beginBatchEdit();
if (mWordComposer.isComposingWord()) {
commitCurrentAutoCorrection(rawText.toString());
} else {
resetComposingState(true /* alsoResetLastComposedWord */);
}
mHandler.postUpdateSuggestionStrip();
final CharSequence text = specificTldProcessingOnTextInput(rawText);
if (SPACE_STATE_PHANTOM == mSpaceState) {
sendKeyCodePoint(Keyboard.CODE_SPACE);
}
mConnection.commitText(text, 1);
mConnection.endBatchEdit();
// Space state must be updated before calling updateShiftState
mSpaceState = SPACE_STATE_NONE;
mKeyboardSwitcher.updateShiftState();
mKeyboardSwitcher.onCodeInput(Keyboard.CODE_OUTPUT_TEXT);
mEnteredText = text;
}
@Override
public void onStartBatchInput() {
BatchInputUpdater.getInstance().onStartBatchInput();
mConnection.beginBatchEdit();
if (mWordComposer.isComposingWord()) {
if (ProductionFlag.IS_INTERNAL) {
if (mWordComposer.isBatchMode()) {
Stats.onAutoCorrection("", mWordComposer.getTypedWord(), " ", mWordComposer);
}
}
if (mWordComposer.size() <= 1) {
// We auto-correct the previous (typed, not gestured) string iff it's one character
// long. The reason for this is, even in the middle of gesture typing, you'll still
// tap one-letter words and you want them auto-corrected (typically, "i" in English
// should become "I"). However for any longer word, we assume that the reason for
// tapping probably is that the word you intend to type is not in the dictionary,
// so we do not attempt to correct, on the assumption that if that was a dictionary
// word, the user would probably have gestured instead.
commitCurrentAutoCorrection(LastComposedWord.NOT_A_SEPARATOR);
} else {
commitTyped(LastComposedWord.NOT_A_SEPARATOR);
}
mExpectingUpdateSelection = true;
// The following is necessary for the case where the user typed something but didn't
// manual pick it and didn't input any separator.
mSpaceState = SPACE_STATE_PHANTOM;
}
mConnection.endBatchEdit();
mWordComposer.setCapitalizedModeAtStartComposingTime(getActualCapsMode());
}
private static final class BatchInputUpdater implements Handler.Callback {
private final Handler mHandler;
private LatinIME mLatinIme;
private boolean mInBatchInput; // synchornized using "this".
private BatchInputUpdater() {
final HandlerThread handlerThread = new HandlerThread(
BatchInputUpdater.class.getSimpleName());
handlerThread.start();
mHandler = new Handler(handlerThread.getLooper(), this);
}
// Initialization-on-demand holder
private static final class OnDemandInitializationHolder {
public static final BatchInputUpdater sInstance = new BatchInputUpdater();
}
public static BatchInputUpdater getInstance() {
return OnDemandInitializationHolder.sInstance;
}
private static final int MSG_UPDATE_GESTURE_PREVIEW_AND_SUGGESTION_STRIP = 1;
@Override
public boolean handleMessage(final Message msg) {
switch (msg.what) {
case MSG_UPDATE_GESTURE_PREVIEW_AND_SUGGESTION_STRIP:
updateBatchInput((InputPointers)msg.obj, mLatinIme);
break;
}
return true;
}
// Run in the UI thread.
public synchronized void onStartBatchInput() {
mInBatchInput = true;
}
// Run in the Handler thread.
private synchronized void updateBatchInput(final InputPointers batchPointers,
final LatinIME latinIme) {
if (!mInBatchInput) {
// Batch input has ended while the message was being delivered.
return;
}
final SuggestedWords suggestedWords = getSuggestedWordsGestureLocked(
batchPointers, latinIme);
latinIme.mHandler.showGesturePreviewAndSuggestionStrip(
suggestedWords, false /* dismissGestureFloatingPreviewText */);
}
// Run in the UI thread.
public void onUpdateBatchInput(final InputPointers batchPointers, final LatinIME latinIme) {
mLatinIme = latinIme;
if (mHandler.hasMessages(MSG_UPDATE_GESTURE_PREVIEW_AND_SUGGESTION_STRIP)) {
return;
}
mHandler.obtainMessage(
MSG_UPDATE_GESTURE_PREVIEW_AND_SUGGESTION_STRIP, batchPointers)
.sendToTarget();
}
// Run in the UI thread.
public synchronized SuggestedWords onEndBatchInput(final InputPointers batchPointers,
final LatinIME latinIme) {
mInBatchInput = false;
final SuggestedWords suggestedWords = getSuggestedWordsGestureLocked(
batchPointers, latinIme);
latinIme.mHandler.showGesturePreviewAndSuggestionStrip(
suggestedWords, true /* dismissGestureFloatingPreviewText */);
return suggestedWords;
}
// {@link LatinIME#getSuggestedWords(int)} method calls with same session id have to
// be synchronized.
private static SuggestedWords getSuggestedWordsGestureLocked(
final InputPointers batchPointers, final LatinIME latinIme) {
latinIme.mWordComposer.setBatchInputPointers(batchPointers);
return latinIme.getSuggestedWords(Suggest.SESSION_GESTURE);
}
}
private void showGesturePreviewAndSuggestionStrip(final SuggestedWords suggestedWords,
final boolean dismissGestureFloatingPreviewText) {
final String batchInputText = (suggestedWords.size() > 0)
? suggestedWords.getWord(0) : null;
final KeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
mainKeyboardView.showGestureFloatingPreviewText(batchInputText);
showSuggestionStrip(suggestedWords, null);
if (dismissGestureFloatingPreviewText) {
mainKeyboardView.dismissGestureFloatingPreviewText();
}
}
@Override
public void onUpdateBatchInput(final InputPointers batchPointers) {
BatchInputUpdater.getInstance().onUpdateBatchInput(batchPointers, this);
}
@Override
public void onEndBatchInput(final InputPointers batchPointers) {
final SuggestedWords suggestedWords = BatchInputUpdater.getInstance().onEndBatchInput(
batchPointers, this);
final String batchInputText = (suggestedWords.size() > 0)
? suggestedWords.getWord(0) : null;
if (TextUtils.isEmpty(batchInputText)) {
return;
}
mWordComposer.setBatchInputWord(batchInputText);
mConnection.beginBatchEdit();
if (SPACE_STATE_PHANTOM == mSpaceState) {
sendKeyCodePoint(Keyboard.CODE_SPACE);
}
mConnection.setComposingText(batchInputText, 1);
mExpectingUpdateSelection = true;
mConnection.endBatchEdit();
// Space state must be updated before calling updateShiftState
mSpaceState = SPACE_STATE_PHANTOM;
mKeyboardSwitcher.updateShiftState();
}
private CharSequence specificTldProcessingOnTextInput(final CharSequence text) {
if (text.length() <= 1 || text.charAt(0) != Keyboard.CODE_PERIOD
|| !Character.isLetter(text.charAt(1))) {
// Not a tld: do nothing.
return text;
}
// We have a TLD (or something that looks like this): make sure we don't add
// a space even if currently in phantom mode.
mSpaceState = SPACE_STATE_NONE;
final CharSequence lastOne = mConnection.getTextBeforeCursor(1, 0);
if (lastOne != null && lastOne.length() == 1
&& lastOne.charAt(0) == Keyboard.CODE_PERIOD) {
return text.subSequence(1, text.length());
} else {
return text;
}
}
// Called from PointerTracker through the KeyboardActionListener interface
@Override
public void onCancelInput() {
// User released a finger outside any key
mKeyboardSwitcher.onCancelInput();
}
private void handleBackspace(final int spaceState) {
// In many cases, we may have to put the keyboard in auto-shift state again. However
// we want to wait a few milliseconds before doing it to avoid the keyboard flashing
// during key repeat.
mHandler.postUpdateShiftState();
if (mWordComposer.isComposingWord()) {
final int length = mWordComposer.size();
if (length > 0) {
// Immediately after a batch input.
if (SPACE_STATE_PHANTOM == spaceState) {
mWordComposer.reset();
} else {
mWordComposer.deleteLast();
}
mConnection.setComposingText(getTextWithUnderline(mWordComposer.getTypedWord()), 1);
mHandler.postUpdateSuggestionStrip();
} else {
mConnection.deleteSurroundingText(1, 0);
}
} else {
if (mLastComposedWord.canRevertCommit()) {
if (ProductionFlag.IS_INTERNAL) {
Stats.onAutoCorrectionCancellation();
}
revertCommit();
return;
}
if (mEnteredText != null && mConnection.sameAsTextBeforeCursor(mEnteredText)) {
// Cancel multi-character input: remove the text we just entered.
// This is triggered on backspace after a key that inputs multiple characters,
// like the smiley key or the .com key.
final int length = mEnteredText.length();
mConnection.deleteSurroundingText(length, 0);
mEnteredText = null;
// If we have mEnteredText, then we know that mHasUncommittedTypedChars == false.
// In addition we know that spaceState is false, and that we should not be
// reverting any autocorrect at this point. So we can safely return.
return;
}
if (SPACE_STATE_DOUBLE == spaceState) {
mHandler.cancelDoubleSpacesTimer();
if (mConnection.revertDoubleSpace()) {
// No need to reset mSpaceState, it has already be done (that's why we
// receive it as a parameter)
return;
}
} else if (SPACE_STATE_SWAP_PUNCTUATION == spaceState) {
if (mConnection.revertSwapPunctuation()) {
// Likewise
return;
}
}
// No cancelling of commit/double space/swap: we have a regular backspace.
// We should backspace one char and restart suggestion if at the end of a word.
if (mLastSelectionStart != mLastSelectionEnd) {
// If there is a selection, remove it.
final int lengthToDelete = mLastSelectionEnd - mLastSelectionStart;
mConnection.setSelection(mLastSelectionEnd, mLastSelectionEnd);
mConnection.deleteSurroundingText(lengthToDelete, 0);
} else {
// There is no selection, just delete one character.
if (NOT_A_CURSOR_POSITION == mLastSelectionEnd) {
// This should never happen.
Log.e(TAG, "Backspace when we don't know the selection position");
}
// 16 is android.os.Build.VERSION_CODES.JELLY_BEAN but we can't write it because
// we want to be able to compile against the Ice Cream Sandwich SDK.
if (mTargetApplicationInfo != null
&& mTargetApplicationInfo.targetSdkVersion < 16) {
// Backward compatibility mode. Before Jelly bean, the keyboard would simulate
// a hardware keyboard event on pressing enter or delete. This is bad for many
// reasons (there are race conditions with commits) but some applications are
// relying on this behavior so we continue to support it for older apps.
sendDownUpKeyEventForBackwardCompatibility(KeyEvent.KEYCODE_DEL);
} else {
mConnection.deleteSurroundingText(1, 0);
}
if (mDeleteCount > DELETE_ACCELERATE_AT) {
mConnection.deleteSurroundingText(1, 0);
}
}
if (mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) {
restartSuggestionsOnWordBeforeCursorIfAtEndOfWord();
}
}
}
private boolean maybeStripSpace(final int code,
final int spaceState, final boolean isFromSuggestionStrip) {
if (Keyboard.CODE_ENTER == code && SPACE_STATE_SWAP_PUNCTUATION == spaceState) {
mConnection.removeTrailingSpace();
return false;
} else if ((SPACE_STATE_WEAK == spaceState
|| SPACE_STATE_SWAP_PUNCTUATION == spaceState)
&& isFromSuggestionStrip) {
if (mCurrentSettings.isWeakSpaceSwapper(code)) {
return true;
} else {
if (mCurrentSettings.isWeakSpaceStripper(code)) {
mConnection.removeTrailingSpace();
}
return false;
}
} else {
return false;
}
}
private void handleCharacter(final int primaryCode, final int x,
final int y, final int spaceState) {
boolean isComposingWord = mWordComposer.isComposingWord();
if (SPACE_STATE_PHANTOM == spaceState &&
!mCurrentSettings.isSymbolExcludedFromWordSeparators(primaryCode)) {
if (isComposingWord) {
// Sanity check
throw new RuntimeException("Should not be composing here");
}
sendKeyCodePoint(Keyboard.CODE_SPACE);
}
// NOTE: isCursorTouchingWord() is a blocking IPC call, so it often takes several
// dozen milliseconds. Avoid calling it as much as possible, since we are on the UI
// thread here.
if (!isComposingWord && (isAlphabet(primaryCode)
|| mCurrentSettings.isSymbolExcludedFromWordSeparators(primaryCode))
&& mCurrentSettings.isSuggestionsRequested(mDisplayOrientation) &&
!mConnection.isCursorTouchingWord(mCurrentSettings)) {
// Reset entirely the composing state anyway, then start composing a new word unless
// the character is a single quote. The idea here is, single quote is not a
// separator and it should be treated as a normal character, except in the first
// position where it should not start composing a word.
isComposingWord = (Keyboard.CODE_SINGLE_QUOTE != primaryCode);
// Here we don't need to reset the last composed word. It will be reset
// when we commit this one, if we ever do; if on the other hand we backspace
// it entirely and resume suggestions on the previous word, we'd like to still
// have touch coordinates for it.
resetComposingState(false /* alsoResetLastComposedWord */);
}
if (isComposingWord) {
final int keyX, keyY;
if (KeyboardActionListener.Adapter.isInvalidCoordinate(x)
|| KeyboardActionListener.Adapter.isInvalidCoordinate(y)) {
keyX = x;
keyY = y;
} else {
final KeyDetector keyDetector =
mKeyboardSwitcher.getMainKeyboardView().getKeyDetector();
keyX = keyDetector.getTouchX(x);
keyY = keyDetector.getTouchY(y);
}
mWordComposer.add(primaryCode, keyX, keyY);
// If it's the first letter, make note of auto-caps state
if (mWordComposer.size() == 1) {
mWordComposer.setCapitalizedModeAtStartComposingTime(getActualCapsMode());
}
mConnection.setComposingText(getTextWithUnderline(mWordComposer.getTypedWord()), 1);
} else {
final boolean swapWeakSpace = maybeStripSpace(primaryCode,
spaceState, Constants.SUGGESTION_STRIP_COORDINATE == x);
sendKeyCodePoint(primaryCode);
if (swapWeakSpace) {
swapSwapperAndSpace();
mSpaceState = SPACE_STATE_WEAK;
}
// In case the "add to dictionary" hint was still displayed.
if (null != mSuggestionStripView) mSuggestionStripView.dismissAddToDictionaryHint();
}
mHandler.postUpdateSuggestionStrip();
if (ProductionFlag.IS_INTERNAL) {
Utils.Stats.onNonSeparator((char)primaryCode, x, y);
}
}
// Returns true if we did an autocorrection, false otherwise.
private boolean handleSeparator(final int primaryCode, final int x, final int y,
final int spaceState) {
boolean didAutoCorrect = false;
// Handle separator
if (mWordComposer.isComposingWord()) {
if (mCurrentSettings.mCorrectionEnabled) {
// TODO: maybe cache Strings in an <String> sparse array or something
commitCurrentAutoCorrection(new String(new int[]{primaryCode}, 0, 1));
didAutoCorrect = true;
} else {
commitTyped(new String(new int[]{primaryCode}, 0, 1));
}
}
final boolean swapWeakSpace = maybeStripSpace(primaryCode, spaceState,
Constants.SUGGESTION_STRIP_COORDINATE == x);
if (SPACE_STATE_PHANTOM == spaceState &&
mCurrentSettings.isPhantomSpacePromotingSymbol(primaryCode)) {
sendKeyCodePoint(Keyboard.CODE_SPACE);
}
sendKeyCodePoint(primaryCode);
if (Keyboard.CODE_SPACE == primaryCode) {
if (mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) {
if (maybeDoubleSpace()) {
mSpaceState = SPACE_STATE_DOUBLE;
} else if (!isShowingPunctuationList()) {
mSpaceState = SPACE_STATE_WEAK;
}
}
mHandler.startDoubleSpacesTimer();
if (!mConnection.isCursorTouchingWord(mCurrentSettings)) {
mHandler.postUpdateSuggestionStrip();
}
} else {
if (swapWeakSpace) {
swapSwapperAndSpace();
mSpaceState = SPACE_STATE_SWAP_PUNCTUATION;
} else if (SPACE_STATE_PHANTOM == spaceState
&& !mCurrentSettings.isWeakSpaceStripper(primaryCode)
&& !mCurrentSettings.isPhantomSpacePromotingSymbol(primaryCode)) {
// If we are in phantom space state, and the user presses a separator, we want to
// stay in phantom space state so that the next keypress has a chance to add the
// space. For example, if I type "Good dat", pick "day" from the suggestion strip
// then insert a comma and go on to typing the next word, I want the space to be
// inserted automatically before the next word, the same way it is when I don't
// input the comma.
// The case is a little different if the separator is a space stripper. Such a
// separator does not normally need a space on the right (that's the difference
// between swappers and strippers), so we should not stay in phantom space state if
// the separator is a stripper. Hence the additional test above.
mSpaceState = SPACE_STATE_PHANTOM;
}
// Set punctuation right away. onUpdateSelection will fire but tests whether it is
// already displayed or not, so it's okay.
setPunctuationSuggestions();
}
if (ProductionFlag.IS_INTERNAL) {
Utils.Stats.onSeparator((char)primaryCode, x, y);
}
mKeyboardSwitcher.updateShiftState();
return didAutoCorrect;
}
private CharSequence getTextWithUnderline(final CharSequence text) {
return mIsAutoCorrectionIndicatorOn
? SuggestionSpanUtils.getTextWithAutoCorrectionIndicatorUnderline(this, text)
: text;
}
private void handleClose() {
commitTyped(LastComposedWord.NOT_A_SEPARATOR);
requestHideSelf(0);
final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
if (mainKeyboardView != null) {
mainKeyboardView.closing();
}
}
// TODO: make this private
// Outside LatinIME, only used by the test suite.
/* package for tests */
boolean isShowingPunctuationList() {
if (mSuggestionStripView == null) return false;
return mCurrentSettings.mSuggestPuncList == mSuggestionStripView.getSuggestions();
}
private boolean isSuggestionsStripVisible() {
if (mSuggestionStripView == null)
return false;
if (mSuggestionStripView.isShowingAddToDictionaryHint())
return true;
if (!mCurrentSettings.isSuggestionStripVisibleInOrientation(mDisplayOrientation))
return false;
if (mCurrentSettings.isApplicationSpecifiedCompletionsOn())
return true;
return mCurrentSettings.isSuggestionsRequested(mDisplayOrientation);
}
private void clearSuggestionStrip() {
setSuggestionStrip(SuggestedWords.EMPTY, false);
setAutoCorrectionIndicator(false);
}
private void setSuggestionStrip(final SuggestedWords words, final boolean isAutoCorrection) {
if (mSuggestionStripView != null) {
mSuggestionStripView.setSuggestions(words);
mKeyboardSwitcher.onAutoCorrectionStateChanged(isAutoCorrection);
}
}
private void setAutoCorrectionIndicator(final boolean newAutoCorrectionIndicator) {
// Put a blue underline to a word in TextView which will be auto-corrected.
if (mIsAutoCorrectionIndicatorOn != newAutoCorrectionIndicator
&& mWordComposer.isComposingWord()) {
mIsAutoCorrectionIndicatorOn = newAutoCorrectionIndicator;
final CharSequence textWithUnderline =
getTextWithUnderline(mWordComposer.getTypedWord());
// TODO: when called from an updateSuggestionStrip() call that results from a posted
// message, this is called outside any batch edit. Potentially, this may result in some
// janky flickering of the screen, although the display speed makes it unlikely in
// the practice.
mConnection.setComposingText(textWithUnderline, 1);
}
}
private void updateSuggestionStrip() {
mHandler.cancelUpdateSuggestionStrip();
// Check if we have a suggestion engine attached.
if (mSuggest == null || !mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) {
if (mWordComposer.isComposingWord()) {
Log.w(TAG, "Called updateSuggestionsOrPredictions but suggestions were not "
+ "requested!");
mWordComposer.setAutoCorrection(mWordComposer.getTypedWord());
}
return;
}
if (!mWordComposer.isComposingWord() && !mCurrentSettings.mBigramPredictionEnabled) {
setPunctuationSuggestions();
return;
}
final SuggestedWords suggestedWords = getSuggestedWords(Suggest.SESSION_TYPING);
final String typedWord = mWordComposer.getTypedWord();
showSuggestionStrip(suggestedWords, typedWord);
}
private SuggestedWords getSuggestedWords(final int sessionId) {
final Keyboard keyboard = mKeyboardSwitcher.getKeyboard();
if (keyboard == null) {
return SuggestedWords.EMPTY;
}
final String typedWord = mWordComposer.getTypedWord();
// Get the word on which we should search the bigrams. If we are composing a word, it's
// whatever is *before* the half-committed word in the buffer, hence 2; if we aren't, we
// should just skip whitespace if any, so 1.
// TODO: this is slow (2-way IPC) - we should probably cache this instead.
final CharSequence prevWord =
mConnection.getNthPreviousWord(mCurrentSettings.mWordSeparators,
mWordComposer.isComposingWord() ? 2 : 1);
final SuggestedWords suggestedWords = mSuggest.getSuggestedWords(mWordComposer,
prevWord, keyboard.getProximityInfo(), mCurrentSettings.mCorrectionEnabled,
sessionId);
return maybeRetrieveOlderSuggestions(typedWord, suggestedWords);
}
private SuggestedWords maybeRetrieveOlderSuggestions(final CharSequence typedWord,
final SuggestedWords suggestedWords) {
// TODO: consolidate this into getSuggestedWords
// We update the suggestion strip only when we have some suggestions to show, i.e. when
// the suggestion count is > 1; else, we leave the old suggestions, with the typed word
// replaced with the new one. However, when the word is a dictionary word, or when the
// length of the typed word is 1 or 0 (after a deletion typically), we do want to remove the
// old suggestions. Also, if we are showing the "add to dictionary" hint, we need to
// revert to suggestions - although it is unclear how we can come here if it's displayed.
if (suggestedWords.size() > 1 || typedWord.length() <= 1
|| !suggestedWords.mTypedWordValid
|| mSuggestionStripView.isShowingAddToDictionaryHint()) {
return suggestedWords;
} else {
SuggestedWords previousSuggestions = mSuggestionStripView.getSuggestions();
if (previousSuggestions == mCurrentSettings.mSuggestPuncList) {
previousSuggestions = SuggestedWords.EMPTY;
}
final ArrayList<SuggestedWords.SuggestedWordInfo> typedWordAndPreviousSuggestions =
SuggestedWords.getTypedWordAndPreviousSuggestions(
typedWord, previousSuggestions);
return new SuggestedWords(typedWordAndPreviousSuggestions,
false /* typedWordValid */,
false /* hasAutoCorrectionCandidate */,
false /* isPunctuationSuggestions */,
true /* isObsoleteSuggestions */,
false /* isPrediction */);
}
}
private void showSuggestionStrip(final SuggestedWords suggestedWords,
final CharSequence typedWord) {
if (null == suggestedWords || suggestedWords.size() <= 0) {
clearSuggestionStrip();
return;
}
final CharSequence autoCorrection;
if (suggestedWords.size() > 0) {
if (suggestedWords.mWillAutoCorrect) {
autoCorrection = suggestedWords.getWord(1);
} else {
autoCorrection = typedWord;
}
} else {
autoCorrection = null;
}
mWordComposer.setAutoCorrection(autoCorrection);
final boolean isAutoCorrection = suggestedWords.willAutoCorrect();
setSuggestionStrip(suggestedWords, isAutoCorrection);
setAutoCorrectionIndicator(isAutoCorrection);
setSuggestionStripShown(isSuggestionsStripVisible());
}
private void commitCurrentAutoCorrection(final String separatorString) {
// Complete any pending suggestions query first
if (mHandler.hasPendingUpdateSuggestions()) {
updateSuggestionStrip();
}
final CharSequence typedAutoCorrection = mWordComposer.getAutoCorrectionOrNull();
final String typedWord = mWordComposer.getTypedWord();
final CharSequence autoCorrection = (typedAutoCorrection != null)
? typedAutoCorrection : typedWord;
if (autoCorrection != null) {
if (TextUtils.isEmpty(typedWord)) {
throw new RuntimeException("We have an auto-correction but the typed word "
+ "is empty? Impossible! I must commit suicide.");
}
if (ProductionFlag.IS_INTERNAL) {
Stats.onAutoCorrection(
typedWord, autoCorrection.toString(), separatorString, mWordComposer);
}
mExpectingUpdateSelection = true;
commitChosenWord(autoCorrection, LastComposedWord.COMMIT_TYPE_DECIDED_WORD,
separatorString);
if (!typedWord.equals(autoCorrection)) {
// This will make the correction flash for a short while as a visual clue
// to the user that auto-correction happened. It has no other effect; in particular
// note that this won't affect the text inside the text field AT ALL: it only makes
// the segment of text starting at the supplied index and running for the length
// of the auto-correction flash. At this moment, the "typedWord" argument is
// ignored by TextView.
mConnection.commitCorrection(
new CorrectionInfo(mLastSelectionEnd - typedWord.length(),
typedWord, autoCorrection));
}
}
}
// Called from {@link SuggestionStripView} through the {@link SuggestionStripView#Listener}
// interface
@Override
public void pickSuggestionManually(final int index, final CharSequence suggestion) {
final SuggestedWords suggestedWords = mSuggestionStripView.getSuggestions();
// If this is a punctuation picked from the suggestion strip, pass it to onCodeInput
if (suggestion.length() == 1 && isShowingPunctuationList()) {
// Word separators are suggested before the user inputs something.
// So, LatinImeLogger logs "" as a user's input.
LatinImeLogger.logOnManualSuggestion("", suggestion.toString(), index, suggestedWords);
// Rely on onCodeInput to do the complicated swapping/stripping logic consistently.
final int primaryCode = suggestion.charAt(0);
onCodeInput(primaryCode,
Constants.SUGGESTION_STRIP_COORDINATE, Constants.SUGGESTION_STRIP_COORDINATE);
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_punctuationSuggestion(index, suggestion);
}
return;
}
mConnection.beginBatchEdit();
if (SPACE_STATE_PHANTOM == mSpaceState && suggestion.length() > 0
// In the batch input mode, a manually picked suggested word should just replace
// the current batch input text and there is no need for a phantom space.
&& !mWordComposer.isBatchMode()) {
int firstChar = Character.codePointAt(suggestion, 0);
if ((!mCurrentSettings.isWeakSpaceStripper(firstChar))
&& (!mCurrentSettings.isWeakSpaceSwapper(firstChar))) {
sendKeyCodePoint(Keyboard.CODE_SPACE);
}
}
if (mCurrentSettings.isApplicationSpecifiedCompletionsOn()
&& mApplicationSpecifiedCompletions != null
&& index >= 0 && index < mApplicationSpecifiedCompletions.length) {
if (mSuggestionStripView != null) {
mSuggestionStripView.clear();
}
mKeyboardSwitcher.updateShiftState();
resetComposingState(true /* alsoResetLastComposedWord */);
final CompletionInfo completionInfo = mApplicationSpecifiedCompletions[index];
mConnection.commitCompletion(completionInfo);
mConnection.endBatchEdit();
return;
}
// We need to log before we commit, because the word composer will store away the user
// typed word.
final String replacedWord = mWordComposer.getTypedWord().toString();
LatinImeLogger.logOnManualSuggestion(replacedWord,
suggestion.toString(), index, suggestedWords);
mExpectingUpdateSelection = true;
commitChosenWord(suggestion, LastComposedWord.COMMIT_TYPE_MANUAL_PICK,
LastComposedWord.NOT_A_SEPARATOR);
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_pickSuggestionManually(replacedWord, index, suggestion);
}
mConnection.endBatchEdit();
// Don't allow cancellation of manual pick
mLastComposedWord.deactivate();
// Space state must be updated before calling updateShiftState
mSpaceState = SPACE_STATE_PHANTOM;
mKeyboardSwitcher.updateShiftState();
// We should show the "Touch again to save" hint if the user pressed the first entry
// AND it's in none of our current dictionaries (main, user or otherwise).
// Please note that if mSuggest is null, it means that everything is off: suggestion
// and correction, so we shouldn't try to show the hint
final boolean showingAddToDictionaryHint = index == 0 && mSuggest != null
// If the suggestion is not in the dictionary, the hint should be shown.
&& !AutoCorrection.isValidWord(mSuggest.getUnigramDictionaries(), suggestion, true);
if (ProductionFlag.IS_INTERNAL) {
Stats.onSeparator((char)Keyboard.CODE_SPACE,
Constants.NOT_A_COORDINATE, Constants.NOT_A_COORDINATE);
}
if (showingAddToDictionaryHint && mIsUserDictionaryAvailable) {
mSuggestionStripView.showAddToDictionaryHint(
suggestion, mCurrentSettings.mHintToSaveText);
} else {
// If we're not showing the "Touch again to save", then update the suggestion strip.
mHandler.postUpdateSuggestionStrip();
}
}
/**
* Commits the chosen word to the text field and saves it for later retrieval.
*/
private void commitChosenWord(final CharSequence chosenWord, final int commitType,
final String separatorString) {
final SuggestedWords suggestedWords = mSuggestionStripView.getSuggestions();
mConnection.commitText(SuggestionSpanUtils.getTextWithSuggestionSpan(
this, chosenWord, suggestedWords, mIsMainDictionaryAvailable), 1);
// Add the word to the user history dictionary
final CharSequence prevWord = addToUserHistoryDictionary(chosenWord);
// TODO: figure out here if this is an auto-correct or if the best word is actually
// what user typed. Note: currently this is done much later in
// LastComposedWord#didCommitTypedWord by string equality of the remembered
// strings.
mLastComposedWord = mWordComposer.commitWord(commitType, chosenWord.toString(),
separatorString, prevWord);
}
private void setPunctuationSuggestions() {
if (mCurrentSettings.mBigramPredictionEnabled) {
clearSuggestionStrip();
} else {
setSuggestionStrip(mCurrentSettings.mSuggestPuncList, false);
}
setAutoCorrectionIndicator(false);
setSuggestionStripShown(isSuggestionsStripVisible());
}
private CharSequence addToUserHistoryDictionary(final CharSequence suggestion) {
if (TextUtils.isEmpty(suggestion)) return null;
if (mSuggest == null) return null;
// If correction is not enabled, we don't add words to the user history dictionary.
// That's to avoid unintended additions in some sensitive fields, or fields that
// expect to receive non-words.
if (!mCurrentSettings.mCorrectionEnabled) return null;
final UserHistoryDictionary userHistoryDictionary = mUserHistoryDictionary;
if (userHistoryDictionary != null) {
final CharSequence prevWord
= mConnection.getNthPreviousWord(mCurrentSettings.mWordSeparators, 2);
final String secondWord;
if (mWordComposer.wasAutoCapitalized() && !mWordComposer.isMostlyCaps()) {
secondWord = suggestion.toString().toLowerCase(
mSubtypeSwitcher.getCurrentSubtypeLocale());
} else {
secondWord = suggestion.toString();
}
// We demote unrecognized words (frequency < 0, below) by specifying them as "invalid".
// We don't add words with 0-frequency (assuming they would be profanity etc.).
final int maxFreq = AutoCorrection.getMaxFrequency(
mSuggest.getUnigramDictionaries(), suggestion);
if (maxFreq == 0) return null;
userHistoryDictionary.addToUserHistory(null == prevWord ? null : prevWord.toString(),
secondWord, maxFreq > 0);
return prevWord;
}
return null;
}
/**
* Check if the cursor is actually at the end of a word. If so, restart suggestions on this
* word, else do nothing.
*/
private void restartSuggestionsOnWordBeforeCursorIfAtEndOfWord() {
final CharSequence word = mConnection.getWordBeforeCursorIfAtEndOfWord(mCurrentSettings);
if (null != word) {
restartSuggestionsOnWordBeforeCursor(word);
}
}
private void restartSuggestionsOnWordBeforeCursor(final CharSequence word) {
mWordComposer.setComposingWord(word, mKeyboardSwitcher.getKeyboard());
final int length = word.length();
mConnection.deleteSurroundingText(length, 0);
mConnection.setComposingText(word, 1);
mHandler.postUpdateSuggestionStrip();
}
private void revertCommit() {
final CharSequence previousWord = mLastComposedWord.mPrevWord;
final String originallyTypedWord = mLastComposedWord.mTypedWord;
final CharSequence committedWord = mLastComposedWord.mCommittedWord;
final int cancelLength = committedWord.length();
final int separatorLength = LastComposedWord.getSeparatorLength(
mLastComposedWord.mSeparatorString);
// TODO: should we check our saved separator against the actual contents of the text view?
final int deleteLength = cancelLength + separatorLength;
if (DEBUG) {
if (mWordComposer.isComposingWord()) {
throw new RuntimeException("revertCommit, but we are composing a word");
}
final String wordBeforeCursor =
mConnection.getTextBeforeCursor(deleteLength, 0)
.subSequence(0, cancelLength).toString();
if (!TextUtils.equals(committedWord, wordBeforeCursor)) {
throw new RuntimeException("revertCommit check failed: we thought we were "
+ "reverting \"" + committedWord
+ "\", but before the cursor we found \"" + wordBeforeCursor + "\"");
}
}
mConnection.deleteSurroundingText(deleteLength, 0);
if (!TextUtils.isEmpty(previousWord) && !TextUtils.isEmpty(committedWord)) {
mUserHistoryDictionary.cancelAddingUserHistory(
previousWord.toString(), committedWord.toString());
}
mConnection.commitText(originallyTypedWord + mLastComposedWord.mSeparatorString, 1);
if (ProductionFlag.IS_INTERNAL) {
Stats.onSeparator(mLastComposedWord.mSeparatorString,
Constants.NOT_A_COORDINATE, Constants.NOT_A_COORDINATE);
}
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_revertCommit(originallyTypedWord);
}
// Don't restart suggestion yet. We'll restart if the user deletes the
// separator.
mLastComposedWord = LastComposedWord.NOT_A_COMPOSED_WORD;
// We have a separator between the word and the cursor: we should show predictions.
mHandler.postUpdateSuggestionStrip();
}
// Used by the RingCharBuffer
public boolean isWordSeparator(final int code) {
return mCurrentSettings.isWordSeparator(code);
}
// TODO: Make this private
// Outside LatinIME, only used by the {@link InputTestsBase} test suite.
/* package for test */
void loadKeyboard() {
// When the device locale is changed in SetupWizard etc., this method may get called via
// onConfigurationChanged before SoftInputWindow is shown.
initSuggest();
loadSettings();
if (mKeyboardSwitcher.getMainKeyboardView() != null) {
// Reload keyboard because the current language has been changed.
mKeyboardSwitcher.loadKeyboard(getCurrentInputEditorInfo(), mCurrentSettings);
}
// Since we just changed languages, we should re-evaluate suggestions with whatever word
// we are currently composing. If we are not composing anything, we may want to display
// predictions or punctuation signs (which is done by the updateSuggestionStrip anyway).
mHandler.postUpdateSuggestionStrip();
}
// TODO: Remove this method from {@link LatinIME} and move {@link FeedbackManager} to
// {@link KeyboardSwitcher}. Called from KeyboardSwitcher
public void hapticAndAudioFeedback(final int primaryCode) {
mFeedbackManager.hapticAndAudioFeedback(
primaryCode, mKeyboardSwitcher.getMainKeyboardView());
}
// Callback called by PointerTracker through the KeyboardActionListener. This is called when a
// key is depressed; release matching call is onReleaseKey below.
@Override
public void onPressKey(final int primaryCode) {
mKeyboardSwitcher.onPressKey(primaryCode);
}
// Callback by PointerTracker through the KeyboardActionListener. This is called when a key
// is released; press matching call is onPressKey above.
@Override
public void onReleaseKey(final int primaryCode, final boolean withSliding) {
mKeyboardSwitcher.onReleaseKey(primaryCode, withSliding);
// If accessibility is on, ensure the user receives keyboard state updates.
if (AccessibilityUtils.getInstance().isTouchExplorationEnabled()) {
switch (primaryCode) {
case Keyboard.CODE_SHIFT:
AccessibleKeyboardViewProxy.getInstance().notifyShiftState();
break;
case Keyboard.CODE_SWITCH_ALPHA_SYMBOL:
AccessibleKeyboardViewProxy.getInstance().notifySymbolsState();
break;
}
}
if (Keyboard.CODE_DELETE == primaryCode) {
// This is a stopgap solution to avoid leaving a high surrogate alone in a text view.
// In the future, we need to deprecate deteleSurroundingText() and have a surrogate
// pair-friendly way of deleting characters in InputConnection.
final CharSequence lastChar = mConnection.getTextBeforeCursor(1, 0);
if (!TextUtils.isEmpty(lastChar) && Character.isHighSurrogate(lastChar.charAt(0))) {
mConnection.deleteSurroundingText(1, 0);
}
}
}
// receive ringer mode change and network state change.
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
final String action = intent.getAction();
if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
mSubtypeSwitcher.onNetworkStateChanged(intent);
} else if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) {
mFeedbackManager.onRingerModeChanged();
}
}
};
private void launchSettings() {
handleClose();
launchSubActivity(SettingsActivity.class);
}
// Called from debug code only
public void launchDebugSettings() {
handleClose();
launchSubActivity(DebugSettingsActivity.class);
}
public void launchKeyboardedDialogActivity(final Class<? extends Activity> activityClass) {
// Put the text in the attached EditText into a safe, saved state before switching to a
// new activity that will also use the soft keyboard.
commitTyped(LastComposedWord.NOT_A_SEPARATOR);
launchSubActivity(activityClass);
}
private void launchSubActivity(final Class<? extends Activity> activityClass) {
Intent intent = new Intent();
intent.setClass(LatinIME.this, activityClass);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
private void showSubtypeSelectorAndSettings() {
final CharSequence title = getString(R.string.english_ime_input_options);
final CharSequence[] items = new CharSequence[] {
// TODO: Should use new string "Select active input modes".
getString(R.string.language_selection_title),
getString(R.string.english_ime_settings),
};
final Context context = this;
final DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface di, int position) {
di.dismiss();
switch (position) {
case 0:
Intent intent = CompatUtils.getInputLanguageSelectionIntent(
ImfUtils.getInputMethodIdOfThisIme(context),
Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
break;
case 1:
launchSettings();
break;
}
}
};
final AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setItems(items, listener)
.setTitle(title);
showOptionDialog(builder.create());
}
public void showOptionDialog(final AlertDialog dialog) {
final IBinder windowToken = mKeyboardSwitcher.getMainKeyboardView().getWindowToken();
if (windowToken == null) {
return;
}
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
final Window window = dialog.getWindow();
final WindowManager.LayoutParams lp = window.getAttributes();
lp.token = windowToken;
lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
window.setAttributes(lp);
window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
mOptionsDialog = dialog;
dialog.show();
}
public void debugDumpStateAndCrashWithException(final String context) {
final StringBuilder s = new StringBuilder();
s.append("Target application : ").append(mTargetApplicationInfo.name)
.append("\nPackage : ").append(mTargetApplicationInfo.packageName)
.append("\nTarget app sdk version : ")
.append(mTargetApplicationInfo.targetSdkVersion)
.append("\nAttributes : ").append(mCurrentSettings.getInputAttributesDebugString())
.append("\nContext : ").append(context);
throw new RuntimeException(s.toString());
}
@Override
protected void dump(final FileDescriptor fd, final PrintWriter fout, final String[] args) {
super.dump(fd, fout, args);
final Printer p = new PrintWriterPrinter(fout);
p.println("LatinIME state :");
final Keyboard keyboard = mKeyboardSwitcher.getKeyboard();
final int keyboardMode = keyboard != null ? keyboard.mId.mMode : -1;
p.println(" Keyboard mode = " + keyboardMode);
p.println(" mIsSuggestionsSuggestionsRequested = "
+ mCurrentSettings.isSuggestionsRequested(mDisplayOrientation));
p.println(" mCorrectionEnabled=" + mCurrentSettings.mCorrectionEnabled);
p.println(" isComposingWord=" + mWordComposer.isComposingWord());
p.println(" mSoundOn=" + mCurrentSettings.mSoundOn);
p.println(" mVibrateOn=" + mCurrentSettings.mVibrateOn);
p.println(" mKeyPreviewPopupOn=" + mCurrentSettings.mKeyPreviewPopupOn);
p.println(" inputAttributes=" + mCurrentSettings.getInputAttributesDebugString());
}
}
| false | false | null | null |
diff --git a/src/java/com/idega/block/importer/business/ImportBusinessBean.java b/src/java/com/idega/block/importer/business/ImportBusinessBean.java
index 0a9741b..6ff4e10 100644
--- a/src/java/com/idega/block/importer/business/ImportBusinessBean.java
+++ b/src/java/com/idega/block/importer/business/ImportBusinessBean.java
@@ -1,465 +1,475 @@
package com.idega.block.importer.business;
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.rmi.RemoteException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.ejb.CreateException;
import javax.ejb.FinderException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;
import com.idega.block.importer.data.ImportFile;
import com.idega.block.importer.data.ImportFileClass;
import com.idega.block.importer.data.ImportFileClassHome;
import com.idega.block.importer.data.ImportHandler;
import com.idega.block.importer.data.ImportHandlerHome;
import com.idega.business.IBOService;
import com.idega.business.IBOServiceBean;
import com.idega.business.IBOSession;
import com.idega.core.file.data.ICFile;
import com.idega.core.file.data.ICFileHome;
import com.idega.data.IDOLookup;
import com.idega.idegaweb.IWUserContext;
import com.idega.presentation.IWContext;
import com.idega.presentation.ui.DropdownMenu;
import com.idega.repository.data.RefactorClassRegistry;
import com.idega.user.business.GroupBusiness;
import com.idega.util.IWTimestamp;
import com.idega.util.expression.ELUtil;
import com.idega.util.text.TextSoap;
/**
* <p>
* Title: IdegaWeb classes
* </p>
* <p>
* Description:
* </p>
* <p>
* Copyright: Copyright (c) 2002
* </p>
* <p>
* Company: Idega Software
* </p>
*
* @author <a href="mailto:[email protected]"> Eirikur Sveinn Hrafnsson</a>
* @version 1.0
*/
public class ImportBusinessBean extends IBOServiceBean implements ImportBusiness {
public ImportBusinessBean() {
}
/**
* @see com.idega.block.importer.business.ImportBusiness#getImportHandlers()
*/
public Collection getImportHandlers() throws RemoteException {
Collection col = null;
try {
col = ((ImportHandlerHome) this.getIDOHome(ImportHandler.class)).findAllImportHandlers();
}
catch (FinderException e) {
}
return col;
}
/**
* @see com.idega.block.importer.business.ImportBusiness#getImportFileTypes()
*/
public Collection getImportFileTypes() throws RemoteException {
Collection col = null;
try {
col = ((ImportFileClassHome) this.getIDOHome(ImportFileClass.class)).findAllImportFileClasses();
}
catch (FinderException e) {
}
return col;
}
/**
* @see com.idega.block.importer.business.ImportBusiness#importRecords(String,
* String, String, Integer)
*/
public boolean importRecords(String handlerClass, String fileClass, String filePath, Integer groupId, IWUserContext iwuc, List failedRecords) throws RemoteException {
return importRecords(handlerClass, fileClass, filePath, groupId, iwuc, failedRecords, null);
}
/**
* @see com.idega.block.importer.business.ImportBusiness#importRecords(String,
* String, String, Integer)
*/
public boolean importRecords(String handlerClass, String fileClass, String filePath, Integer groupId, IWUserContext iwuc, List failedRecords, List successRecords) throws RemoteException {
try {
boolean status = false;
ImportFileHandler handler = this.getImportFileHandler(handlerClass, iwuc);
ImportFile file = this.getImportFile(fileClass);
file.setFile(new File(filePath));
handler.setImportFile(file);
handler.setRootGroup(getGroupBusiness().getGroupByGroupID(groupId.intValue()));
status = handler.handleRecords();
failedRecords.addAll(handler.getFailedRecords());
successRecords.addAll(handler.getSuccessRecords());
return status;
}
catch (NoRecordsException ex) {
ex.printStackTrace();
return false;
}
catch (Exception ex) {
ex.printStackTrace();
return false;
}
}
/**
* @see com.idega.block.importer.business.ImportBusiness#importRecords(String,
* String, String)
*/
public boolean importRecords(String handlerClass, String fileClass, String filePath, IWUserContext iwuc, List failedRecords) throws RemoteException {
return importRecords(handlerClass, fileClass, filePath, iwuc, failedRecords, null);
}
/**
* @see com.idega.block.importer.business.ImportBusiness#importRecords(String,
* String, String)
*/
public boolean importRecords(String handlerClass, String fileClass, String filePath, IWUserContext iwuc, List failedRecords, List successRecords) throws RemoteException {
try {
boolean status = false;
ImportFileHandler handler = this.getImportFileHandler(handlerClass, iwuc);
ImportFile file = this.getImportFile(fileClass);
file.setFile(new File(filePath));
handler.setImportFile(file);
status = handler.handleRecords();
failedRecords.addAll(handler.getFailedRecords());
List success = handler.getSuccessRecords();
if (success != null) {
successRecords.addAll(success);
}
return status;
}
catch (NoRecordsException ex) {
ex.printStackTrace();
return false;
}
catch (Exception ex) {
ex.printStackTrace();
return false;
}
}
public GroupBusiness getGroupBusiness() throws Exception {
return (GroupBusiness) this.getServiceInstance(GroupBusiness.class);
}
public ImportFileHandler getImportFileHandler(String handlerClass, IWUserContext iwuc) throws Exception {
Class importHandlerInterfaceClass = RefactorClassRegistry.forName(handlerClass);
Class[] interfaces = importHandlerInterfaceClass.getInterfaces();
boolean isSessionBean = false;
boolean isServiceBean = false;
for (int i = 0; i < interfaces.length; i++) {
Class class1 = interfaces[i];
if (class1.equals(IBOSession.class)) {
isSessionBean = true;
}
if (class1.equals(IBOService.class)) {
isServiceBean = true;
}
}
ImportFileHandler handler = null;
if (isSessionBean) {
handler = (ImportFileHandler) getSessionInstance(iwuc, importHandlerInterfaceClass);
}
else if (isServiceBean) {
handler = (ImportFileHandler) getServiceInstance(importHandlerInterfaceClass);
}
else {
Service bname = (Service) importHandlerInterfaceClass.getAnnotation(Service.class);
if (bname != null) {
handler = (ImportFileHandler) ELUtil.getInstance().getBean(bname.value());
}
}
if (handler == null) {
handler = (ImportFileHandler) getServiceInstance(importHandlerInterfaceClass);
}
return handler;
}
public ImportFile getImportFile(String fileClass) throws Exception {
return (ImportFile) RefactorClassRegistry.forName(fileClass).newInstance();
}
public DropdownMenu getImportHandlers(IWContext iwc, String name) throws RemoteException {
DropdownMenu menu = new DropdownMenu(name);
Collection col = getImportHandlers();
Iterator iter = col.iterator();
while (iter.hasNext()) {
ImportHandler element = (ImportHandler) iter.next();
menu.addMenuElement(element.getClassName(), element.getName());
}
return menu;
}
public DropdownMenu getImportFileClasses(IWContext iwc, String name) throws RemoteException {
DropdownMenu menu = new DropdownMenu(name);
Collection col = getImportFileTypes();
Iterator iter = col.iterator();
while (iter.hasNext()) {
ImportFileClass element = (ImportFileClass) iter.next();
menu.addMenuElement(element.getClassName(), element.getName());
}
return menu;
}
public ICFile getReportFolder(String importFileName, boolean createIfNotFound) throws RemoteException, CreateException {
String reportFilename = importFileName;
int i = reportFilename.indexOf('_');
if (i > 0) {
reportFilename = reportFilename.substring(i + 1);
}
// i = reportFilename.lastIndexOf('.');
// if(i>0)
// {
// reportFilename = reportFilename.substring(0,i);
// }
reportFilename = reportFilename + ".report";
ICFile reportFile = null;
ICFileHome fileHome = (ICFileHome) IDOLookup.getHome(ICFile.class);
try {
reportFile = fileHome.findByFileName(reportFilename);
return reportFile;
}
catch (FinderException e) {
if (createIfNotFound) {
reportFile = fileHome.create();
reportFile.setName(reportFilename);
reportFile.setCreationDate(IWTimestamp.getTimestampRightNow());
reportFile.store();
return reportFile;
}
}
return null;
}
public void addReport(File importFile, File reportFile) throws RemoteException, CreateException {
boolean replace = true;
ICFile folder = getReportFolder(importFile.getName(), true);
ICFile report;
ICFileHome fileHome = (ICFileHome) IDOLookup.getHome(ICFile.class);
- BufferedInputStream bis;
+ BufferedInputStream bis = null;
try {
bis = new BufferedInputStream(new FileInputStream(reportFile));
report = fileHome.create();
report.setName(reportFile.getName());
report.setFileValue(bis);
report.setCreationDate(IWTimestamp.getTimestampRightNow());
report.store();
if (replace) {
Iterator children = folder.getChildrenIterator();
ICFile child = null;
boolean found = false;
while (children != null && children.hasNext() && !found) {
child = (ICFile) children.next();
found = child.getName().equals(reportFile.getName());
}
if (found && child != null) {
folder.removeChild(child);
}
}
folder.addChild(report);
}
catch (FileNotFoundException e1) {
e1.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
+ finally {
+ if (bis != null) {
+ try {
+ bis.close();
+ }
+ catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ }
}
/**
* Creates a text file and adds it the the importFile. Each collection element
* should contain a single Objecet or a colleciton of objects.
*
* @param separator
* @param data
* Collection containing Collection
*/
public void addReport(File importFile, String name, Collection data, String separator) throws RemoteException, CreateException {
File report = getReport(importFile.getName() + "_" + name, data, separator);
addReport(importFile, report);
report.delete();
}
/**
* Creates an excel file and adds it the the importFile. Each collection
* element should contain a single Objecet or a colleciton of objects.
*
* @param separator
* @param data
* Collection containing Collection
*/
public void addExcelReport(File importFile, String name, Collection data, String separator) throws RemoteException, CreateException {
File report = getExcelReport(importFile.getName() + "_" + name + ".xls", data, separator);
addReport(importFile, report);
report.delete();
}
/**
* Creates a text file with separated columns. Each collection element should
* contain the data for a single line. Note. this does NOT add the report to
* the importFile, use addReport for that.
*
* @param name
* Name of the file, with full path
* @param data
* Collection containing Collection
* @param separator
*/
public File getReport(String name, Collection data, String separator) {
if (data != null && !data.isEmpty()) {
File file = new File(name);
try {
file.createNewFile();
BufferedWriter output = null;
try {
output = new BufferedWriter(new FileWriter(file));
Iterator iter = data.iterator();
Object obj;
while (iter.hasNext()) {
obj = iter.next();
if (obj instanceof String) {
output.write(obj.toString());
}
else if (obj instanceof Collection && obj != null) {
Iterator iter2 = ((Collection) obj).iterator();
String string = null;
while (iter2.hasNext()) {
string = iter2.next().toString();
if (!string.trim().equals("")) {
output.write(string);
output.write(separator);
}
}
}
output.newLine();
}
}
finally {
if (output != null) {
output.close();
}
}
return file;
}
catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* Creates an excel file with separated columns. Each collection element
* should contain the data for a single line. Note. this does NOT add the
* report to the importFile, use addReport for that.
*
* @param name
* Name of the file, with full path
* @param data
* Collection containing Collection
* @param separator
*/
public File getExcelReport(String name, Collection data, String separator) {
if (data != null && !data.isEmpty()) {
try {
HSSFWorkbook wb = new HSSFWorkbook();
File file = null;
try {
HSSFSheet sheet = wb.createSheet(TextSoap.encodeToValidExcelSheetName(name));
int rowIndex = 0;
Iterator iter = data.iterator();
Object obj;
int cellRow = 0;
while (iter.hasNext()) {
HSSFRow row = sheet.createRow((short) rowIndex++);
cellRow = 0;
obj = iter.next();
if (obj instanceof String) {
HSSFCell cell = row.createCell((short) cellRow++);
cell.setCellValue(obj.toString());
}
else if (obj instanceof Collection && obj != null) {
Iterator iter2 = ((Collection) obj).iterator();
String string = null;
while (iter2.hasNext()) {
string = iter2.next().toString();
if (!string.trim().equals("")) {
HSSFCell cell = row.createCell((short) cellRow++);
cell.setCellValue(string);
if (separator != null && separator.equalsIgnoreCase("\n")) {
cellRow = 0;
row = sheet.createRow((short) rowIndex++);
}
}
}
}
}
}
finally {
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream(name);
wb.write(fileOut);
fileOut.close();
file = new File(name);
// if (output != null) output.close();
}
return file;
}
catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
\ No newline at end of file
diff --git a/src/java/com/idega/block/importer/data/ExcelImportFile.java b/src/java/com/idega/block/importer/data/ExcelImportFile.java
index eaccda4..f9e8d34 100644
--- a/src/java/com/idega/block/importer/data/ExcelImportFile.java
+++ b/src/java/com/idega/block/importer/data/ExcelImportFile.java
@@ -1,119 +1,130 @@
package com.idega.block.importer.data;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import com.idega.block.importer.business.NoRecordsException;
import com.idega.util.CoreConstants;
import com.idega.util.Timer;
public class ExcelImportFile extends GenericImportFile {
private Iterator iter;
@Override
public Object getNextRecord() {
if (iter == null) {
Collection records = getAllRecords();
if (records != null) {
iter = records.iterator();
}
}
if (iter != null) {
while (iter.hasNext()) {
return iter.next();
}
}
return "";
}
public Collection getAllRecords() throws NoRecordsException {
+ FileInputStream input = null;
try {
- FileInputStream input = new FileInputStream(getFile());
+ input = new FileInputStream(getFile());
HSSFWorkbook wb = new HSSFWorkbook(input);
HSSFSheet sheet = wb.getSheetAt(0);
int records = 0;
Timer clock = new Timer();
clock.start();
StringBuffer buffer = new StringBuffer();
ArrayList list = new ArrayList();
for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
HSSFRow row = sheet.getRow(i);
if (buffer == null) {
buffer = new StringBuffer();
}
if (row != null) {
for (short j = row.getFirstCellNum(); j < row.getLastCellNum(); j++) {
HSSFCell cell = row.getCell(j);
if (cell != null) {
if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
buffer.append(cell.getStringCellValue());
} else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
buffer.append(cell.getNumericCellValue());
} else if (cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA) {
switch (cell.getCachedFormulaResultType()) {
case HSSFCell.CELL_TYPE_NUMERIC: {
buffer.append(cell.getNumericCellValue());
break;
}
case HSSFCell.CELL_TYPE_STRING: {
buffer.append(cell.getStringCellValue());
break;
}
case HSSFCell.CELL_TYPE_BLANK: {
buffer.append(CoreConstants.EMPTY);
break;
}
case HSSFCell.CELL_TYPE_BOOLEAN: {
buffer.append(cell.getBooleanCellValue());
break;
}
}
} else {
buffer.append(cell.getStringCellValue());
}
}
buffer.append(getValueSeparator());
}
records++;
if ((records % 1000) == 0) {
System.out.println("Importer: Reading record nr.: " + records + " from file " + getFile().getName());
}
list.add(buffer.toString());
buffer = null;
}
}
if (records == 0) {
throw new NoRecordsException("No records where found in the selected file" + getFile().getAbsolutePath());
}
return list;
}
catch (FileNotFoundException ex) {
ex.printStackTrace(System.err);
return null;
}
catch (IOException ex) {
ex.printStackTrace(System.err);
return null;
}
+ finally {
+ if (input != null) {
+ try {
+ input.close();
+ }
+ catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ }
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/gdxtest02/src/com/gdxtest02/Balance.java b/gdxtest02/src/com/gdxtest02/Balance.java
index 01c4911..041a905 100644
--- a/gdxtest02/src/com/gdxtest02/Balance.java
+++ b/gdxtest02/src/com/gdxtest02/Balance.java
@@ -1,766 +1,766 @@
package com.gdxtest02;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.utils.Array;
public class Balance {
private static final int TEST_DAMAGE = 0;
private static final int TEST_HEAL = 1;
private static final int TEST_DMGHEAL = 2;
Char player;
private int totaldmg;
private float bestdmg;
private Array<Integer> bestcombo;
private TestResult testresult;
private int numberofbests;
/**Array of Lists of how much damage each skill does each round
* if there are 4 skills, there will be 4 lists, one for each round
* each list will have how much damage that skill does on each round
* if there are 10 rounds, that list will have 10 items
*/
private Array<Array<Float>> listsof_damageperskill;
/**A list of the difference in damage between the best damage skill
* and the second best, for each round
*/
private Array<Float> listof_damagediff;
/**List of the ids of the skill that does the most dmg this round
*
*/
private Array<Integer> listof_bestdmgid;
private int maxrounds;
private float bestheal;
private float bestdmgheal;
// private int whattotest;
public Balance(Char c) {
player = c;
}
public float getAvgDps() {
float total = 0;
for (Action a : player.actions) {
total += a.getAvgDps();
}
return total;
}
/**Model 1: Dps vs Dps
*
* 1000 damage in 10 rounds
*/
public void testModel1() {
testDmgModelA(10, 1000, 0);
testDmgModelA(10, 1000, 1);
}
/** Model 2: Dps vs Healer
*
* 1500 in 15 rounds
*/
public void testModel2() {
testDmgModelA(15, 1500, 0);
testDmgModelA(15, 1500, 1);
}
/** Model 3: Healer vs Dps if he heals
*
* 1000 dmg in 15 rounds, heal 500 in 15 rounds
*/
public void testModel3() {
testDmgAndHeal(15, 1000f, 500f);
}
private void testDmgAndHeal(int maxrounds, float damage, float heal) {
-// testTree(maxrounds, TEST_DAMAGE);
-// printTestResults();
-// testTree(maxrounds, TEST_HEAL);
-// printTestResults();
+ testTree(maxrounds, TEST_DAMAGE);
+ printTestResults();
+ testTree(maxrounds, TEST_HEAL);
+ printTestResults();
testTree(maxrounds, TEST_DMGHEAL);
printTestResults();
Array<Integer> skillsthatdodmg = new Array<Integer>();
Array<Integer> skillsthatheal = new Array<Integer>();
skillsthatdodmg = getSkillsThatDoDmg();
}
private Array<Integer> getSkillsThatDoDmg() {
Array<Integer> list = new Array<Integer>();
for (Action a : player.actions) {
if (a.getDmgAfterRounds(10) > 0) {
list.add(player.getIdOfAction(a));
}
}
return null;
}
// TODO check for abilities with only 1 ability with a large cooldown
public void testDmgModelA(int maxrounds, float targetdamage, int type) {
log("testing model 1 on char " + player.getName());
this.maxrounds = maxrounds;
testresult = new TestResult();
if (type == 0) {
log("doing best combo test");
testresult = testBestCombo(maxrounds);
}
else if (type == 1) {
log("doing tree test");
// testresult = testTree(maxrounds);
testTree(maxrounds, TEST_DAMAGE);
}
else {
log("doing brute force test");
testresult = testAllCombinations(maxrounds);
}
printTestResults();
int bestdmg = testresult.getBestdmg();
if (bestdmg > 0) {
float ratio = targetdamage/bestdmg;
fixDmgByRatio(player, ratio);
}
}
/**Prints test results on log
*
* @param maxrounds
* @return
*/
private void printTestResults() {
int bestdmg = testresult.getBestdmg();
Array<Integer> bestcombo = testresult.getBestcombo();
int numberofbests = testresult.getNumberofbests();
log("test over, best dmgheal: " + bestdmgheal + " best dmg: " + bestdmg + " best heal: " + bestheal + " combo: " + bestcombo
+ " number of bests: " + numberofbests);
int numberofskills = player.actions.size;
int totalsize = (int)Math.pow(numberofskills, maxrounds);
float pct = 100f*totaldmg/totalsize;
log("total loops: " + totaldmg + " of " + totalsize + " (" + pct + "%)");
}
/**Build a game tree to find the best combo
* @param maxrounds
* @return
*/
private void testTree(int maxrounds, int whattotest) {
// prepare for calculations
int round = 1;
// this.whattotest = whattotest;
prepareTest();
Array<Integer> combo = new Array<Integer>();
buildListsOfDamagesPerSkill(maxrounds, whattotest);
// Start:
loopToNextBranches(maxrounds, round, combo, whattotest);
}
/**Initializes and resets the variables common to all tests
*
*/
private void prepareTest() {
totaldmg = 0;
bestdmg = 0;
bestheal = 0;
bestdmgheal = 0;
numberofbests = 0;
bestcombo = new Array<Integer>();
}
/**Build lists of how much damage each skill does each round
* and a list of the difference between the highest dmg skill
* and the second, records them on listsof_damageperskill
* and listof_damagediff
* @param maxrounds
* @param whattotest
*/
private void buildListsOfDamagesPerSkill(int maxrounds, int whattotest) {
listsof_damageperskill = new Array<Array<Float>>();
listof_damagediff = new Array<Float>();
listof_bestdmgid = new Array<Integer>();
int numberofskills = player.actions.size;
float dmg;
for (int id = 1; id <= numberofskills; id++) {
Action a = player.getAction(id);
Array<Float> damagelist = new Array<Float>();
listsof_damageperskill.add(damagelist);
for (int round = 1; round <= maxrounds; round++) {
dmg = getOutputOfAction(a, round, maxrounds, whattotest);
damagelist.add(dmg);
}
}
log("lists of dmg: " + listsof_damageperskill);
// build list of differences
float best; float second; float delta; int id;
float[] array;
for (int round = 1; round <= maxrounds; round++) {
array = getBestDmgThisRound(round);
best = array[0];
second = array[1];
id = (int) array[2];
delta = best - second;
listof_damagediff.add(delta);
listof_bestdmgid.add(id);
}
log("list of delta: " + listof_damagediff);
log("list of best dmg ids: " + listof_bestdmgid);
}
private float getOutputOfAction(Action a, int round, int maxrounds, int whattotest) {
float total = 0;
if (whattotest == TEST_DAMAGE || whattotest == TEST_DMGHEAL) total += a.getDmgThisRound(round, maxrounds);
if (whattotest == TEST_HEAL || whattotest == TEST_DMGHEAL) total += a.getHealThisRound(round, maxrounds);
return total;
}
/**Returns 3 values, first is the best dmg this round, second is the second best
* third is the best dmg id
* @param round
* @return
*/
private float[] getBestDmgThisRound(int round) {
int numberofskills = player.actions.size;
// if (numberofskills == 1) return listsof_damageperskill.get(0).get(round);
float best = 0; float second = 0; float dmg; int id = 0;
for (int i = 0; i < numberofskills; i++) {
dmg = listsof_damageperskill.get(i).get(round-1);
if (dmg > best) {
second = best;
best = dmg;
id = i + 1;
}
else if (dmg > second) {
second = dmg;
}
}
float[] array = {best, second, id};
return array;
}
/**Loop through all next branches
*
* o
* [/ | \] -> You are here
* o o o
*
* @param round
* @param maxrounds
* @param combo
* @param whattotest
*/
private void loopToNextBranches(int maxrounds, int round, Array<Integer> combo, int whattotest) {
// log("looping on round: " + round + "/" + maxrounds);
int numberofskills = player.actions.size;
for (int id = 1; id < numberofskills + 1; id++) {
Action a = player.getAction(id);
nextBranch(a, maxrounds, round, combo, whattotest);
}
}
/**Calculate the next branch on the game tree
*
* o
* / |[\] -> You are here
* o o o
*
* @param a
* @param round
* @param maxrounds
* @param combo
* @param whattotest
*/
private void nextBranch(Action a, int maxrounds, int round, Array<Integer> combo, int whattotest) {
int id = player.getIdOfAction(a);
combo = new Array<Integer>(combo);
combo.add(id);
// log("branch: " + id + " combo so far: " + combo);
// Pruning goes here
// cooldown prune, stop trying this combo is the ccurrent skill is on cd
if (isThisSkillOnCooldown(a, round, combo)) {
// log("yes, skill " + id + " is on cd on combo: " + combo + " prunning");
return;
}
// // obvious best dmg prune
if (shouldIPruneForDmg(a, round, maxrounds, combo, whattotest)) {
// log("pruning for dmg, skill: " + id + " combo: " + combo);
return;
}
// Pruning ends here
round++;
if (round <= maxrounds) {
loopToNextBranches(maxrounds, round, combo, whattotest);
}
else {
// finish, success
float dmgheal = calculateDmgFromCombo(combo, whattotest);
float dmg = calculateDmgFromCombo(combo, TEST_DAMAGE);
float heal = calculateDmgFromCombo(combo, TEST_HEAL);
// log("and it's all over! Total loops: " + ++total + " combo: " + combo + " dmg: " +dmg);
totaldmg++;
addDmgToList(combo, dmgheal, dmg, heal);
buildTestResult();
}
}
/**Build together the test results and store them on the
* testresult object
*
*/
private void buildTestResult() {
testresult = new TestResult();
testresult.setBestdmg((int) bestdmg);
testresult.setBestcombo(bestcombo);
testresult.setNumberofbests(numberofbests);
}
/**Adds this damage and combo to the list of best ones, if it's one of the
* best ones
*
* @param combo
* @param dmgheal
*/
private void addDmgToList(Array<Integer> combo, float dmgheal, float dmg, float heal) {
if (dmgheal > bestdmgheal) {
bestdmgheal = dmgheal;
bestcombo = combo;
numberofbests = 0;
bestheal = heal;
bestdmg = dmg;
}
if (dmgheal == bestdmgheal) {
numberofbests++;
}
}
/**Tests if I should prune this branch for max dmg
*
* The basic idea here is that you are only not sure if the skill that does
* the most dmg is the best option, if using it later would put this in place
* of another skill that does less on different rounds (example, dots). If
* all skills in the foreseable future (the number of skills, so one doesn't
* get in place of another) do the same damage, then it's safe to
* just use the one with the most damage on this round, and you wouldn't have
* to think too hard about it.
*
* @param a
* @param round
* @param maxrounds
* @param combo
* @param whattotest
* @return true if pruning should be done, false otherwise
*/
private boolean shouldIPruneForDmg(Action a, int round, int maxrounds, Array<Integer> combo, int whattotest) {
// am I the strongest skill?
int id = player.getIdOfAction(a);
int bestavailable = getBestAvailable(combo, round, maxrounds, whattotest);
// log("combo: " + combo + " round: " + round + " id: " + id + " bestavailable: " + bestavailable);
- if (id == bestavailable) {
+ if (id == bestavailable || bestavailable == 0) {
return false;
}
// now I know I'm NOT the strongest available
// does the delta change in the near future?
int roundsleft = maxrounds - round + 1;
// how long should I look in the future?
// TODO take skill cooldown into account?
int lookupsize = player.actions.size-1;
lookupsize = Math.min(lookupsize, roundsleft);
float delta = listof_damagediff.get(round-1);
float newdelta = 0f;
for (int i = 0; i < lookupsize; i++) {
newdelta = listof_damagediff.get(round-1 + i);
if (newdelta != delta) {
// yes, delta does change in the near future
return false;
}
}
return true;
}
private int getBestAvailable(Array<Integer> combo, int round, int maxrounds, int whattotest) {
int roundsleft = maxrounds - round + 1;
int bestid = 0;
Action a;
float bestdmg = 0;
float dmg = 0;
for (int id = 1; id <= 4; id++) {
a = player.getAction(id);
if (a == null || isThisSkillOnCooldown(a, round, combo)) continue;
- dmg = a.getDmgAfterRounds(roundsleft);
+// dmg = a.getDmgAfterRounds(roundsleft);
dmg = getOutputOfAction(a, round, maxrounds, whattotest);
if (dmg > bestdmg) {
bestdmg = dmg;
bestid = id;
}
}
return bestid;
}
/**Calculates how much dmg a combshouldIPruneForDmgo does
* @param combo
* @param whattotest
* @return
*/
private float calculateDmgFromCombo(Array<Integer> combo, int whattotest) {
int maxrounds = combo.size;
if (maxrounds == 0) return 0;
float dmg = 0;
int id; Action a = null; int roundsleft;
for (int round = 1; round <= maxrounds; round++) {
id = combo.get(round-1);
a = player.getAction(id);
roundsleft = maxrounds - round + 1;
if (isThisSkillOnCooldown(a, round, combo)) {
// log("skill " + id + " is on cd on round " + round);
}
else {
// log("round: " + round + " left: " + roundsleft + " skill: " + id + " dmg: " + a.getDmgAfterRounds(roundsleft));
if (whattotest == TEST_DAMAGE || whattotest == TEST_DMGHEAL) dmg += a.getDmgAfterRounds(roundsleft);
if (whattotest == TEST_HEAL || whattotest == TEST_DMGHEAL) dmg += a.getHealAfterRounds(roundsleft);
}
}
// log("combo: " + combo + " dmg: " + dmg);
return dmg;
}
/**Will check if this skill is on cooldown (cannot be used)
* on this round if this combination
* is used
*
* @param a
* @param round
* @param combo
* @return
*/
private boolean isThisSkillOnCooldown(Action a, int round,
Array<Integer> combo) {
// log("checking if skill " + player.getIdOfAction(a) + " is on cd on round " + round);
if (round == 1) return false;
int cd = a.getCooldown();
int lastuse = lastTimeThisSkillWasUsed(a, round, combo);
if (lastuse == 0) return false;
int timesincelastuse = round - lastuse;
if (timesincelastuse <= cd) {
// log("yes");
return true;
}
else {
// log("no, cd: " + cd + " lastuse: " + lastuse + " timesince: " + timesincelastuse);
return false;
}
}
/**The last time this skill was used in this combination, before this
* specific round
*
* @param a
* @param round
* @param combo
* @return
*/
private int lastTimeThisSkillWasUsed(Action a, int round,
Array<Integer> combo) {
int id = player.getIdOfAction(a);
Array<Integer> combobefore = new Array<Integer>(combo);
combobefore.truncate(round - 1);
return combobefore.lastIndexOf(id, true) + 1;
// log("last use of: " + id + " combobefore: " + combobefore + " lastuse: " + lastuse);
}
/**Will do only 1 simulation trying to use only the best skills available at
* each round, then returns the results
*
* @param maxrounds
* @return
*/
private TestResult testBestCombo(int maxrounds) {
// prepare for simulation
Char dummy = new Char("dummy");
dummy.setMaxhp(100000);
int inihp = dummy.getMaxhp();
player.setTarget(dummy);
Array<Integer> combo = new Array<Integer>();
int dmg = 0;
player.resetStats();
dummy.resetStats();
int id = 1;
int roundsleft = maxrounds;
// start simulation
for (int round = 1; round <= maxrounds; round++) {
id = getNextBestSkill(player, roundsleft);
combo.add(id);
player.setActiveActionId(id);
player.updateAll();
dummy.updateAll();
dummy.applyDmg();
roundsleft--;
}
// simulation ended
// get damage done
dmg = (inihp - dummy.getHp());
// record results on a TestResult object and return it
TestResult testresult = new TestResult();
testresult.setBestdmg(dmg);
testresult.setBestcombo(combo);
testresult.setNumberofbests(1);
return testresult;
}
/**Returns what is the id of the best skill Char p can use,
* based on which one does the best damage until game is over
* and is off cooldown
*
* @param p
* @param roundsleft
* @return
*/
private int getNextBestSkill(Char p, int roundsleft) {
int bestid = 0;
Action a;
float bestdmg = 0;
float dmg = 0;
for (int id = 1; id <= 4; id++) {
a = p.getAction(id);
if (a == null || a.getCurcooldown() > 0) continue;
dmg = a.getDmgAfterRounds(roundsleft);
if (dmg > bestdmg) {
bestdmg = dmg;
bestid = id;
}
}
return bestid;
}
/**Build all possible combinations of combos with maxrounds duration,
* then will simulate all of them, then return the results
*
* @param maxrounds
* @return TestResult with best combo, dmg and number of bests
*/
private TestResult testAllCombinations(int maxrounds) {
Array<Array<Integer>> listofcombos = new Array<Array<Integer>>();
listofcombos = makeCombination(maxrounds, 4);
TestResult testresult = bruteForceAllCombos(maxrounds, listofcombos);
return testresult;
}
/**Takes a list of combos, then do simulations of all of them and return results
*
* @param maxrounds
* @param listofcombos
* @return
*/
private TestResult bruteForceAllCombos(int maxrounds,
Array<Array<Integer>> listofcombos) {
Char dummy = new Char("dummy");
dummy.setMaxhp(100000);
player.resetStats();
player.setTarget(dummy);
Array<Integer> bestcombo = new Array<Integer>();
int bestdmg = 0;
int dmg = 0;
int numberofbests = 0;
TestResult testresult = new TestResult();
for (Array<Integer> combo : listofcombos) {
dmg = getDmgFromCombo(maxrounds, dummy, combo);
// log("dmg: " + dmg + " bestdmg: " + bestdmg);
if (dmg > bestdmg) {
bestdmg = dmg;
bestcombo = combo;
numberofbests = 0;
}
if (dmg == bestdmg) {
numberofbests++;
}
}
testresult.setBestdmg(bestdmg);
testresult.setBestcombo(bestcombo);
testresult.setNumberofbests(numberofbests);
return testresult;
}
/**Do one simulation of a fight and return the damage done
*
* @param maxrounds
* @param dummy
* @param combo
* @return
*/
private int getDmgFromCombo(int maxrounds, Char dummy, Array<Integer> combo) {
Action a = null;
int dmg;
int inihp = dummy.getMaxhp();
// log("testing combo: " + combo.toString());
int id = 0;
player.resetStats();
dummy.resetStats();
for (int round = 1; round <= maxrounds; round++) {
try {id = combo.get(round-1);}
catch (Exception e) {log("out of bounds, no action to use this round");}
player.setActiveActionId(id);
a = player.getActiveAction();
// log("round: " + round);
// log("hp before: " + dummy.getHp());
// if (a != null) {
// log("using action: " + player.getActiveAction().getName());
// }
player.updateAll();
dummy.updateAll();
dummy.applyDmg();
// else log("action " + player.getActiveActionId() + "is null");
// log("hp after: " + dummy.getHp());
}
dmg = (inihp - dummy.getHp());
return dmg;
}
/**Suggests a fix to balance the player skills using ratio
*
* @param player
* @param ratio
*/
private void fixDmgByRatio(Char player, float ratio) {
int id = 1;
player.getAction(id);
Array<Float> skillsdmg = new Array<Float>();
for (id = 1; id <= 4; id++) {
Action a = player.getAction(id);
if (a != null) {
skillsdmg.add(a.getPower()*ratio);
}
else skillsdmg.add(0f);
}
log("ratio: " + ratio + " new skills: " + skillsdmg.toString());
}
private void addCombo2(int maxrounds, Array<Array<Integer>> listofcombos) {
int round;
Array<Integer> actioncombo2 = new Array<Integer>();
for (round = 1; round <= maxrounds; round++) {
actioncombo2.add(round%3+1);
}
listofcombos.add(actioncombo2);
}
private void addCombo1(int maxrounds, Array<Array<Integer>> listofcombos) {
int round;
Array<Integer> actioncombo = new Array<Integer>();
for (round = 1; round <= maxrounds; round++) {
actioncombo.add(2);
}
listofcombos.add(actioncombo);
}
private Array<Array<Integer>> makeCombination(int sizex, int sizey) {
Array<Array<Integer>> list = new Array<Array<Integer>>();
// int sizex = 10;
// int sizey = 4;
int[] loop = new int[sizex];
for (int i : loop) {
loop[i] = 0;
}
int i = 0;
recb(list, loop, sizex, sizey, i);
return list;
// log("list: " + list);
}
private void recb(Array<Array<Integer>> list, int[] loop, int sizex, int sizey, int i) {
while (i<Math.pow(sizey,sizex)) {
Array<Integer> combo = new Array<Integer>();
for (int p = 0; p < sizex; p++) {
combo.add(loop[p]+1);
}
// log("combo(" + i + "): " + combo);
list.add(combo);
for (int d = 0; d < sizex; d++) {
if (loop[d] < sizey - 1) {
loop[d]++;
if (d>0) {
for (int a = d; a > 0; a--) {
loop[a-1] = 0;
}
}
break;
}
}
i++;
}
}
private void rec(Array<Array<Integer>> list, int[] loop, int size, int i) {
int l = 0;
for (l = 0; l < size; l++) {
for (loop[l] = 0; loop[l] < size; loop[l]++) {
Array<Integer> combo = new Array<Integer>();
for (int p = 0; p < size; p++) {
combo.add(loop[p]);
}
// combo.add(c);
log("combo(" + i + "): " + combo);
list.add(combo);
i++;
}
}
}
private void reca(Array<Array<Integer>> list, int i, int c, int b) {
for (int a = 0; a < 3; a++) {
Array<Integer> combo = new Array<Integer>();
combo.add(a);
combo.add(b);
combo.add(c);
log("combo(" + i + "): " + combo);
list.add(combo);
i++;
}
}
/**Logs text to Gdx.app.log()
* @param text
*/
private void log(String text) {
Gdx.app.log("gdxtest", text);
}
}
| false | false | null | null |
diff --git a/app/src/processing/app/debug/Compiler.java b/app/src/processing/app/debug/Compiler.java
index bc5e5603..bad9feb8 100755
--- a/app/src/processing/app/debug/Compiler.java
+++ b/app/src/processing/app/debug/Compiler.java
@@ -1,858 +1,857 @@
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2004-08 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package processing.app.debug;
import processing.app.Base;
import processing.app.Preferences;
import processing.app.Sketch;
import processing.app.SketchCode;
import processing.core.*;
import java.io.*;
import java.util.*;
import java.util.zip.*;
import java.text.MessageFormat;
import org.apache.log4j.BasicConfigurator;
//import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.Logger;
import org.apache.log4j.Level;
public class Compiler implements MessageConsumer {
static Logger logger = Logger.getLogger(Base.class.getName());
static final String BUGS_URL = "http://code.google.com/p/arduino/issues/list";
static final String SUPER_BADNESS = "Compiler error, please submit this code to "
+ BUGS_URL;
Sketch sketch;
String buildPath;
String primaryClassName;
String platform;
boolean verbose;
String board;
//CommandRunner runner;
RunnerException exception;
HashMap<String, String> configPreferences;
Map<String, String> boardPreferences;
Map<String, String> platformPreferences;
Map<String, String> sketchPreferences;
String avrBasePath;
String corePath;
List<File> objectFiles;
ArrayList<String> includePaths;
public Compiler() {
logger.debug("DEBUG: Compiler(): Start no arguments");
}
/**
* Compile with avr-gcc.
*
* @param sketch
* Sketch object to be compiled.
* @param buildPath
* Where the temporary files live and will be built from.
* @param primaryClassName
* the name of the combined sketch file w/ extension
* @return true if successful.
* @throws RunnerException
* Only if there's a problem. Only then.
*/
public boolean compile(Sketch sketch, String buildPath,String primaryClassName, boolean verbose) throws RunnerException
{
logger.debug("DEBUG: Compiler.java: Start Compile(...).");
this.sketch = sketch;
this.buildPath = buildPath;
this.primaryClassName = primaryClassName;
this.verbose = verbose;
// the pms object isn't used for anything but storage
MessageStream pms = new MessageStream(this);
boardPreferences = new HashMap(Base.getBoardPreferences());
String buildCore = boardPreferences.get("build.core");
if (buildCore == null) {
RunnerException re = new RunnerException("No board selected; please choose a board from the Tools > Board menu.");
re.hideStackTrace();
throw re;
}
//Check for null platform, and use system default if not found
platform = boardPreferences.get("platform");
if (platform == null)
{
platformPreferences = new HashMap(Base.getPlatformPreferences());
}
else
{
platformPreferences = new HashMap(Base.getPlatformPreferences(platform));
}
//Get the preferences file from the sketch folder
File sketchFolder = sketch.getFolder();
sketchPreferences = Base.getSketchPreferences(sketchFolder) ;
//Put all the global preference configuration into one Master configpreferences
configPreferences = mergePreferences( Preferences.getMap(), platformPreferences, boardPreferences, sketchPreferences);
avrBasePath = configPreferences.get("compiler.path");
logger.debug("avrBasePath: " + avrBasePath);
if (avrBasePath == null)
{
avrBasePath = Base.getAvrBasePath();
}
else
{
//Put in the system path in the compiler path if available
MessageFormat compileFormat = new MessageFormat(avrBasePath);
String basePath = System.getProperty("user.dir");
if (Base.isMacOS()) {
logger.debug("basePath: " + basePath);
basePath += "/mpide.app/Contents/Resources/Java";
}
Object[] Args = {basePath};
avrBasePath = compileFormat.format( Args );
}
this.board = configPreferences.get("board");
if (this.board == "")
{
this.board = "_UNKNOWN";
}
String core = configPreferences.get("build.core");
if (core == null)
{
RunnerException re = new RunnerException(
"No board selected; please choose a board from the Tools > Board menu.");
re.hideStackTrace();
throw re;
}
//String corePath;
if (core.indexOf(':') == -1)
{
Target t = Base.getTarget();
File coreFolder = new File(new File(t.getFolder(), "cores"), core);
this.corePath = coreFolder.getAbsolutePath();
} else {
Target t = Base.targetsTable.get(core.substring(0, core.indexOf(':')));
File coresFolder = new File(t.getFolder(), "cores");
File coreFolder = new File(coresFolder, core.substring(core.indexOf(':') + 1));
this.corePath = coreFolder.getAbsolutePath();
}
/*
* Debug corePath
*/
logger.debug("corePaths: " + this.corePath);
String variant = boardPreferences.get("build.variant");
String variantPath = null;
if (variant != null) {
if (variant.indexOf(':') == -1) {
Target t = Base.getTarget();
File variantFolder = new File(new File(t.getFolder(), "variants"), variant);
variantPath = variantFolder.getAbsolutePath();
} else {
Target t = Base.targetsTable.get(variant.substring(0, variant.indexOf(':')));
File variantFolder = new File(t.getFolder(), "variants");
variantFolder = new File(variantFolder, variant.substring(variant.indexOf(':') + 1));
variantPath = variantFolder.getAbsolutePath();
}
}
this.objectFiles = new ArrayList<File>();
// 0. include paths for core + all libraries
logger.debug("0. getIncludes");
sketch.setCompilingProgress(20);
this.includePaths = getIncludes(this.corePath);
if (variantPath != null) {
includePaths.add(variantPath);
}
for (File file : sketch.getImportedLibraries()) {
includePaths.add(file.getPath());
}
// 1. compile the sketch (already in the buildPath)
logger.debug("1. compileSketch");
compileSketch(avrBasePath, buildPath, includePaths, configPreferences);
sketch.setCompilingProgress(30);
// 2. compile the libraries, outputting .o files to:
// <buildPath>/<library>/
//Doesn't really use configPreferences
logger.debug("2. compileLibraries");
compileLibraries(avrBasePath, buildPath, includePaths, configPreferences);
sketch.setCompilingProgress(40);
// 3. compile the core, outputting .o files to <buildPath> and then
// collecting them into the core.a library file.
logger.debug("3. compileCore");
compileCore(avrBasePath, buildPath, corePath, variant, variantPath, configPreferences);
sketch.setCompilingProgress(50);
// 4. link it all together into the .elf file
logger.debug("4. compileLink");
compileLink(avrBasePath, buildPath, this.corePath, includePaths, configPreferences);
sketch.setCompilingProgress(60);
// 5. extract EEPROM data (from EEMEM directive) to .eep file.
logger.debug("5. compileEep");
compileEep(avrBasePath, buildPath, includePaths, configPreferences);
sketch.setCompilingProgress(70);
// 6. build the .hex file
logger.debug("6. compileHex");
sketch.setCompilingProgress(80);
compileHex(avrBasePath, buildPath, includePaths, configPreferences);
sketch.setCompilingProgress(90);
//done
logger.debug("7. compile done");
return true;
}
private List<File> compileFiles(String avrBasePath,
String buildPath,
ArrayList<String> includePaths,
List<File> sSources, List<File>
cSources,
List<File> cppSources,
HashMap<String, String> configPreferences) throws RunnerException {
List<File> objectPaths = new ArrayList<File>();
for (File file : sSources) {
String objectPath = buildPath + File.separator + file.getName()
+ ".o";
objectPaths.add(new File(objectPath));
execAsynchronously(getCommandCompilerS(avrBasePath, includePaths,
file.getAbsolutePath(), objectPath, configPreferences));
}
for (File file : cSources) {
String objectPath = buildPath + File.separator + file.getName()
+ ".o";
objectPaths.add(new File(objectPath));
execAsynchronously(getCommandCompilerC(avrBasePath, includePaths,
file.getAbsolutePath(), objectPath, configPreferences));
}
for (File file : cppSources) {
String objectPath = buildPath + File.separator + file.getName()
+ ".o";
objectPaths.add(new File(objectPath));
execAsynchronously(getCommandCompilerCPP(avrBasePath, includePaths,
file.getAbsolutePath(), objectPath, configPreferences));
}
return objectPaths;
}
boolean firstErrorFound;
boolean secondErrorFound;
/***
* Exec as String instead of Array
*
*/
private void execAsynchronously(String command) throws RunnerException
{
{
logger.debug("execAsynchronously: start");
String[] commandArray = command.split("::");
List<String> stringList = new ArrayList<String>();
for(String string : commandArray) {
string = string.trim();
if(string != null && string.length() > 0) {
stringList.add(string);
}
}
commandArray = stringList.toArray(new String[stringList.size()]);
int result = 0;
if (verbose || Preferences.getBoolean("build.verbose"))
{
System.out.print(command.replace(":"," "));
System.out.println();
/*if(logger.isDebugEnabled()) {
for (int i = 0; i < commandArray.length; i++) {
logger.debug("commandArray[" + i + "]: " + commandArray[i]);
}
logger.debug("Command: " + command.replace(":"," "));
}*/
}
firstErrorFound = false; // haven't found any errors yet
secondErrorFound = false;
Process process;
try {
process = Runtime.getRuntime().exec(commandArray);
} catch (IOException e) {
RunnerException re = new RunnerException(e.getMessage());
re.hideStackTrace();
throw re;
}
MessageSiphon in = new MessageSiphon(process.getInputStream(), this);
MessageSiphon err = new MessageSiphon(process.getErrorStream(), this);
// wait for the process to finish. if interrupted
// before waitFor returns, continue waiting
boolean running = true;
while (running) {
try {
if (in.thread != null)
in.thread.join();
if (err.thread != null)
err.thread.join();
result = process.waitFor();
//System.out.println("result is " + result);
running = false;
} catch (InterruptedException ignored) { }
}
// an error was queued up by message(), barf this back to compile(),
// which will barf it back to Editor. if you're having trouble
// discerning the imagery, consider how cows regurgitate their food
// to digest it, and the fact that they have five stomaches.
//
//System.out.println("throwing up " + exception);
if (exception != null) { throw exception; }
if (result > 1) {
// a failure in the tool (e.g. unable to locate a sub-executable)
System.err.println(command + " returned " + result);
}
if (result != 0) {
RunnerException re = new RunnerException("Error running.");
re.hideStackTrace();
throw re;
}
}
}
/**
* Part of the MessageConsumer interface, this is called whenever a piece
* (usually a line) of error message is spewed out from the compiler. The
* errors are parsed for their contents and line number, which is then
* reported back to Editor.
*/
public void message(String s) {
int i;
// remove the build path so people only see the filename
// can't use replaceAll() because the path may have characters in it
// which
// have meaning in a regular expression.
if (!verbose) {
while ((i = s.indexOf(buildPath + File.separator)) != -1) {
s = s.substring(0, i)
+ s.substring(i + (buildPath + File.separator).length());
}
}
// look for error line, which contains file name, line number,
// and at least the first line of the error message
String errorFormat = "([\\w\\d_]+.\\w+):(\\d+):\\s*error:\\s*(.*)\\s*";
String[] pieces = PApplet.match(s, errorFormat);
// if (pieces != null && exception == null) {
// exception = sketch.placeException(pieces[3], pieces[1],
// PApplet.parseInt(pieces[2]) - 1);
// if (exception != null) exception.hideStackTrace();
// }
if (pieces != null) {
RunnerException e = sketch.placeException(pieces[3], pieces[1],
PApplet.parseInt(pieces[2]) - 1);
// replace full file path with the name of the sketch tab (unless
// we're
// in verbose mode, in which case don't modify the compiler output)
if (e != null && !verbose) {
SketchCode code = sketch.getCode(e.getCodeIndex());
String fileName = code
.isExtension(sketch.getDefaultExtension()) ? code
.getPrettyName() : code.getFileName();
s = fileName + ":" + e.getCodeLine() + ": error: "
+ e.getMessage();
}
if (pieces[3].trim().equals("SPI.h: No such file or directory")) {
e = new RunnerException(
"Please import the SPI library from the Sketch > Import Library menu.");
s += "\nAs of Arduino 0019, the Ethernet library depends on the SPI library."
+ "\nYou appear to be using it or another library that depends on the SPI library.";
}
if (exception == null && e != null) {
exception = e;
exception.hideStackTrace();
}
}
System.err.print(s);
}
// ///////////////////////////////////////////////////////////////////////////
//What conditions is getCommandCompilerS invoke from?
static private String getCommandCompilerS(String avrBasePath,
ArrayList<String> includePaths, String sourceName, String objectName,
HashMap<String, String> configPreferences)
{
logger.debug("getCommandCompilerS: start");
String baseCommandString = configPreferences.get("recipe.cpp.o.pattern");
MessageFormat compileFormat = new MessageFormat(baseCommandString);
//getIncludes to String
String includes = preparePaths(includePaths);
Object[] Args = {
avrBasePath, //0
configPreferences.get("compiler.cpp.cmd"), //1
configPreferences.get("compiler.S.flags"), //2
configPreferences.get("compiler.cpudef"), //3
configPreferences.get("build.mcu"), //4
configPreferences.get("build.f_cpu"), //5
configPreferences.get("software") + "=" + Base.REVISION,//6
configPreferences.get("board") , //7,
configPreferences.get("compiler.define") + " " + configPreferences.get("board.define") , //8
includes, //9
sourceName, //10
objectName //11
};
return compileFormat.format( Args );
}
//removed static
private String getCommandCompilerC(String avrBasePath,
ArrayList<String> includePaths, String sourceName, String objectName,
HashMap<String, String> configPreferences)
{
logger.debug("getCommandCompilerC: start");
String baseCommandString = configPreferences.get("recipe.c.o.pattern");
MessageFormat compileFormat = new MessageFormat(baseCommandString);
//getIncludes to String
String includes = preparePaths(includePaths);
Object[] Args = {
avrBasePath,
configPreferences.get("compiler.c.cmd"),
configPreferences.get("compiler.c.flags"),
configPreferences.get("compiler.cpudef"),
configPreferences.get("build.mcu"),
configPreferences.get("build.f_cpu"),
configPreferences.get("software") + "=" + Base.REVISION,
configPreferences.get("board"),
configPreferences.get("compiler.define") + " " + configPreferences.get("board.define"),
includes,
sourceName,
objectName
};
return compileFormat.format( Args );
}
static private String getCommandCompilerCPP(String avrBasePath,
ArrayList<String> includePaths, String sourceName, String objectName,
HashMap<String, String> configPreferences)
{
logger.debug("getCommandCompilerCPP: start");
String baseCommandString = configPreferences.get("recipe.cpp.o.pattern");
MessageFormat compileFormat = new MessageFormat(baseCommandString);
//getIncludes to String
String includes = preparePaths(includePaths);
logger.debug("Source: " + sourceName);
Object[] Args = {
avrBasePath,
configPreferences.get("compiler.cpp.cmd"),
configPreferences.get("compiler.cpp.flags"),
configPreferences.get("compiler.cpudef"),
configPreferences.get("build.mcu"),
configPreferences.get("build.f_cpu"),
configPreferences.get("software") + "=" + Base.REVISION,
configPreferences.get("board"),
configPreferences.get("compiler.define") + " " + configPreferences.get("board.define"),
includes,
sourceName,
objectName
};
return compileFormat.format( Args );
}
// ///////////////////////////////////////////////////////////////////////////
static private void createFolder(File folder) throws RunnerException {
if (folder.isDirectory())
return;
if (!folder.mkdir())
throw new RunnerException("Couldn't create: " + folder);
}
/**
* Given a folder, return a list of the header files in that folder (but not
* the header files in its sub-folders, as those should be included from
* within the header files at the top-level).
*/
static public String[] headerListFromIncludePath(String path) {
FilenameFilter onlyHFiles = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".h");
}
};
return (new File(path)).list(onlyHFiles);
}
static public ArrayList<File> findFilesInPath(String path,
String extension, boolean recurse) {
return findFilesInFolder(new File(path), extension, recurse);
}
static public ArrayList<File> findFilesInFolder(File folder,
String extension, boolean recurse) {
ArrayList<File> files = new ArrayList<File>();
if (folder.listFiles() == null)
return files;
for (File file : folder.listFiles()) {
if (file.getName().startsWith("."))
continue; // skip hidden files
if (file.getName().endsWith("." + extension))
files.add(file);
if (recurse && file.isDirectory()) {
files.addAll(findFilesInFolder(file, extension, true));
}
}
return files;
}
// 0. include paths for core + all libraries
ArrayList<String> getIncludes(String corePath)
{
logger.debug("corePath: " + corePath);
logger.debug("getSketchFlderPath: " + sketch.getFolder().toString());
ArrayList<String> includePaths = new ArrayList();
//add the sketch path to the includes
includePaths.add(sketch.getFolder().toString());
includePaths.add(corePath);
for (File file : sketch.getImportedLibraries())
{
logger.debug("getImportedLibraries: " + file.getPath());
includePaths.add(file.getPath());
}
return includePaths;
}
// 1. compile the sketch (already in the buildPath)
void compileSketch(String avrBasePath, String buildPath, ArrayList<String> includePaths, HashMap<String, String> configPreferences)
throws RunnerException
{
logger.debug("compileSketch: start");
this.objectFiles.addAll(compileFiles(avrBasePath, buildPath, includePaths,
findFilesInPath(buildPath, "S", false),
findFilesInPath(buildPath, "c", false),
findFilesInPath(buildPath, "cpp", false),
configPreferences));
}
// 2. compile the libraries, outputting .o files to:
// <buildPath>/<library>/
void compileLibraries (String avrBasePath, String buildPath, ArrayList<String> includePaths, HashMap<String, String> configPreferences)
throws RunnerException
{
logger.debug("compileLibraries: start");
for (File libraryFolder : sketch.getImportedLibraries())
{
File outputFolder = new File(buildPath, libraryFolder.getName());
File utilityFolder = new File(libraryFolder, "utility");
createFolder(outputFolder);
// this library can use includes in its utility/ folder
this.includePaths.add(utilityFolder.getAbsolutePath());
this.objectFiles.addAll(compileFiles(avrBasePath,
outputFolder.getAbsolutePath(), includePaths,
findFilesInFolder(libraryFolder, "S", false),
findFilesInFolder(libraryFolder, "c", false),
findFilesInFolder(libraryFolder, "cpp", false),
configPreferences));
outputFolder = new File(outputFolder, "utility");
createFolder(outputFolder);
this.objectFiles.addAll(compileFiles(avrBasePath,
outputFolder.getAbsolutePath(), includePaths,
findFilesInFolder(utilityFolder, "S", false),
findFilesInFolder(utilityFolder, "c", false),
findFilesInFolder(utilityFolder, "cpp", false),
configPreferences));
// other libraries should not see this library's utility/ folder
this.includePaths.remove(includePaths.size() - 1);
}
}
// 3. compile the core, outputting .o files to <buildPath> and then
// collecting them into the core.a library file.
void compileCore (String avrBasePath, String buildPath, String corePath, String variant, String variantPath, HashMap<String, String> configPreferences)
throws RunnerException
{
logger.debug("compileCore(...) start");
ArrayList<String> includePaths = new ArrayList();
includePaths.add(corePath); //include core path only
if (variantPath != null) includePaths.add(variantPath);
String baseCommandString = configPreferences.get("recipe.ar.pattern");
String commandString = "";
MessageFormat compileFormat = new MessageFormat(baseCommandString);
List<File> coreObjectFiles = compileFiles(
avrBasePath,
buildPath,
includePaths,
findFilesInPath(corePath, "S", true),
findFilesInPath(corePath, "c", true),
findFilesInPath(corePath, "cpp", true),
configPreferences);
for (File file : coreObjectFiles) {
//List commandAR = new ArrayList(baseCommandAR);
//commandAR = commandAR + file.getAbsolutePath();
Object[] Args = {
avrBasePath,
configPreferences.get("compiler.ar.cmd"),
configPreferences.get("compiler.ar.flags"),
//corePath,
buildPath + File.separator,
"core.a",
//objectName
file.getAbsolutePath()
};
commandString = compileFormat.format( Args );
execAsynchronously(commandString);
}
}
// 4. link it all together into the .elf file
void compileLink(String avrBasePath, String buildPath, String corePath, ArrayList<String> includePaths, HashMap<String, String> configPreferences)
throws RunnerException
{
logger.debug("compileLink: start");
String baseCommandString = configPreferences.get("recipe.c.combine.pattern");
String commandString = "";
MessageFormat compileFormat = new MessageFormat(baseCommandString);
String objectFileList = "";
for (File file : objectFiles) {
objectFileList = objectFileList + file.getAbsolutePath() + "::";
}
Object[] Args = {
avrBasePath,
configPreferences.get("compiler.c.elf.cmd"),
configPreferences.get("compiler.c.elf.flags"),
configPreferences.get("compiler.cpudef"),
configPreferences.get("build.mcu"),
buildPath + File.separator,
primaryClassName,
objectFileList,
buildPath + File.separator + "core.a",
buildPath,
- corePath,
- avrBasePath,
+ corePath,
configPreferences.get("ldscript"),
};
commandString = compileFormat.format( Args );
execAsynchronously(commandString);
}
// 5. extract EEPROM data (from EEMEM directive) to .eep file.
void compileEep (String avrBasePath, String buildPath, ArrayList<String> includePaths, HashMap<String, String> configPreferences)
throws RunnerException
{
logger.debug("compileEep: start");
String baseCommandString = configPreferences.get("recipe.objcopy.eep.pattern");
String commandString = "";
MessageFormat compileFormat = new MessageFormat(baseCommandString);
String objectFileList = "";
Object[] Args = {
avrBasePath,
configPreferences.get("compiler.objcopy.cmd"),
configPreferences.get("compiler.objcopy.eep.flags"),
buildPath + File.separator + primaryClassName,
buildPath + File.separator + primaryClassName
};
commandString = compileFormat.format( Args );
execAsynchronously(commandString);
}
// 6. build the .hex file
void compileHex (String avrBasePath, String buildPath, ArrayList<String> includePaths, HashMap<String, String> configPreferences)
throws RunnerException
{
logger.debug("compileHex: start");
String baseCommandString = configPreferences.get("recipe.objcopy.hex.pattern");
String commandString = "";
MessageFormat compileFormat = new MessageFormat(baseCommandString);
String objectFileList = "";
Object[] Args = {
avrBasePath,
configPreferences.get("compiler.elf2hex.cmd"),
configPreferences.get("compiler.elf2hex.flags"),
buildPath + File.separator + primaryClassName,
buildPath + File.separator + primaryClassName
};
commandString = compileFormat.format( Args );
execAsynchronously(commandString);
}
//merge all the preferences file in the correct order of precedence
HashMap mergePreferences(Map Preferences, Map platformPreferences, Map boardPreferences, Map sketchPreferences)
{
HashMap _map = new HashMap();
Iterator iterator = Preferences.entrySet().iterator();
while(iterator.hasNext())
{
Map.Entry pair = (Map.Entry)iterator.next();
if (pair.getValue() == null)
{
_map.put(pair.getKey(), "");
}
else
{
_map.put(pair.getKey(), pair.getValue());
}
}
//logger.debug("Preferences Platform Dump: " + platformPreferences);
iterator = platformPreferences.entrySet().iterator();
while(iterator.hasNext())
{
Map.Entry pair = (Map.Entry)iterator.next();
if (pair.getValue() == null)
{
_map.put(pair.getKey(), "");
}
else
{
_map.put(pair.getKey(), pair.getValue());
}
//System.out.println(pair.getKey() + " = " + pair.getValue());
}
//System.out.println("Done: platformPreferences");
iterator = boardPreferences.entrySet().iterator();
while(iterator.hasNext())
{
Map.Entry pair = (Map.Entry)iterator.next();
if (pair.getValue() == null)
{
_map.put(pair.getKey(), "");
}
else
{
_map.put(pair.getKey(), pair.getValue());
}
//System.out.println(pair.getKey() + " = " + pair.getValue());
}
//System.out.println("Done: boardPreferences");
iterator = sketchPreferences.entrySet().iterator();
while(iterator.hasNext())
{
Map.Entry pair = (Map.Entry)iterator.next();
if (pair.getValue() == null)
{
_map.put(pair.getKey(), "");
}
else
{
_map.put(pair.getKey(), pair.getValue());
}
//System.out.println(pair.getKey() + " = " + pair.getValue());
}
//System.out.println("Done: boardPreferences");
// logger.debug("Final Preferences Dump: " + _map);
return _map;
}
private static String preparePaths(ArrayList<String> includePaths) {
//getIncludes to String
//logger.debug("Start: Prepare paths");
String includes = "";
for (int i = 0; i < includePaths.size(); i++)
{
includes = includes + (" -I" + (String) includePaths.get(i)) + "::";
}
//logger.debug("Paths prepared: " + includes);
return includes;
}
}
| true | false | null | null |
diff --git a/core/src/main/java/io/keen/client/java/KeenClient.java b/core/src/main/java/io/keen/client/java/KeenClient.java
index b769616..a4a53fa 100644
--- a/core/src/main/java/io/keen/client/java/KeenClient.java
+++ b/core/src/main/java/io/keen/client/java/KeenClient.java
@@ -1,1346 +1,1347 @@
package io.keen.client.java;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import io.keen.client.java.exceptions.InvalidEventCollectionException;
import io.keen.client.java.exceptions.InvalidEventException;
import io.keen.client.java.exceptions.NoWriteKeyException;
import io.keen.client.java.exceptions.ServerException;
import io.keen.client.java.http.HttpHandler;
import io.keen.client.java.http.OutputSource;
import io.keen.client.java.http.Request;
import io.keen.client.java.http.Response;
import io.keen.client.java.http.UrlConnectionHttpHandler;
/**
* <p>
* KeenClient provides all of the functionality required to:
* </p>
*
* <ul>
* <li>Create events from map objects</li>
* <li>Automatically insert properties into events as they are created</li>
* <li>Post events to the Keen server, either one-at-a-time or in batches</li>
* <li>Store events in between batch posts, if desired</li>
* <li>Perform posts either synchronously or asynchronously</li>
* </ul>
*
* <p>
* To create a {@link KeenClient}, use a subclass of {@link io.keen.client.java.KeenClient.Builder}
* which provides the default interfaces for various operations (HTTP, JSON, queueing, async).
* </p>
*
* @author dkador, klitwack
* @since 1.0.0
*/
public class KeenClient {
///// PUBLIC STATIC METHODS /////
/**
* Call this to retrieve the {@code KeenClient} singleton instance.
*
* @return The singleton instance of the client.
*/
public static KeenClient client() {
if (ClientSingleton.INSTANCE.client == null) {
throw new IllegalStateException("Please call KeenClient.initialize() before requesting the client.");
}
return ClientSingleton.INSTANCE.client;
}
/**
* Initializes the static Keen client. Only the first call to this method has any effect. All
* subsequent calls are ignored.
*
* @param client The {@link io.keen.client.java.KeenClient} implementation to use as the
* singleton client for the library.
*/
public static void initialize(KeenClient client) {
if (client == null) {
throw new IllegalArgumentException("Client must not be null");
}
if (ClientSingleton.INSTANCE.client != null) {
// Do nothing.
return;
}
ClientSingleton.INSTANCE.client = client;
}
/**
* Gets whether or not the singleton KeenClient has been initialized.
*
* @return {@code true} if and only if the client has been initialized.
*/
public static boolean isInitialized() {
return (ClientSingleton.INSTANCE.client != null);
}
///// PUBLIC METHODS //////
/**
* Adds an event to the default project with default Keen properties and no callbacks.
*
* @see #addEvent(KeenProject, String, java.util.Map, java.util.Map, KeenCallback)
*/
public void addEvent(String eventCollection, Map<String, Object> event) {
addEvent(eventCollection, event, null);
}
/**
* Adds an event to the default project with no callbacks.
*
* @see #addEvent(KeenProject, String, java.util.Map, java.util.Map, KeenCallback)
*/
public void addEvent(String eventCollection, Map<String, Object> event,
Map<String, Object> keenProperties) {
addEvent(null, eventCollection, event, keenProperties, null);
}
/**
* Synchronously adds an event to the specified collection. This method will immediately
* publish the event to the Keen server in the current thread.
*
* @param project The project in which to publish the event. If a default project has been set
* on the client, this parameter may be null, in which case the default project
* will be used.
* @param eventCollection The name of the collection in which to publish the event.
* @param event A Map that consists of key/value pairs. Keen naming conventions apply (see
* docs). Nested Maps and lists are acceptable (and encouraged!).
* @param keenProperties A Map that consists of key/value pairs to override default properties.
* ex: "timestamp" -> Calendar.getInstance()
* @param callback An optional callback to receive notification of success or failure.
*/
public void addEvent(KeenProject project, String eventCollection, Map<String, Object> event,
Map<String, Object> keenProperties, KeenCallback callback) {
if (!isActive) {
handleLibraryInactive(callback);
return;
}
if (project == null && defaultProject == null) {
handleFailure(null, new IllegalStateException("No project specified, but no default project found"));
return;
}
KeenProject useProject = (project == null ? defaultProject : project);
try {
// Build the event.
Map<String, Object> newEvent =
validateAndBuildEvent(useProject, eventCollection, event, keenProperties);
// Publish the event.
publish(useProject, eventCollection, newEvent);
handleSuccess(callback);
} catch (Exception e) {
handleFailure(callback, e);
}
}
/**
* Adds an event to the default project with default Keen properties and no callbacks.
*
* @see #addEvent(KeenProject, String, java.util.Map, java.util.Map, KeenCallback)
*/
public void addEventAsync(String eventCollection, Map<String, Object> event) {
addEventAsync(eventCollection, event, null);
}
/**
* Adds an event to the default project with no callbacks.
*
* @see #addEvent(KeenProject, String, java.util.Map, java.util.Map, KeenCallback)
*/
public void addEventAsync(String eventCollection, Map<String, Object> event,
final Map<String, Object> keenProperties) {
addEventAsync(null, eventCollection, event, keenProperties, null);
}
/**
* Asynchronously adds an event to the specified collection. This method will request that
* the Keen client's {@link java.util.concurrent.Executor} executes the publish operation.
*
* @param project The project in which to publish the event. If a default project has been set
* on the client this parameter may be null, in which case the default project
* will be used.
* @param eventCollection The name of the collection in which to publish the event.
* @param event A Map that consists of key/value pairs. Keen naming conventions apply (see
* docs). Nested Maps and lists are acceptable (and encouraged!).
* @param keenProperties A Map that consists of key/value pairs to override default properties.
* ex: "timestamp" -> Calendar.getInstance()
* @param callback An optional callback to receive notification of success or failure.
*/
public void addEventAsync(final KeenProject project, final String eventCollection,
final Map<String, Object> event,
final Map<String, Object> keenProperties,
final KeenCallback callback) {
if (!isActive) {
handleLibraryInactive(callback);
return;
}
if (project == null && defaultProject == null) {
handleFailure(null, new IllegalStateException("No project specified, but no default project found"));
return;
}
final KeenProject useProject = (project == null ? defaultProject : project);
// Wrap the asynchronous execute in a try/catch block in case the executor throws a
// RejectedExecutionException (or anything else).
try {
publishExecutor.execute(new Runnable() {
@Override
public void run() {
addEvent(useProject, eventCollection, event, keenProperties, callback);
}
});
} catch (Exception e) {
handleFailure(callback, e);
}
}
/**
* Queues an event in the default project with default Keen properties and no callbacks.
*
* @see #queueEvent(KeenProject, String, java.util.Map, java.util.Map, KeenCallback)
*/
public void queueEvent(String eventCollection, Map<String, Object> event) {
queueEvent(eventCollection, event, null);
}
/**
* Queues an event in the default project with no callbacks.
*
* @see #queueEvent(KeenProject, String, java.util.Map, java.util.Map, KeenCallback)
*/
public void queueEvent(String eventCollection, Map<String, Object> event,
Map<String, Object> keenProperties) {
queueEvent(null, eventCollection, event, keenProperties, null);
}
/**
* Synchronously queues an event for publishing. The event will be cached in the client's
* {@link io.keen.client.java.KeenEventStore} until the next call to either
* {@link #sendQueuedEvents()} or {@link #sendQueuedEventsAsync()}.
*
* @param project The project in which to publish the event. If a default project has been set
* on the client this parameter may be null, in which case the default project
* will be used.
* @param eventCollection The name of the collection in which to publish the event.
* @param event A Map that consists of key/value pairs. Keen naming conventions apply (see
* docs). Nested Maps and lists are acceptable (and encouraged!).
* @param keenProperties A Map that consists of key/value pairs to override default properties.
* ex: "timestamp" -> Calendar.getInstance()
* @param callback An optional callback to receive notification of success or failure.
*/
public void queueEvent(KeenProject project, String eventCollection, Map<String, Object> event,
Map<String, Object> keenProperties, final KeenCallback callback) {
if (!isActive) {
handleLibraryInactive(callback);
return;
}
if (project == null && defaultProject == null) {
handleFailure(null, new IllegalStateException("No project specified, but no default project found"));
return;
}
KeenProject useProject = (project == null ? defaultProject : project);
try {
// Build the event
Map<String, Object> newEvent =
validateAndBuildEvent(useProject, eventCollection, event, keenProperties);
// Serialize the event into JSON.
StringWriter writer = new StringWriter();
jsonHandler.writeJson(writer, newEvent);
String jsonEvent = writer.toString();
KeenUtils.closeQuietly(writer);
// Save the JSON event out to the event store.
eventStore.store(useProject.getProjectId(), eventCollection, jsonEvent);
handleSuccess(callback);
} catch (Exception e) {
handleFailure(callback, e);
}
}
/**
* Sends all queued events for the default project with no callbacks.
*
* @see #sendQueuedEvents(KeenProject, KeenCallback)
*/
public void sendQueuedEvents() {
sendQueuedEvents(null);
}
/**
* Sends all queued events for the specified project with no callbacks.
*
* @see #sendQueuedEvents(KeenProject, KeenCallback)
*/
public void sendQueuedEvents(KeenProject project) {
sendQueuedEvents(project, null);
}
/**
* Synchronously sends all queued events for the given project. This method will immediately
* publish the events to the Keen server in the current thread.
*
* @param project The project for which to send queued events. If a default project has been set
* on the client this parameter may be null, in which case the default project
* will be used.
* @param callback An optional callback to receive notification of success or failure.
*/
public synchronized void sendQueuedEvents(KeenProject project, KeenCallback callback) {
if (!isActive) {
handleLibraryInactive(callback);
return;
}
if (project == null && defaultProject == null) {
handleFailure(null, new IllegalStateException("No project specified, but no default project found"));
return;
}
KeenProject useProject = (project == null ? defaultProject : project);
try {
String projectId = useProject.getProjectId();
Map<String, List<Object>> eventHandles = eventStore.getHandles(projectId);
Map<String, List<Map<String, Object>>> events = buildEventMap(eventHandles);
String response = publishAll(useProject, events);
if (response != null) {
try {
handleAddEventsResponse(eventHandles, response);
} catch (Exception e) {
// Errors handling the response are non-fatal; just log them.
KeenLogging.log("Error handling response to batch publish: " + e.getMessage());
}
}
handleSuccess(callback);
} catch (Exception e) {
handleFailure(callback, e);
}
}
/**
* Sends all queued events for the default project with no callbacks.
*
* @see #sendQueuedEventsAsync(KeenProject, KeenCallback)
*/
public void sendQueuedEventsAsync() {
sendQueuedEventsAsync(null);
}
/**
* Sends all queued events for the specified project with no callbacks.
*
* @see #sendQueuedEventsAsync(KeenProject, KeenCallback)
*/
public void sendQueuedEventsAsync(final KeenProject project) {
sendQueuedEventsAsync(project, null);
}
/**
* Asynchronously sends all queued events for the given project. This method will request that
* the Keen client's {@link java.util.concurrent.Executor} executes the publish operation.
*
* @param project The project for which to send queued events. If a default project has been set
* on the client this parameter may be null, in which case the default project
* will be used.
* @param callback An optional callback to receive notification of success or failure.
*/
public void sendQueuedEventsAsync(final KeenProject project, final KeenCallback callback) {
if (!isActive) {
handleLibraryInactive(callback);
return;
}
if (project == null && defaultProject == null) {
handleFailure(null, new IllegalStateException("No project specified, but no default project found"));
return;
}
final KeenProject useProject = (project == null ? defaultProject : project);
// Wrap the asynchronous execute in a try/catch block in case the executor throws a
// RejectedExecutionException (or anything else).
try {
publishExecutor.execute(new Runnable() {
@Override
public void run() {
sendQueuedEvents(useProject, callback);
}
});
} catch (Exception e) {
handleFailure(callback, e);
}
}
/**
* Gets the JSON handler for this client.
*
* @return The {@link io.keen.client.java.KeenJsonHandler}.
*/
public KeenJsonHandler getJsonHandler() {
return jsonHandler;
}
/**
* Gets the event store for this client.
*
* @return The {@link io.keen.client.java.KeenEventStore}.
*/
public KeenEventStore getEventStore() {
return eventStore;
}
/**
* Gets the executor for asynchronous publishing for this client.
*
* @return The {@link java.util.concurrent.Executor}.
*/
public Executor getPublishExecutor() {
return publishExecutor;
}
/**
* Gets the default project that this {@link KeenClient} will use if no project is specified.
*
* @return The default project.
*/
public KeenProject getDefaultProject() {
return defaultProject;
}
/**
* Sets the default project that this {@link KeenClient} should use if no project is specified.
*
* @param defaultProject The new default project.
*/
public void setDefaultProject(KeenProject defaultProject) {
this.defaultProject = defaultProject;
}
/**
* Gets the base API URL associated with this instance of the {@link KeenClient}.
*
* @return The base API URL
*/
public String getBaseUrl() {
return baseUrl;
}
/**
* Sets the base API URL associated with this instance of the {@link KeenClient}.
* <p/>
* Use this if you want to disable SSL.
*
* @param baseUrl The new base URL (i.e. 'http://api.keen.io'), or null to reset the base URL to
* the default ('https://api.keen.io').
*/
public void setBaseUrl(String baseUrl) {
if (baseUrl == null) {
this.baseUrl = KeenConstants.SERVER_ADDRESS;
} else {
this.baseUrl = baseUrl;
}
}
/**
* Gets the {@link GlobalPropertiesEvaluator} associated with this instance of the {@link KeenClient}.
*
* @return The {@link GlobalPropertiesEvaluator}
*/
public GlobalPropertiesEvaluator getGlobalPropertiesEvaluator() {
return globalPropertiesEvaluator;
}
/**
* Call this to set the {@link GlobalPropertiesEvaluator} for this instance of the {@link KeenClient}.
* The evaluator is invoked every time an event is added to an event collection.
* <p/>
* Global properties are properties which are sent with EVERY event. For example, you may wish to always
* capture device information like OS version, handset type, orientation, etc.
* <p/>
* The evaluator takes as a parameter a single String, which is the name of the event collection the
* event's being added to. You're responsible for returning a Map which represents the global properties
* for this particular event collection.
* <p/>
* Note that because we use a class defined by you, you can create DYNAMIC global properties. For example,
* if you want to capture device orientation, then your evaluator can ask the device for its current orientation
* and then construct the Map. If your global properties aren't dynamic, then just return the same Map
* every time.
* <p/>
* Example usage:
* <pre>
* {@code KeenClient client = KeenClient.client();
* GlobalPropertiesEvaluator evaluator = new GlobalPropertiesEvaluator() {
* public Map<String, Object> getGlobalProperties(String eventCollection) {
* Map<String, Object> map = new HashMap<String, Object>();
* map.put("some dynamic property name", "some dynamic property value");
* return map;
* }
* };
* client.setGlobalPropertiesEvaluator(evaluator);
* }
* </pre>
*
* @param globalPropertiesEvaluator The evaluator which is invoked any time an event is added to an event
* collection.
*/
public void setGlobalPropertiesEvaluator(GlobalPropertiesEvaluator globalPropertiesEvaluator) {
this.globalPropertiesEvaluator = globalPropertiesEvaluator;
}
/**
* Gets the Keen Global Properties map. See docs for {@link #setGlobalProperties(java.util.Map)}.
*
* @return The Global Properties map.
*/
public Map<String, Object> getGlobalProperties() {
return globalProperties;
}
/**
* Call this to set the Keen Global Properties Map for this instance of the {@link KeenClient}. The Map
* is used every time an event is added to an event collection.
* <p/>
* Keen Global Properties are properties which are sent with EVERY event. For example, you may wish to always
* capture static information like user ID, app version, etc.
* <p/>
* Every time an event is added to an event collection, the SDK will check to see if this property is defined.
* If it is, the SDK will copy all the properties from the global properties into the newly added event.
* <p/>
* Note that because this is just a Map, it's much more difficult to create DYNAMIC global properties.
* It also doesn't support per-collection properties. If either of these use cases are important to you, please use
* the {@link GlobalPropertiesEvaluator}.
* <p/>
* Also note that the Keen properties defined in {@link #getGlobalPropertiesEvaluator()} take precedence over
* the properties defined in getGlobalProperties, and that the Keen Properties defined in each
* individual event take precedence over either of the Global Properties.
* <p/>
* Example usage:
* <p/>
* <pre>
* KeenClient client = KeenClient.client();
* Map<String, Object> map = new HashMap<String, Object>();
* map.put("some standard key", "some standard value");
* client.setGlobalProperties(map);
* </pre>
*
* @param globalProperties The new map you wish to use as the Keen Global Properties.
*/
public void setGlobalProperties(Map<String, Object> globalProperties) {
this.globalProperties = globalProperties;
}
/**
* Gets whether or not the Keen client is running in debug mode.
*
* @return {@code true} if debug mode is enabled, otherwise {@code false}.
*/
public boolean isDebugMode() {
return isDebugMode;
}
/**
* Sets whether or not the Keen client should run in debug mode. When debug mode is enabled,
* all exceptions will be thrown immediately; otherwise they will be logged and reported to
* any callbacks, but never thrown.
*
* @param isDebugMode {@code true} to enable debug mode, or {@code false} to disable it.
*/
public void setDebugMode(boolean isDebugMode) {
this.isDebugMode = isDebugMode;
}
/**
* Gets whether or not the client is in active mode.
*
* @return {@code true} if the client is active,; {@code false} if it is inactive.
*/
public boolean isActive() {
return isActive;
}
///// PROTECTED ABSTRACT BUILDER IMPLEMENTATION /////
/**
* Builder class for instantiating Keen clients. Subclasses should override this and
* implement the getDefault* methods to provide new default behavior.
* <p/>
* This builder doesn't include any default implementation for handling JSON serialization and
* de-serialization. Subclasses must provide one.
* <p/>
* This builder defaults to using HttpURLConnection to handle HTTP requests.
* <p/>
* To cache events in between batch uploads, this builder defaults to a RAM-based event store.
* <p/>
* This builder defaults to a fixed thread pool (constructed with
* {@link java.util.concurrent.Executors#newFixedThreadPool(int)}) to run asynchronous requests.
*/
public static abstract class Builder {
private HttpHandler httpHandler;
private KeenJsonHandler jsonHandler;
private KeenEventStore eventStore;
private Executor publishExecutor;
/**
* Gets the default {@link HttpHandler} to use if none is explicitly set for this builder.
*
* This implementation returns a handler that will use {@link java.net.HttpURLConnection}
* to make HTTP requests.
*
* Subclasses should override this to provide an alternative default {@link HttpHandler}.
*
* @return The default {@link HttpHandler}.
* @throws Exception If there is an error creating the {@link HttpHandler}.
*/
protected HttpHandler getDefaultHttpHandler() throws Exception {
return new UrlConnectionHttpHandler();
}
/**
* Gets the {@link HttpHandler} that this builder is currently configured to use for making
* HTTP requests. If null, a default will be used instead.
*
* @return The {@link HttpHandler} to use.
*/
public HttpHandler getHttpHandler() {
return httpHandler;
}
/**
* Sets the {@link HttpHandler} to use for making HTTP requests.
*
* @param httpHandler The {@link HttpHandler} to use.
*/
public void setHttpHandler(HttpHandler httpHandler) {
this.httpHandler = httpHandler;
}
/**
* Sets the {@link HttpHandler} to use for making HTTP requests.
*
* @param httpHandler The {@link HttpHandler} to use.
* @return This instance (for method chaining).
*/
public Builder withHttpHandler(HttpHandler httpHandler) {
setHttpHandler(httpHandler);
return this;
}
/**
* Gets the default {@link KeenJsonHandler} to use if none is explicitly set for this builder.
*
* Subclasses must override this to provide a default {@link KeenJsonHandler}.
*
* @return The default {@link KeenJsonHandler}.
* @throws Exception If there is an error creating the {@link KeenJsonHandler}.
*/
protected abstract KeenJsonHandler getDefaultJsonHandler() throws Exception;
/**
* Gets the {@link KeenJsonHandler} that this builder is currently configured to use for
* handling JSON operations. If null, a default will be used instead.
*
* @return The {@link KeenJsonHandler} to use.
*/
public KeenJsonHandler getJsonHandler() {
return jsonHandler;
}
/**
* Sets the {@link KeenJsonHandler} to use for handling JSON operations.
*
* @param jsonHandler The {@link KeenJsonHandler} to use.
*/
public void setJsonHandler(KeenJsonHandler jsonHandler) {
this.jsonHandler = jsonHandler;
}
/**
* Sets the {@link KeenJsonHandler} to use for handling JSON operations.
*
* @param jsonHandler The {@link KeenJsonHandler} to use.
* @return This instance (for method chaining).
*/
public Builder withJsonHandler(KeenJsonHandler jsonHandler) {
setJsonHandler(jsonHandler);
return this;
}
/**
* Gets the default {@link KeenEventStore} to use if none is explicitly set for this builder.
*
* This implementation returns a RAM-based store.
*
* Subclasses should override this to provide an alternative default {@link KeenEventStore}.
*
* @return The default {@link KeenEventStore}.
* @throws Exception If there is an error creating the {@link KeenEventStore}.
*/
protected KeenEventStore getDefaultEventStore() throws Exception {
return new RamEventStore();
}
/**
* Gets the {@link KeenEventStore} that this builder is currently configured to use for
* storing events between batch publish operations. If null, a default will be used instead.
*
* @return The {@link KeenEventStore} to use.
*/
public KeenEventStore getEventStore() {
return eventStore;
}
/**
* Sets the {@link KeenEventStore} to use for storing events in between batch publish
* operations.
*
* @param eventStore The {@link KeenEventStore} to use.
*/
public void setEventStore(KeenEventStore eventStore) {
this.eventStore = eventStore;
}
/**
* Sets the {@link KeenEventStore} to use for storing events in between batch publish
* operations.
*
* @param eventStore The {@link KeenEventStore} to use.
* @return This instance (for method chaining).
*/
public Builder withEventStore(KeenEventStore eventStore) {
setEventStore(eventStore);
return this;
}
/**
* Gets the default {@link Executor} to use if none is explicitly set for this builder.
*
* This implementation returns a simple fixed thread pool with the number of threads equal
* to the number of available processors.
*
* Subclasses should override this to provide an alternative default {@link Executor}.
*
* @return The default {@link Executor}.
* @throws Exception If there is an error creating the {@link Executor}.
*/
protected Executor getDefaultPublishExecutor() throws Exception {
int procCount = Runtime.getRuntime().availableProcessors();
return Executors.newFixedThreadPool(procCount);
}
/**
* Gets the {@link Executor} that this builder is currently configured to use for
* asynchronous publishing operations. If null, a default will be used instead.
*
* @return The {@link Executor} to use.
*/
public Executor getPublishExecutor() {
return publishExecutor;
}
/**
* Sets the {@link Executor} to use for asynchronous publishing operations.
*
* @param publishExecutor The {@link Executor} to use.
*/
public void setPublishExecutor(Executor publishExecutor) {
this.publishExecutor = publishExecutor;
}
/**
* Sets the {@link Executor} to use for asynchronous publishing operations.
*
* @param publishExecutor The {@link Executor} to use.
* @return This instance (for method chaining).
*/
public Builder withPublishExecutor(Executor publishExecutor) {
setPublishExecutor(publishExecutor);
return this;
}
/**
* Builds a new Keen client using the interfaces which have been specified explicitly on
* this builder instance via the set* or with* methods, or the default interfaces if none
* have been specified.
*
* @return A newly constructed Keen client.
*/
public KeenClient build() {
try {
if (httpHandler == null) {
httpHandler = getDefaultHttpHandler();
}
} catch (Exception e) {
KeenLogging.log("Exception building HTTP handler: " + e.getMessage());
}
try {
if (jsonHandler == null) {
jsonHandler = getDefaultJsonHandler();
}
} catch (Exception e) {
KeenLogging.log("Exception building JSON handler: " + e.getMessage());
}
try {
if (eventStore == null) {
eventStore = getDefaultEventStore();
}
} catch (Exception e) {
KeenLogging.log("Exception building event store: " + e.getMessage());
}
try {
if (publishExecutor == null) {
publishExecutor = getDefaultPublishExecutor();
}
} catch (Exception e) {
KeenLogging.log("Exception building publish executor: " + e.getMessage());
}
return buildInstance();
}
/**
* Builds an instance based on this builder. This method is exposed only as a test hook to
* allow test classes to modify how the {@link KeenClient} is constructed (i.e. by
* providing a mock {@link Environment}.
*
* @return The new {@link KeenClient}.
*/
protected KeenClient buildInstance() {
return new KeenClient(this);
}
}
///// PROTECTED CONSTRUCTORS /////
/**
* Constructs a Keen client using system environment variables.
*
* @param builder The builder from which to retrieve this client's interfaces and settings.
*/
protected KeenClient(Builder builder) {
this(builder, new Environment());
}
/**
* Constructs a Keen client using the provided environment.
*
* NOTE: This constructor is only intended for use by test code, and should not be used
* directly. Subclasses should call the default {@link #KeenClient(Builder)} constructor.
*
* @param builder The builder from which to retrieve this client's interfaces and settings.
* @param env The environment to use to attempt to build the default project.
*/
KeenClient(Builder builder, Environment env) {
// Initialize final properties using the builder.
this.httpHandler = builder.httpHandler;
this.jsonHandler = builder.jsonHandler;
this.eventStore = builder.eventStore;
this.publishExecutor = builder.publishExecutor;
// If any of the interfaces are null, mark this client as inactive.
if (httpHandler == null || jsonHandler == null ||
eventStore == null || publishExecutor == null) {
setActive(false);
}
// Initialize other properties.
this.baseUrl = KeenConstants.SERVER_ADDRESS;
this.globalPropertiesEvaluator = null;
this.globalProperties = null;
// If a default project has been specified in environment variables, use it.
if (env.getKeenProjectId() != null) {
defaultProject = new KeenProject(env);
}
}
///// PROTECTED METHODS /////
/**
* Sets whether or not the client is in active mode. When the client is inactive, all requests
* will be ignored.
*
* @param isActive {@code true} to make the client active, or {@code false} to make it
* inactive.
*/
protected void setActive(boolean isActive) {
this.isActive = isActive;
KeenLogging.log("Keen Client set to " + (isActive? "active" : "inactive"));
}
/**
* Validates an event and inserts global properties, producing a new event object which is
* ready to be published to the Keen service.
*
* @param project The project in which the event will be published.
* @param eventCollection The name of the collection in which the event will be published.
* @param event A Map that consists of key/value pairs.
* @param keenProperties A Map that consists of key/value pairs to override default properties.
* @return A new event Map containing Keen properties and global properties.
*/
protected Map<String, Object> validateAndBuildEvent(KeenProject project,
String eventCollection, Map<String, Object> event, Map<String, Object> keenProperties) {
if (project.getWriteKey() == null) {
throw new NoWriteKeyException("You can't send events to Keen IO if you haven't set a write key.");
}
validateEventCollection(eventCollection);
validateEvent(event);
KeenLogging.log(String.format(Locale.US, "Adding event to collection: %s", eventCollection));
// build the event
Map<String, Object> newEvent = new HashMap<String, Object>();
// handle keen properties
Calendar currentTime = Calendar.getInstance();
String timestamp = ISO_8601_FORMAT.format(currentTime.getTime());
if (keenProperties == null) {
keenProperties = new HashMap<String, Object>();
keenProperties.put("timestamp", timestamp);
- } else {
- if (!keenProperties.containsKey("timestamp")) {
- keenProperties.put("timestamp", timestamp);
- }
+ } else if (!keenProperties.containsKey("timestamp")) {
+ // we need to make a copy if we are setting the timestamp since
+ // they might reuse the original keepProperties object.
+ keenProperties = new HashMap<String, Object>(keenProperties);
+ keenProperties.put("timestamp", timestamp);
}
newEvent.put("keen", keenProperties);
// handle global properties
Map<String, Object> globalProperties = getGlobalProperties();
if (globalProperties != null) {
newEvent.putAll(globalProperties);
}
GlobalPropertiesEvaluator globalPropertiesEvaluator = getGlobalPropertiesEvaluator();
if (globalPropertiesEvaluator != null) {
Map<String, Object> props = globalPropertiesEvaluator.getGlobalProperties(eventCollection);
if (props != null) {
newEvent.putAll(props);
}
}
// now handle user-defined properties
newEvent.putAll(event);
return newEvent;
}
///// PRIVATE TYPES /////
/**
* The {@link io.keen.client.java.KeenClient} class's singleton enum.
*/
private enum ClientSingleton {
INSTANCE;
KeenClient client;
}
///// PRIVATE CONSTANTS /////
private static final DateFormat ISO_8601_FORMAT =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);
///// PRIVATE FIELDS /////
private final HttpHandler httpHandler;
private final KeenJsonHandler jsonHandler;
private final KeenEventStore eventStore;
private final Executor publishExecutor;
private boolean isActive = true;
private boolean isDebugMode;
private KeenProject defaultProject;
private String baseUrl;
private GlobalPropertiesEvaluator globalPropertiesEvaluator;
private Map<String, Object> globalProperties;
///// PRIVATE METHODS /////
/**
* Validates the name of an event collection.
*
* @param eventCollection An event collection name to be validated.
* @throws io.keen.client.java.exceptions.InvalidEventCollectionException If the event collection name is invalid. See Keen documentation for details.
*/
private void validateEventCollection(String eventCollection) {
if (eventCollection == null || eventCollection.length() == 0) {
throw new InvalidEventCollectionException("You must specify a non-null, " +
"non-empty event collection: " + eventCollection);
}
if (eventCollection.startsWith("$")) {
throw new InvalidEventCollectionException("An event collection name cannot start with the dollar sign ($)" +
" character.");
}
if (eventCollection.length() > 256) {
throw new InvalidEventCollectionException("An event collection name cannot be longer than 256 characters.");
}
}
/**
* @see #validateEvent(java.util.Map, int)
*/
private void validateEvent(Map<String, Object> event) {
validateEvent(event, 0);
}
/**
* Validates an event.
*
* @param event The event to validate.
* @param depth The number of layers of the map structure that have already been traversed; this
* should be 0 for the initial call and will increment on each recursive call.
*/
@SuppressWarnings("unchecked") // cast to generic Map will always be okay in this case
private void validateEvent(Map<String, Object> event, int depth) {
if (depth == 0) {
if (event == null || event.size() == 0) {
throw new InvalidEventException("You must specify a non-null, non-empty event.");
}
if (event.containsKey("keen")) {
throw new InvalidEventException("An event cannot contain a root-level property named 'keen'.");
}
} else if (depth > KeenConstants.MAX_EVENT_DEPTH) {
throw new InvalidEventException("An event's depth (i.e. layers of nesting) cannot exceed " +
KeenConstants.MAX_EVENT_DEPTH);
}
for (Map.Entry<String, Object> entry : event.entrySet()) {
String key = entry.getKey();
if (key.contains(".")) {
throw new InvalidEventException("An event cannot contain a property with the period (.) character in " +
"it.");
}
if (key.startsWith("$")) {
throw new InvalidEventException("An event cannot contain a property that starts with the dollar sign " +
"($) character in it.");
}
if (key.length() > 256) {
throw new InvalidEventException("An event cannot contain a property name longer than 256 characters.");
}
validateEventValue(entry.getValue(), depth);
}
}
/**
* Validates a value within an event structure. This method will handle validating each element
* in a list, as well as recursively validating nested maps.
*
* @param value The value to validate.
* @param depth The current depth of validation.
*/
@SuppressWarnings("unchecked") // cast to generic Map will always be okay in this case
private void validateEventValue(Object value, int depth) {
if (value instanceof String) {
String strValue = (String) value;
if (strValue.length() >= 10000) {
throw new InvalidEventException("An event cannot contain a string property value longer than 10," +
"000 characters.");
}
} else if (value instanceof Map) {
validateEvent((Map<String, Object>) value, depth + 1);
} else if (value instanceof Iterable) {
for (Object listElement : (Iterable) value) {
validateEventValue(listElement, depth);
}
}
}
/**
* Builds a map from collection name to a list of event maps, given a map from collection name
* to a list of event handles. This method just uses the event store to retrieve each event by
* its handle.
*
* @param eventHandles A map from collection name to a list of event handles in the event store.
* @return A map from collection name to a list of event maps.
* @throws IOException If there is an error retrieving events from the store.
*/
private Map<String, List<Map<String, Object>>> buildEventMap(
Map<String, List<Object>> eventHandles) throws IOException {
Map<String, List<Map<String, Object>>> result =
new HashMap<String, List<Map<String, Object>>>();
for (Map.Entry<String, List<Object>> entry : eventHandles.entrySet()) {
String eventCollection = entry.getKey();
List<Object> handles = entry.getValue();
// Skip event collections that don't contain any events.
if (handles == null || handles.size() == 0) {
continue;
}
// Build the event list by retrieving events from the store.
List<Map<String, Object>> events = new ArrayList<Map<String, Object>>(handles.size());
for (Object handle : handles) {
// Get the event from the store.
String jsonEvent = eventStore.get(handle);
// De-serialize the event from its JSON.
StringReader reader = new StringReader(jsonEvent);
Map<String, Object> event = jsonHandler.readJson(reader);
KeenUtils.closeQuietly(reader);
events.add(event);
}
result.put(eventCollection, events);
}
return result;
}
/**
* Publishes a single event to the Keen service.
*
* @param project The project in which to publish the event.
* @param eventCollection The name of the collection in which to publish the event.
* @param event The event to publish.
* @return The response from the server.
* @throws IOException If there was an error communicating with the server.
*/
private String publish(KeenProject project, String eventCollection,
Map<String, Object> event) throws IOException {
// just using basic JDK HTTP library
String urlString = String.format(Locale.US, "%s/%s/projects/%s/events/%s", getBaseUrl(),
KeenConstants.API_VERSION, project.getProjectId(), eventCollection);
URL url = new URL(urlString);
return publishObject(project, url, event);
}
/**
* Publishes a batch of events to the Keen service.
*
* @param project The project in which to publish the event.
* @param events A map from collection name to a list of event maps.
* @return The response from the server.
* @throws IOException If there was an error communicating with the server.
*/
private String publishAll(KeenProject project,
Map<String, List<Map<String, Object>>> events) throws IOException {
// just using basic JDK HTTP library
String urlString = String.format(Locale.US, "%s/%s/projects/%s/events", getBaseUrl(),
KeenConstants.API_VERSION, project.getProjectId());
URL url = new URL(urlString);
return publishObject(project, url, events);
}
/**
* Posts a request to the server in the specified project, using the given URL and request data.
* The request data will be serialized into JSON using the client's
* {@link io.keen.client.java.KeenJsonHandler}.
*
* @param project The project in which the event(s) will be published; this is used to
* determine the write key to use for authentication.
* @param url The URL to which the POST should be sent.
* @param requestData The request data, which will be serialized into JSON and sent in the
* request body.
* @return The response from the server.
* @throws IOException If there was an error communicating with the server.
*/
private synchronized String publishObject(KeenProject project, URL url,
final Map<String, ?> requestData) throws IOException {
if (requestData == null || requestData.size() == 0) {
KeenLogging.log("No API calls were made because there were no events to upload");
return null;
}
// Build an output source which simply writes the serialized JSON to the output.
OutputSource source = new OutputSource() {
@Override
public void writeTo(OutputStream out) throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(out, ENCODING);
jsonHandler.writeJson(writer, requestData);
}
};
// If logging is enabled, log the request being sent.
if (KeenLogging.isLoggingEnabled()) {
try {
StringWriter writer = new StringWriter();
jsonHandler.writeJson(writer, requestData);
String request = writer.toString();
KeenLogging.log(String.format(Locale.US, "Sent request '%s' to URL '%s'",
request, url.toString()));
} catch (IOException e) {
KeenLogging.log("Couldn't log event written to file: ");
e.printStackTrace();
}
}
// Send the request.
String writeKey = project.getWriteKey();
Request request = new Request(url, "POST", writeKey, source);
Response response = httpHandler.execute(request);
// If logging is enabled, log the response.
if (KeenLogging.isLoggingEnabled()) {
KeenLogging.log(String.format(Locale.US,
"Received response: '%s' (%d)", response.body,
response.statusCode));
}
// If the request succeeded, return the response body. Otherwise throw an exception.
if (response.isSuccess()) {
return response.body;
} else {
throw new ServerException(response.body);
}
}
///// PRIVATE CONSTANTS /////
private static final String ENCODING = "UTF-8";
/**
* Handles a response from the Keen service to a batch post events operation. In particular,
* this method will iterate through the responses and remove any successfully processed events
* (or events which failed for known fatal reasons) from the event store so they won't be sent
* in subsequent posts.
*
* @param handles A map from collection names to lists of handles in the event store. This is
* referenced against the response from the server to determine which events to
* remove from the store.
* @param response The response from the server.
* @throws IOException If there is an error removing events from the store.
*/
@SuppressWarnings("unchecked")
private void handleAddEventsResponse(Map<String, List<Object>> handles, String response) throws IOException {
// Parse the response into a map.
StringReader reader = new StringReader(response);
Map<String, Object> responseMap;
responseMap = jsonHandler.readJson(reader);
// It's not obvious what the best way is to try and recover from them, but just hoping it
// doesn't happen is probably the wrong answer.
// Loop through all the event collections.
for (Map.Entry<String, Object> entry : responseMap.entrySet()) {
String collectionName = entry.getKey();
// Get the list of handles in this collection.
List<Object> collectionHandles = handles.get(collectionName);
// Iterate through the elements in the collection
List<Map<String, Object>> eventResults = (List<Map<String, Object>>) entry.getValue();
int index = 0;
for (Map<String, Object> eventResult : eventResults) {
// now loop through each event collection's individual results
boolean removeCacheEntry = true;
boolean success = (Boolean) eventResult.get(KeenConstants.SUCCESS_PARAM);
if (!success) {
// grab error code and description
Map errorDict = (Map) eventResult.get(KeenConstants.ERROR_PARAM);
String errorCode = (String) errorDict.get(KeenConstants.NAME_PARAM);
if (errorCode.equals(KeenConstants.INVALID_COLLECTION_NAME_ERROR) ||
errorCode.equals(KeenConstants.INVALID_PROPERTY_NAME_ERROR) ||
errorCode.equals(KeenConstants.INVALID_PROPERTY_VALUE_ERROR)) {
removeCacheEntry = true;
KeenLogging.log("An invalid event was found. Deleting it. Error: " +
errorDict.get(KeenConstants.DESCRIPTION_PARAM));
} else {
String description = (String) errorDict.get(KeenConstants.DESCRIPTION_PARAM);
removeCacheEntry = false;
KeenLogging.log(String.format(Locale.US,
"The event could not be inserted for some reason. " +
"Error name and description: %s %s", errorCode,
description));
}
}
// If the cache entry should be removed, get the handle at the appropriate index
// and ask the event store to remove it.
if (removeCacheEntry) {
Object handle = collectionHandles.get(index);
// Try to remove the object from the cache. Catch and log exceptions to prevent
// a single failure from derailing the rest of the cleanup.
try {
eventStore.remove(handle);
} catch (IOException e) {
KeenLogging.log("Failed to remove object '" + handle + "' from cache");
}
}
index++;
}
}
}
/**
* Reports success to a callback. If the callback is null, this is a no-op. Any exceptions
* thrown by the callback are silently ignored.
*
* @param callback A callback; may be null.
*/
private void handleSuccess(KeenCallback callback) {
if (callback != null) {
try {
callback.onSuccess();
} catch (Exception userException) {
// Do nothing.
}
}
}
/**
* Handles a failure in the Keen library. If the client is running in debug mode, this will
* immediately throw a runtime exception. Otherwise, this will log an error message and, if the
* callback is non-null, call the {@link KeenCallback#onFailure(Exception)} method. Any
* exceptions thrown by the callback are silently ignored.
*
* @param callback A callback; may be null.
* @param e The exception which caused the failure.
*/
private void handleFailure(KeenCallback callback, Exception e) {
if (isDebugMode) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else {
throw new RuntimeException(e);
}
} else {
KeenLogging.log("Encountered error: " + e.getMessage());
if (callback != null) {
try {
callback.onFailure(e);
} catch (Exception userException) {
// Do nothing.
}
}
}
}
/**
* Reports failure when the library is inactive due to failed initialization.
*
* @param callback A callback; may be null.
*/
// TODO: Cap how many times this failure is reported, and after that just fail silently.
private void handleLibraryInactive(KeenCallback callback) {
handleFailure(callback, new IllegalStateException("The Keen library failed to initialize " +
"properly and is inactive"));
}
}
diff --git a/core/src/test/java/io/keen/client/java/KeenClientTest.java b/core/src/test/java/io/keen/client/java/KeenClientTest.java
index c5196fc..b6a4a07 100644
--- a/core/src/test/java/io/keen/client/java/KeenClientTest.java
+++ b/core/src/test/java/io/keen/client/java/KeenClientTest.java
@@ -1,583 +1,599 @@
package io.keen.client.java;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import io.keen.client.java.exceptions.KeenException;
import io.keen.client.java.exceptions.NoWriteKeyException;
import io.keen.client.java.exceptions.ServerException;
import io.keen.client.java.http.HttpHandler;
import io.keen.client.java.http.Request;
import io.keen.client.java.http.Response;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* KeenClientTest
*
* @author dkador
* @since 1.0.0
*/
public class KeenClientTest {
private static KeenProject TEST_PROJECT;
private static List<Map<String, Object>> TEST_EVENTS;
private static final String TEST_COLLECTION = "test_collection";
private static final String TEST_COLLECTION_2 = "test_collection_2";
private static final String POST_EVENT_SUCCESS = "{\"created\": true}";
/**
* JSON object mapper that the test infrastructure can use without worrying about any
* interference with the Keen library's JSON handler.
*/
private static ObjectMapper JSON_MAPPER;
private KeenClient client;
private HttpHandler mockHttpHandler;
@BeforeClass
public static void classSetUp() {
KeenLogging.enableLogging();
TEST_PROJECT = new KeenProject("<project ID>", "<write key>", "<read key");
TEST_EVENTS = new ArrayList<Map<String, Object>>();
for (int i = 0; i < 10; i++) {
Map<String, Object> event = new HashMap<String, Object>();
event.put("test-key", "test-value-" + i);
TEST_EVENTS.add(event);
}
JSON_MAPPER = new ObjectMapper();
JSON_MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
}
@Before
public void setup() throws IOException {
// Set up a mock HTTP handler.
mockHttpHandler = mock(HttpHandler.class);
setMockResponse(500, "Unexpected HTTP request");
// Build the client.
client = new TestKeenClientBuilder()
.withHttpHandler(mockHttpHandler)
.build();
client.setBaseUrl(null);
client.setDebugMode(true);
client.setDefaultProject(TEST_PROJECT);
// Clear the RAM event store.
((RamEventStore) client.getEventStore()).clear();
}
@After
public void cleanUp() {
client = null;
}
@Test
public void initializeWithEnvironmentVariables() throws Exception {
// Construct a new test client and make sure it doesn't have a default project.
KeenClient testClient = new TestKeenClientBuilder().build();
assertNull(testClient.getDefaultProject());
// Mock an environment with a project.
Environment mockEnv = mock(Environment.class);
when(mockEnv.getKeenProjectId()).thenReturn("<project ID>");
// Make sure a new test client using the mock environment has the expected default project.
testClient = new TestKeenClientBuilder(mockEnv).build();
KeenProject defaultProject = testClient.getDefaultProject();
assertNotNull(defaultProject);
assertEquals("<project ID>", defaultProject.getProjectId());
}
@Test
public void testInvalidEventCollection() throws KeenException {
runValidateAndBuildEventTest(TestUtils.getSimpleEvent(), "$asd", "collection can't start with $",
"An event collection name cannot start with the dollar sign ($) character.");
String tooLong = TestUtils.getString(257);
runValidateAndBuildEventTest(TestUtils.getSimpleEvent(), tooLong, "collection can't be longer than 256 chars",
"An event collection name cannot be longer than 256 characters.");
}
@Test
public void nullEvent() throws Exception {
runValidateAndBuildEventTest(null, "foo", "null event",
"You must specify a non-null, non-empty event.");
}
@Test
public void emptyEvent() throws Exception {
runValidateAndBuildEventTest(new HashMap<String, Object>(), "foo", "empty event",
"You must specify a non-null, non-empty event.");
}
@Test
public void eventWithKeenRootProperty() throws Exception {
Map<String, Object> event = new HashMap<String, Object>();
event.put("keen", "reserved");
runValidateAndBuildEventTest(event, "foo", "keen reserved",
"An event cannot contain a root-level property named 'keen'.");
}
@Test
public void eventWithDotInPropertyName() throws Exception {
Map<String, Object> event = new HashMap<String, Object>();
event.put("ab.cd", "whatever");
runValidateAndBuildEventTest(event, "foo", ". in property name",
"An event cannot contain a property with the period (.) character in it.");
}
@Test
public void eventWithInitialDollarPropertyName() throws Exception {
Map<String, Object> event = new HashMap<String, Object>();
event.put("$a", "whatever");
runValidateAndBuildEventTest(event, "foo", "$ at start of property name",
"An event cannot contain a property that starts with the dollar sign ($) " +
"character in it.");
}
@Test
public void eventWithTooLongPropertyName() throws Exception {
Map<String, Object> event = new HashMap<String, Object>();
String tooLong = TestUtils.getString(257);
event.put(tooLong, "whatever");
runValidateAndBuildEventTest(event, "foo", "too long property name",
"An event cannot contain a property name longer than 256 characters.");
}
@Test
public void eventWithTooLongStringValue() throws Exception {
Map<String, Object> event = new HashMap<String, Object>();
String tooLong = TestUtils.getString(10000);
event.put("long", tooLong);
runValidateAndBuildEventTest(event, "foo", "too long property value",
"An event cannot contain a string property value longer than 10,000 characters.");
}
@Test
public void eventWithSelfReferencingProperty() throws Exception {
Map<String, Object> event = new HashMap<String, Object>();
event.put("recursion", event);
runValidateAndBuildEventTest(event, "foo", "self referencing",
"An event's depth (i.e. layers of nesting) cannot exceed " + KeenConstants.MAX_EVENT_DEPTH);
}
@Test
public void eventWithInvalidPropertyInList() throws Exception {
Map<String, Object> event = new HashMap<String, Object>();
List<String> invalidList = new ArrayList<String>();
String tooLong = TestUtils.getString(10000);
invalidList.add(tooLong);
event.put("invalid_list", invalidList);
runValidateAndBuildEventTest(event, "foo", "invalid value in list",
"An event cannot contain a string property value longer than 10,000 characters.");
}
@Test
public void validEvent() throws Exception {
Map<String, Object> event = new HashMap<String, Object>();
event.put("valid key", "valid value");
Map<String, Object> builtEvent = client.validateAndBuildEvent(client.getDefaultProject(), "foo", event, null);
assertNotNull(builtEvent);
assertEquals("valid value", builtEvent.get("valid key"));
// also make sure the event has been timestamped
@SuppressWarnings("unchecked")
Map<String, Object> keenNamespace = (Map<String, Object>) builtEvent.get("keen");
assertNotNull(keenNamespace);
assertNotNull(keenNamespace.get("timestamp"));
}
@Test
public void validEventWithTimestamp() throws Exception {
Map<String, Object> event = new HashMap<String, Object>();
event.put("valid key", "valid value");
Calendar now = Calendar.getInstance();
event.put("datetime", now);
client.validateAndBuildEvent(client.getDefaultProject(), "foo", event, null);
}
@Test
+ public void validEventWithKeenPropertiesWithoutTimestamp() throws Exception {
+ Map<String, Object> event = new HashMap<String, Object>();
+ event.put("valid key", "valid value");
+ Map<String, Object> keenProperties = new HashMap<String, Object>();
+ keenProperties.put("keen key", "keen value");
+ Map<String, Object> result = client.validateAndBuildEvent(client.getDefaultProject(), "foo", event, keenProperties);
+ @SuppressWarnings("unchecked")
+ Map<String, Object> keenPropResult = (Map<String, Object>)result.get("keen");
+ assertNotNull(keenPropResult.get("timestamp"));
+ assertNull(keenProperties.get("timestamp"));
+ assertEquals(keenProperties.get("keen key"), "keen value");
+ assertEquals(keenPropResult.get("keen key"), "keen value");
+ assertEquals(keenProperties.get("keen key"), keenPropResult.get("keen key"));
+ }
+
+ @Test
public void validEventWithNestedKeenProperty() throws Exception {
Map<String, Object> event = TestUtils.getSimpleEvent();
Map<String, Object> nested = new HashMap<String, Object>();
nested.put("keen", "value");
event.put("nested", nested);
client.validateAndBuildEvent(client.getDefaultProject(), "foo", event, null);
}
@Test
public void testAddEventNoWriteKey() throws KeenException, IOException {
client.setDefaultProject(new KeenProject("508339b0897a2c4282000000", null, null));
Map<String, Object> event = new HashMap<String, Object>();
event.put("test key", "test value");
try {
client.addEvent("foo", event);
fail("add event without write key should fail");
} catch (NoWriteKeyException e) {
assertEquals("You can't send events to Keen IO if you haven't set a write key.",
e.getLocalizedMessage());
}
}
@Test
public void testAddEvent() throws Exception {
setMockResponse(201, POST_EVENT_SUCCESS);
client.addEvent(TEST_COLLECTION, TEST_EVENTS.get(0));
ArgumentCaptor<Request> capturedRequest = ArgumentCaptor.forClass(Request.class);
verify(mockHttpHandler).execute(capturedRequest.capture());
assertThat(capturedRequest.getValue().url.toString(), startsWith("https://api.keen.io"));
}
@Test
public void testAddEventNonSSL() throws Exception {
setMockResponse(201, POST_EVENT_SUCCESS);
client.setBaseUrl("http://api.keen.io");
client.addEvent(TEST_COLLECTION, TEST_EVENTS.get(0));
ArgumentCaptor<Request> capturedRequest = ArgumentCaptor.forClass(Request.class);
verify(mockHttpHandler).execute(capturedRequest.capture());
assertThat(capturedRequest.getValue().url.toString(), startsWith("http://api.keen.io"));
}
@Test(expected = ServerException.class)
public void testAddEventServerFailure() throws Exception {
setMockResponse(500, "Injected server error");
client.addEvent(TEST_COLLECTION, TEST_EVENTS.get(0));
}
@Test
public void testAddEventWithCallback() throws Exception {
setMockResponse(201, POST_EVENT_SUCCESS);
final CountDownLatch latch = new CountDownLatch(1);
client.addEvent(null, TEST_COLLECTION, TEST_EVENTS.get(0), null, new LatchKeenCallback(latch));
latch.await(2, TimeUnit.SECONDS);
}
@Test
public void testSendQueuedEvents() throws Exception {
// Mock the response from the server.
Map<String, Integer> expectedResponse = new HashMap<String, Integer>();
expectedResponse.put(TEST_COLLECTION, 3);
setMockResponse(200, getPostEventsResponse(buildSuccessMap(expectedResponse)));
// Queue some events.
client.queueEvent(TEST_COLLECTION, TEST_EVENTS.get(0));
client.queueEvent(TEST_COLLECTION, TEST_EVENTS.get(1));
client.queueEvent(TEST_COLLECTION, TEST_EVENTS.get(2));
// Check that the expected number of events are in the store.
RamEventStore store = (RamEventStore) client.getEventStore();
Map<String, List<Object>> handleMap = store.getHandles(TEST_PROJECT.getProjectId());
assertEquals(1, handleMap.size());
assertEquals(3, handleMap.get(TEST_COLLECTION).size());
// Send the queued events.
client.sendQueuedEvents();
// Validate that the store is now empty.
handleMap = store.getHandles(TEST_PROJECT.getProjectId());
assertEquals(0, handleMap.size());
// Try sending events again; this should be a no-op.
setMockResponse(200, "{}");
client.sendQueuedEvents();
// Validate that the store is still empty.
handleMap = store.getHandles(TEST_PROJECT.getProjectId());
assertEquals(0, handleMap.size());
}
@Test
public void testSendQueuedEventsWithSingleFailure() throws Exception {
// Queue some events.
client.queueEvent(TEST_COLLECTION, TEST_EVENTS.get(0));
client.queueEvent(TEST_COLLECTION, TEST_EVENTS.get(1));
client.queueEvent(TEST_COLLECTION, TEST_EVENTS.get(2));
// Check that the expected number of events are in the store.
RamEventStore store = (RamEventStore) client.getEventStore();
Map<String, List<Object>> handleMap = store.getHandles(TEST_PROJECT.getProjectId());
assertEquals(1, handleMap.size());
assertEquals(3, handleMap.get(TEST_COLLECTION).size());
// Mock a response containing an error.
Map<String, Integer> expectedResponse = new HashMap<String, Integer>();
expectedResponse.put(TEST_COLLECTION, 3);
Map<String, Object> responseMap = buildSuccessMap(expectedResponse);
replaceSuccessWithFailure(responseMap, TEST_COLLECTION, 2, "TestInjectedError",
"This is an error injected by the unit test code");
setMockResponse(200, getPostEventsResponse(responseMap));
// Send the events.
client.sendQueuedEvents();
// Validate that the store still contains the failed event, but not the other events.
handleMap = store.getHandles(TEST_PROJECT.getProjectId());
assertEquals(1, handleMap.size());
List<Object> handles = handleMap.get(TEST_COLLECTION);
assertEquals(1, handles.size());
Object handle = handles.get(0);
assertThat(store.get(handle), containsString("test-value-2"));
}
@Test
public void testSendQueuedEventsWithServerFailure() throws Exception {
// Queue some events.
client.queueEvent(TEST_COLLECTION, TEST_EVENTS.get(0));
client.queueEvent(TEST_COLLECTION, TEST_EVENTS.get(1));
client.queueEvent(TEST_COLLECTION, TEST_EVENTS.get(2));
// Mock a server failure.
setMockResponse(500, "Injected server failure");
// Send the events.
try {
client.sendQueuedEvents();
} catch (ServerException e) {
// This exception is expected; continue.
}
// Validate that the store still contains all the events.
RamEventStore store = (RamEventStore) client.getEventStore();
Map<String, List<Object>> handleMap = store.getHandles(TEST_PROJECT.getProjectId());
assertEquals(1, handleMap.size());
List<Object> handles = handleMap.get(TEST_COLLECTION);
assertEquals(3, handles.size());
}
@Test
public void testSendQueuedEventsConcurrentProjects() throws Exception {
// Queue some events in each of two separate projects
KeenProject otherProject = new KeenProject("<other project>", "<write>", "<read>");
client.queueEvent(TEST_PROJECT, TEST_COLLECTION, TEST_EVENTS.get(0), null, null);
client.queueEvent(TEST_PROJECT, TEST_COLLECTION_2, TEST_EVENTS.get(1), null, null);
client.queueEvent(otherProject, TEST_COLLECTION, TEST_EVENTS.get(2), null, null);
client.queueEvent(otherProject, TEST_COLLECTION, TEST_EVENTS.get(3), null, null);
// Check that the expected number of events are in the store, in the expected collections
RamEventStore store = (RamEventStore) client.getEventStore();
Map<String, List<Object>> handleMap = store.getHandles(TEST_PROJECT.getProjectId());
assertEquals(2, handleMap.size());
assertEquals(1, handleMap.get(TEST_COLLECTION).size());
assertEquals(1, handleMap.get(TEST_COLLECTION_2).size());
handleMap = store.getHandles(otherProject.getProjectId());
assertEquals(1, handleMap.size());
assertEquals(2, handleMap.get(TEST_COLLECTION).size());
}
@Test
public void testGlobalPropertiesMap() throws Exception {
// a null map should be okay
runGlobalPropertiesMapTest(null, 1);
// an empty map should be okay
runGlobalPropertiesMapTest(new HashMap<String, Object>(), 1);
// a map w/ non-conflicting property names should be okay
Map<String, Object> globals = new HashMap<String, Object>();
globals.put("default name", "default value");
Map<String, Object> builtEvent = runGlobalPropertiesMapTest(globals, 2);
assertEquals("default value", builtEvent.get("default name"));
// a map that returns a conflicting property name should not overwrite the property on the event
globals = new HashMap<String, Object>();
globals.put("a", "c");
builtEvent = runGlobalPropertiesMapTest(globals, 1);
assertEquals("b", builtEvent.get("a"));
}
private Map<String, Object> runGlobalPropertiesMapTest(Map<String, Object> globalProperties,
int expectedNumProperties) throws Exception {
client.setGlobalProperties(globalProperties);
Map<String, Object> event = TestUtils.getSimpleEvent();
String eventCollection = String.format("foo%d", Calendar.getInstance().getTimeInMillis());
Map<String, Object> builtEvent = client.validateAndBuildEvent(client.getDefaultProject(), eventCollection, event, null);
assertEquals(expectedNumProperties + 1, builtEvent.size());
return builtEvent;
}
@Test
public void testGlobalPropertiesEvaluator() throws Exception {
// a null evaluator should be okay
runGlobalPropertiesEvaluatorTest(null, 1);
// an evaluator that returns an empty map should be okay
GlobalPropertiesEvaluator evaluator = new GlobalPropertiesEvaluator() {
@Override
public Map<String, Object> getGlobalProperties(String eventCollection) {
return new HashMap<String, Object>();
}
};
runGlobalPropertiesEvaluatorTest(evaluator, 1);
// an evaluator that returns a map w/ non-conflicting property names should be okay
evaluator = new GlobalPropertiesEvaluator() {
@Override
public Map<String, Object> getGlobalProperties(String eventCollection) {
Map<String, Object> globals = new HashMap<String, Object>();
globals.put("default name", "default value");
return globals;
}
};
Map<String, Object> builtEvent = runGlobalPropertiesEvaluatorTest(evaluator, 2);
assertEquals("default value", builtEvent.get("default name"));
// an evaluator that returns a map w/ conflicting property name should not overwrite the property on the event
evaluator = new GlobalPropertiesEvaluator() {
@Override
public Map<String, Object> getGlobalProperties(String eventCollection) {
Map<String, Object> globals = new HashMap<String, Object>();
globals.put("a", "c");
return globals;
}
};
builtEvent = runGlobalPropertiesEvaluatorTest(evaluator, 1);
assertEquals("b", builtEvent.get("a"));
}
private Map<String, Object> runGlobalPropertiesEvaluatorTest(GlobalPropertiesEvaluator evaluator,
int expectedNumProperties) throws Exception {
client.setGlobalPropertiesEvaluator(evaluator);
Map<String, Object> event = TestUtils.getSimpleEvent();
String eventCollection = String.format("foo%d", Calendar.getInstance().getTimeInMillis());
Map<String, Object> builtEvent = client.validateAndBuildEvent(client.getDefaultProject(), eventCollection, event, null);
assertEquals(expectedNumProperties + 1, builtEvent.size());
return builtEvent;
}
@Test
public void testGlobalPropertiesTogether() throws Exception {
// properties from the evaluator should take precedence over properties from the map
// but properties from the event itself should take precedence over all
Map<String, Object> globalProperties = new HashMap<String, Object>();
globalProperties.put("default property", 5);
globalProperties.put("foo", "some new value");
GlobalPropertiesEvaluator evaluator = new GlobalPropertiesEvaluator() {
@Override
public Map<String, Object> getGlobalProperties(String eventCollection) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("default property", 6);
map.put("foo", "some other value");
return map;
}
};
client.setGlobalProperties(globalProperties);
client.setGlobalPropertiesEvaluator(evaluator);
Map<String, Object> event = new HashMap<String, Object>();
event.put("foo", "bar");
Map<String, Object> builtEvent = client.validateAndBuildEvent(client.getDefaultProject(), "apples", event, null);
assertEquals("bar", builtEvent.get("foo"));
assertEquals(6, builtEvent.get("default property"));
assertEquals(3, builtEvent.size());
}
private void runValidateAndBuildEventTest(Map<String, Object> event, String eventCollection, String msg,
String expectedMessage) {
try {
client.validateAndBuildEvent(client.getDefaultProject(), eventCollection, event, null);
fail(msg);
} catch (KeenException e) {
assertEquals(expectedMessage, e.getLocalizedMessage());
}
}
private void setMockResponse(int statusCode, String body) throws IOException {
Response response = new Response(statusCode, body);
when(mockHttpHandler.execute(any(Request.class))).thenReturn(response);
}
private Map<String, Object> buildSuccessMap(Map<String, Integer> postedEvents) throws IOException {
// Build a map that will represent the response.
Map<String, Object> response = new HashMap<String, Object>();
// Create a single map for a successfully posted event; this can be reused for each event.
final Map<String, Boolean> success = new HashMap<String, Boolean>();
success.put("success", true);
// Build the response map by creating a list of the appropriate number of successes for
// each event collection.
for (Map.Entry<String, Integer> entry : postedEvents.entrySet()) {
List<Map<String, Boolean>> list = new ArrayList<Map<String, Boolean>>();
for (int i = 0; i < entry.getValue(); i++) {
list.add(success);
}
response.put(entry.getKey(), list);
}
// Return the success map.
return response;
}
@SuppressWarnings("unchecked")
private void replaceSuccessWithFailure(Map<String, Object> response, String collection,
int index, String errorName, String errorDescription) {
// Build the failure map.
Map<String, Object> failure = new HashMap<String, Object>();
failure.put("success", Boolean.FALSE);
Map<String, String> reason = new HashMap<String, String>();
reason.put("name", errorName);
reason.put("description", errorDescription);
failure.put("error", reason);
// Replace the element at the appropriate index with the failure.
List<Object> eventStatuses = (List<Object>) response.get(collection);
eventStatuses.set(index, failure);
}
private String getPostEventsResponse(Map<String, Object> postedEvents) throws IOException {
return JSON_MAPPER.writeValueAsString(postedEvents);
}
private static class LatchKeenCallback implements KeenCallback {
private final CountDownLatch latch;
LatchKeenCallback(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void onSuccess() {
latch.countDown();
}
@Override
public void onFailure(Exception e) {
}
}
}
| false | false | null | null |
diff --git a/src/rajawali/materials/ParticleMaterial.java b/src/rajawali/materials/ParticleMaterial.java
index 20b83171..f284278a 100644
--- a/src/rajawali/materials/ParticleMaterial.java
+++ b/src/rajawali/materials/ParticleMaterial.java
@@ -1,192 +1,192 @@
package rajawali.materials;
import java.nio.FloatBuffer;
import rajawali.math.Number3D;
import android.opengl.GLES20;
public class ParticleMaterial extends AParticleMaterial {
protected static final String mVShader =
"precision mediump float;\n" +
"uniform mat4 uMVPMatrix;\n" +
"uniform float uPointSize;\n" +
"uniform mat4 uMMatrix;\n" +
"uniform vec3 uCamPos;\n" +
"uniform vec3 uDistanceAtt;\n" +
"uniform vec3 uFriction;\n" +
"uniform float uTime;\n" +
"uniform bool uMultiParticlesEnabled;\n" +
"#ifdef ANIMATED\n" +
"uniform float uCurrentFrame;\n" +
"uniform float uTileSize;\n" +
"uniform float uNumTileRows;\n" +
"attribute float aAnimOffset;\n" +
"#endif\n" +
"attribute vec4 aPosition;\n" +
"attribute vec2 aTextureCoord;\n" +
"attribute vec3 aVelocity;\n" +
"varying vec2 vTextureCoord;\n" +
"void main() {\n" +
" vec4 position = vec4(aPosition);\n" +
" if(uMultiParticlesEnabled){" +
" position.x += aVelocity.x * uFriction.x * uTime;\n" +
" position.y += aVelocity.y * uFriction.y * uTime;\n" +
" position.z += aVelocity.z * uFriction.z * uTime; }" +
" gl_Position = uMVPMatrix * position;\n" +
" vec3 cp = vec3(uCamPos);\n" +
" float pdist = length(cp - position.xyz);\n" +
" gl_PointSize = uPointSize / sqrt(uDistanceAtt.x + uDistanceAtt.y * pdist + uDistanceAtt.z * pdist * pdist);\n" +
" #ifdef ANIMATED\n" +
" vTextureCoord.s = mod(uCurrentFrame + aAnimOffset, uNumTileRows) * uTileSize;" +
" vTextureCoord.t = uTileSize * floor((uCurrentFrame + aAnimOffset ) / uNumTileRows);\n" +
" #else\n" +
" vTextureCoord = aTextureCoord;\n" +
" #endif\n" +
"}\n";
protected static final String mFShader =
"precision mediump float;\n" +
"varying vec2 vTextureCoord;\n" +
"uniform sampler2D uDiffuseTexture;\n" +
"#ifdef ANIMATED\n" +
"uniform float uTileSize;\n" +
"uniform float uNumTileRows;\n" +
"#endif\n" +
"void main() {\n" +
" \n#ifdef ANIMATED\n" +
" vec2 realTexCoord = vTextureCoord + (gl_PointCoord / uNumTileRows);" +
" gl_FragColor = texture2D(uDiffuseTexture, realTexCoord);\n" +
" #else\n" +
" gl_FragColor = texture2D(uDiffuseTexture, gl_PointCoord);\n" +
" #endif\n" +
"}\n";
protected float mPointSize = 10.0f;
protected int muPointSizeHandle;
protected int muCamPosHandle;
protected int muDistanceAttHandle;
protected int muCurrentFrameHandle;
protected int muTileSizeHandle;
protected int muNumTileRowsHandle;
protected int maVelocityHandle;
protected int maAnimOffsetHandle;
protected int muFrictionHandle;
protected int muTimeHandle;
protected int muMultiParticlesEnabledHandle;
protected float[] mDistanceAtt;
protected boolean mMultiParticlesEnabled;
protected float[] mFriction;
protected float[] mCamPos;
protected float mTime;
protected int mCurrentFrame;
protected float mTileSize;
protected float mNumTileRows;
protected boolean mIsAnimated;
public ParticleMaterial() {
this(false);
}
public ParticleMaterial(boolean isAnimated) {
this(mVShader, mFShader, isAnimated);
}
public ParticleMaterial(String vertexShader, String fragmentShader, boolean isAnimated) {
super(vertexShader, fragmentShader, NONE);
mDistanceAtt = new float[] {1, 1, 1};
mFriction = new float[3];
mCamPos = new float[3];
mIsAnimated = isAnimated;
if(mIsAnimated) {
mUntouchedVertexShader = "\n#define ANIMATED\n" + mUntouchedVertexShader;
mUntouchedFragmentShader = "\n#define ANIMATED\n" + mUntouchedFragmentShader;
}
setShaders(mUntouchedVertexShader, mUntouchedFragmentShader);
}
public void setPointSize(float pointSize) {
mPointSize = pointSize;
GLES20.glUniform1f(muPointSizeHandle, mPointSize);
}
public void setMultiParticlesEnabled(boolean enabled) {
mMultiParticlesEnabled = enabled;
GLES20.glUniform1i(muMultiParticlesEnabledHandle, mMultiParticlesEnabled == true ? GLES20.GL_TRUE : GLES20.GL_FALSE);
}
@Override
public void useProgram() {
super.useProgram();
+ GLES20.glUniform3fv(muCamPosHandle, 1, mCamPos, 0);
+ GLES20.glUniform3fv(muDistanceAttHandle, 1, mDistanceAtt, 0);
+ GLES20.glUniform3fv(muFrictionHandle, 1, mFriction, 0);
+ GLES20.glUniform1f(muTimeHandle, mTime);
+ GLES20.glUniform1f(muCurrentFrameHandle, mCurrentFrame);
+ GLES20.glUniform1f(muTileSizeHandle, mTileSize);
+ GLES20.glUniform1f(muNumTileRowsHandle, mNumTileRows);
}
public void setVelocity(final int velocityBufferHandle) {
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, velocityBufferHandle);
GLES20.glEnableVertexAttribArray(maVelocityHandle);
fix.android.opengl.GLES20.glVertexAttribPointer(maVelocityHandle, 3, GLES20.GL_FLOAT, false,
0, 0);
}
public void setFriction(Number3D friction) {
mFriction[0] = friction.x; mFriction[1] = friction.y; mFriction[2] = friction.z;
- GLES20.glUniform3fv(muFrictionHandle, 1, mFriction, 0);
}
public void setTime(float time) {
mTime = time;
- GLES20.glUniform1f(muTimeHandle, mTime);
}
@Override
public void setShaders(String vertexShader, String fragmentShader)
{
super.setShaders(vertexShader, fragmentShader);
muPointSizeHandle = getUniformLocation("uPointSize");
muDistanceAttHandle = getUniformLocation("uDistanceAtt");
maVelocityHandle = getAttribLocation("aVelocity");
maAnimOffsetHandle = getAttribLocation("aAnimOffset");
muFrictionHandle = getUniformLocation("uFriction");
muTimeHandle = getUniformLocation("uTime");
muMultiParticlesEnabledHandle = getUniformLocation("uMultiParticlesEnabled");
muCurrentFrameHandle = getUniformLocation("uCurrentFrame");
muTileSizeHandle = getUniformLocation("uTileSize");
muNumTileRowsHandle = getUniformLocation("uNumTileRows");
}
public void setAnimOffsets(FloatBuffer animOffsets) {
GLES20.glEnableVertexAttribArray(maAnimOffsetHandle);
GLES20.glVertexAttribPointer(maAnimOffsetHandle, 1, GLES20.GL_FLOAT, false, 0, animOffsets);
}
public void setCurrentFrame(int currentFrame) {
mCurrentFrame = currentFrame;
- GLES20.glUniform1f(muCurrentFrameHandle, mCurrentFrame);
}
public void setTileSize(float tileSize) {
mTileSize = tileSize;
- GLES20.glUniform1f(muTileSizeHandle, mTileSize);
}
public void setNumTileRows(int numTileRows) {
mNumTileRows = numTileRows;
- GLES20.glUniform1f(muNumTileRowsHandle, mNumTileRows);
}
public void setCameraPosition(Number3D cameraPos) {
mCamPos[0] = cameraPos.x; mCamPos[1] = cameraPos.y; mCamPos[2] = cameraPos.z;
- GLES20.glUniform3fv(muCamPosHandle, 1, mCamPos, 0);
- GLES20.glUniform3fv(muDistanceAttHandle, 1, mDistanceAtt, 0);
}
}
| false | false | null | null |
diff --git a/flume-ng-node/src/test/java/org/apache/flume/conf/file/TestJsonFileConfigurationProvider.java b/flume-ng-node/src/test/java/org/apache/flume/conf/file/TestJsonFileConfigurationProvider.java
index 00e1cdae..d4bff2ac 100644
--- a/flume-ng-node/src/test/java/org/apache/flume/conf/file/TestJsonFileConfigurationProvider.java
+++ b/flume-ng-node/src/test/java/org/apache/flume/conf/file/TestJsonFileConfigurationProvider.java
@@ -1,103 +1,106 @@
package org.apache.flume.conf.file;
import java.io.File;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.flume.Channel;
import org.apache.flume.ChannelFactory;
import org.apache.flume.SinkFactory;
import org.apache.flume.SourceFactory;
import org.apache.flume.SourceRunner;
import org.apache.flume.channel.DefaultChannelFactory;
import org.apache.flume.channel.MemoryChannel;
import org.apache.flume.node.NodeConfiguration;
import org.apache.flume.node.nodemanager.NodeConfigurationAware;
import org.apache.flume.sink.DefaultSinkFactory;
import org.apache.flume.sink.LoggerSink;
import org.apache.flume.sink.NullSink;
import org.apache.flume.source.DefaultSourceFactory;
import org.apache.flume.source.NetcatSource;
import org.apache.flume.source.SequenceGeneratorSource;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestJsonFileConfigurationProvider {
private static final File testFile = new File(
TestJsonFileConfigurationProvider.class.getClassLoader()
.getResource("flume-conf.json").getFile());
private static final Logger logger = LoggerFactory
.getLogger(TestJsonFileConfigurationProvider.class);
private JsonFileConfigurationProvider provider;
@Before
public void setUp() {
ChannelFactory channelFactory = new DefaultChannelFactory();
SourceFactory sourceFactory = new DefaultSourceFactory();
SinkFactory sinkFactory = new DefaultSinkFactory();
channelFactory.register("memory", MemoryChannel.class);
sourceFactory.register("seq", SequenceGeneratorSource.class);
sourceFactory.register("netcat", NetcatSource.class);
sinkFactory.register("null", NullSink.class);
sinkFactory.register("logger", LoggerSink.class);
provider = new JsonFileConfigurationProvider();
provider.setChannelFactory(channelFactory);
provider.setSourceFactory(sourceFactory);
provider.setSinkFactory(sinkFactory);
}
@Test
public void testLifecycle() throws InterruptedException {
final AtomicBoolean sawEvent = new AtomicBoolean();
final CountDownLatch latch = new CountDownLatch(1);
provider.setFile(testFile);
NodeConfigurationAware delegate = new NodeConfigurationAware() {
@Override
public void onNodeConfigurationChanged(NodeConfiguration nodeConfiguration) {
sawEvent.set(true);
Map<String, Channel> channels = nodeConfiguration.getChannels();
Assert.assertNotNull("Channel ch1 exists", channels.get("ch1"));
Assert.assertNotNull("Channel ch2 exists", channels.get("ch2"));
Map<String, SourceRunner> sourceRunners = nodeConfiguration
.getSourceRunners();
Assert.assertNotNull("Source runner for source1 exists",
sourceRunners.get("source1"));
Assert.assertNotNull("Source runner for source2 exists",
sourceRunners.get("source2"));
latch.countDown();
}
};
provider.setConfigurationAware(delegate);
provider.start();
+
+ Thread.sleep(100L);
+
provider.stop();
latch.await(5, TimeUnit.SECONDS);
logger.debug("provider:{}", provider);
Assert.assertTrue("Saw a configuration event", sawEvent.get());
}
}
| true | false | null | null |
diff --git a/jason/asSemantics/ActionExec.java b/jason/asSemantics/ActionExec.java
index 86e5651..90d762e 100644
--- a/jason/asSemantics/ActionExec.java
+++ b/jason/asSemantics/ActionExec.java
@@ -1,99 +1,99 @@
//----------------------------------------------------------------------------
// Copyright (C) 2003 Rafael H. Bordini, Jomi F. Hubner, et al.
//
// 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
//
// To contact the authors:
// http://www.dur.ac.uk/r.bordini
// http://www.inf.furb.br/~jomi
//
//----------------------------------------------------------------------------
package jason.asSemantics;
import jason.asSyntax.Literal;
import jason.asSyntax.Pred;
import jason.asSyntax.Structure;
import java.io.Serializable;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class ActionExec implements Serializable {
private static final long serialVersionUID = 1L;
private Literal action;
private Intention intention;
private boolean result;
public ActionExec(Literal ac, Intention i) {
action = ac;
intention = i;
result = false;
}
@Override
public boolean equals(Object ao) {
if (ao == null) return false;
if (!(ao instanceof ActionExec)) return false;
ActionExec a = (ActionExec)ao;
return action.equals(a.action);
}
@Override
public int hashCode() {
return action.hashCode();
}
public Structure getActionTerm() {
- if (action.isAtom())
- return new Structure(action.getFunctor());
- else
+ if (action instanceof Structure)
return (Structure)action;
+ else
+ return new Structure(action);
}
public Intention getIntention() {
return intention;
}
public boolean getResult() {
return result;
}
public void setResult(boolean ok) {
result = ok;
}
public String toString() {
return "<"+action+","+intention+","+result+">";
}
protected ActionExec clone() {
ActionExec ae = new ActionExec((Pred)action.clone(), intention.clone());
ae.result = this.result;
return ae;
}
/** get as XML */
public Element getAsDOM(Document document) {
Element eact = (Element) document.createElement("action");
eact.setAttribute("term", action.toString());
eact.setAttribute("result", result+"");
eact.setAttribute("intention", intention.getId()+"");
return eact;
}
}
diff --git a/jason/bb/DefaultBeliefBase.java b/jason/bb/DefaultBeliefBase.java
index 68d9b39..12f2c6f 100644
--- a/jason/bb/DefaultBeliefBase.java
+++ b/jason/bb/DefaultBeliefBase.java
@@ -1,333 +1,333 @@
//----------------------------------------------------------------------------
// Copyright (C) 2003 Rafael H. Bordini, Jomi F. Hubner, et al.
//
// 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
//
// To contact the authors:
// http://www.dur.ac.uk/r.bordini
// http://www.inf.furb.br/~jomi
//
//----------------------------------------------------------------------------
package jason.bb;
import jason.asSemantics.Agent;
import jason.asSemantics.Unifier;
import jason.asSyntax.Literal;
import jason.asSyntax.PredicateIndicator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Default implementation of Jason BB.
*/
public class DefaultBeliefBase implements BeliefBase {
private static Logger logger = Logger.getLogger(DefaultBeliefBase.class.getSimpleName());
/**
* belsMap is a table where the key is the bel.getFunctorArity and the value
* is a list of literals with the same functorArity.
*/
private Map<PredicateIndicator, BelEntry> belsMap = new HashMap<PredicateIndicator, BelEntry>();
private int size = 0;
/** set of beliefs with percept annot, used to improve performance of buf */
- private Set<Literal> percepts = new HashSet<Literal>();
+ protected Set<Literal> percepts = new HashSet<Literal>();
public void init(Agent ag, String[] args) {
if (ag != null) {
logger = Logger.getLogger(ag.getTS().getUserAgArch().getAgName() + "-"+DefaultBeliefBase.class.getSimpleName());
}
}
public void stop() {
}
public int size() {
return size;
}
@SuppressWarnings("unchecked")
public Iterator<Literal> getPercepts() {
final Iterator<Literal> i = percepts.iterator();
return new Iterator<Literal>() {
Literal current = null;
public boolean hasNext() {
return i.hasNext();
}
public Literal next() {
current = i.next();
return current;
}
public void remove() {
if (current == null) {
logger.warning("Trying to remove a perception, but the the next() from the iterator is not called before!");
}
// remove from percepts
i.remove();
// remove the percept annot
current.delAnnot(BeliefBase.TPercept);
// and also remove from the BB
removeFromEntry(current);
}
};
//return ((Set<Literal>)percepts.clone()).iterator();
}
Set<Literal> getPerceptsSet() {
return percepts;
}
public boolean add(Literal l) {
return add(l, false);
}
public boolean add(int index, Literal l) {
return add(l, index != 0);
}
protected boolean add(Literal l, boolean addInEnd) {
if (!l.canBeAddedInBB()) {
logger.log(Level.SEVERE, "Error: '"+l+"' can not be added in the belief base.");
return false;
}
Literal bl = contains(l);
if (bl != null && !bl.isRule()) {
// add only annots
if (bl.importAnnots(l)) {
// check if it needs to be added in the percepts list
if (l.hasAnnot(TPercept)) {
percepts.add(bl);
}
return true;
}
} else {
BelEntry entry = belsMap.get(l.getPredicateIndicator());
if (entry == null) {
entry = new BelEntry();
belsMap.put(l.getPredicateIndicator(), entry);
}
entry.add(l, addInEnd);
// add it in the percepts list
if (l.hasAnnot(TPercept)) {
percepts.add(l);
}
size++;
return true;
}
return false;
}
public boolean remove(Literal l) {
Literal bl = contains(l);
if (bl != null) {
if (l.hasSubsetAnnot(bl)) { // e.g. removing b[a] or b[a,d] from BB b[a,b,c]
// second case fails
if (l.hasAnnot(TPercept)) {
percepts.remove(bl);
}
boolean result = bl.delAnnots(l.getAnnots()); // note that l annots can be empty, in this case, nothing is deleted!
return removeFromEntry(bl) || result;
}
} else {
if (logger.isLoggable(Level.FINE)) logger.fine("Does not contain " + l + " in " + belsMap);
}
return false;
}
private boolean removeFromEntry(Literal l) {
if (l.hasSource()) {
return false;
} else {
PredicateIndicator key = l.getPredicateIndicator();
BelEntry entry = belsMap.get(key);
entry.remove(l);
if (entry.isEmpty()) {
belsMap.remove(key);
}
size--;
return true;
}
}
public Iterator<Literal> iterator() {
final Iterator<BelEntry> ibe = belsMap.values().iterator();
if (ibe.hasNext()) {
return new Iterator<Literal>() {
Iterator<Literal> il = ibe.next().list.iterator();
public boolean hasNext() {
return il.hasNext();
}
public Literal next() {
Literal l = il.next();
if (!il.hasNext() && ibe.hasNext()) {
il = ibe.next().list.iterator();
}
return l;
}
public void remove() {
logger.warning("remove is not implemented for BB.iterator().");
}
};
} else {
return new ArrayList<Literal>(0).iterator();
}
}
/** @deprecated use iterator() instead of getAll */
public Iterator<Literal> getAll() {
return iterator();
}
public boolean abolish(PredicateIndicator pi) {
return belsMap.remove(pi) != null;
}
public Literal contains(Literal l) {
BelEntry entry = belsMap.get(l.getPredicateIndicator());
if (entry == null) {
return null;
} else {
//logger.info("*"+l+":"+l.hashCode()+" = "+entry.contains(l)+" in "+this);//+" entry="+entry);
return entry.contains(l);
}
}
public Iterator<Literal> getCandidateBeliefs(Literal l, Unifier u) {
if (l.isVar()) {
// all bels are relevant
return iterator();
} else {
BelEntry entry = belsMap.get(l.getPredicateIndicator());
if (entry != null) {
return Collections.unmodifiableList(entry.list).iterator();
} else {
return null;
}
}
}
/** @deprecated use getCandidateBeliefs(l,null) instead */
public Iterator<Literal> getRelevant(Literal l) {
return getCandidateBeliefs(l, null);
}
public String toString() {
return belsMap.toString();
}
public Object clone() {
DefaultBeliefBase bb = new DefaultBeliefBase();
for (Literal b: this) {
bb.add(1, b.copy());
}
return bb;
}
public Element getAsDOM(Document document) {
Element ebels = (Element) document.createElement("beliefs");
for (Literal l: this) {
ebels.appendChild(l.getAsDOM(document));
}
return ebels;
}
/** each predicate indicator has one BelEntry assigned to it */
final class BelEntry {
final private List<Literal> list = new LinkedList<Literal>(); // maintains the order of the bels
final private Map<LiteralWrapper,Literal> map = new HashMap<LiteralWrapper,Literal>(); // to fastly find contents, from literal do list index
@SuppressWarnings("unchecked")
public void add(Literal l, boolean addInEnd) {
//try {
// minimise the allocation space of terms
// Moved to the parser.
// if (!l.isAtom()) ((ArrayList) l.getTerms()).trimToSize();
//} catch (Exception e) {}
map.put(new LiteralWrapper(l), l);
if (addInEnd) {
list.add(l);
} else {
list.add(0,l);
}
}
public void remove(Literal l) {
Literal linmap = map.remove(new LiteralWrapper(l));
if (linmap != null) {
list.remove(linmap);
}
}
public boolean isEmpty() {
return list.isEmpty();
}
public Literal contains(Literal l) {
return map.get(new LiteralWrapper(l));
}
protected Object clone() {
BelEntry be = new BelEntry();
for (Literal l: list) {
be.add(l.copy(), false);
}
return be;
}
public String toString() {
StringBuilder s = new StringBuilder();
for (Literal l: list) {
s.append(l+":"+l.hashCode()+",");
}
return s.toString();
}
/** a literal that uses equalsAsTerm for equals */
final class LiteralWrapper {
final private Literal l;
public LiteralWrapper(Literal l) { this.l = l; }
public int hashCode() { return l.hashCode(); }
public boolean equals(Object o) { return o instanceof LiteralWrapper && l.equalsAsStructure(((LiteralWrapper)o).l); }
public String toString() { return l.toString(); }
}
}
}
| false | false | null | null |
diff --git a/src/main/java/com/marc/lastweek/business/entities/classifiedad/repository/ClassifiedAdRepository.java b/src/main/java/com/marc/lastweek/business/entities/classifiedad/repository/ClassifiedAdRepository.java
index 22672cb..782283f 100644
--- a/src/main/java/com/marc/lastweek/business/entities/classifiedad/repository/ClassifiedAdRepository.java
+++ b/src/main/java/com/marc/lastweek/business/entities/classifiedad/repository/ClassifiedAdRepository.java
@@ -1,37 +1,40 @@
/*
* ClasifiedAdRepository.java
* Copyright (c) 2009, Monte Alto Research Center, All Rights Reserved.
*
* This software is the confidential and proprietary information of
* Monte Alto Research Center ("Confidential Information"). You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with Monte Alto Research Center
*/
package com.marc.lastweek.business.entities.classifiedad.repository;
import java.util.ArrayList;
import java.util.List;
import loc.marc.commons.business.entities.general.GeneralRepository;
+import org.springframework.stereotype.Repository;
+
import com.marc.lastweek.business.entities.classifiedad.ClassifiedAd;
import com.marc.lastweek.business.views.aaa.FilterParameters;
+@Repository
public class ClassifiedAdRepository extends GeneralRepository {
public List<ClassifiedAd> filterAdvertisements(FilterParameters parameters, int start, int count) {
List<ClassifiedAd> results = new ArrayList<ClassifiedAd>();
// TODO: add criteria query
return results;
}
public Integer countFilterAdvertisements(FilterParameters parameters) {
// TODO: add criteria query
return 0;
}
}
| false | false | null | null |
diff --git a/src/me/neatmonster/spacebukkit/PanelListener.java b/src/me/neatmonster/spacebukkit/PanelListener.java
index e8bb389..03fcf2e 100644
--- a/src/me/neatmonster/spacebukkit/PanelListener.java
+++ b/src/me/neatmonster/spacebukkit/PanelListener.java
@@ -1,133 +1,137 @@
/*
* This file is part of SpaceBukkit (http://spacebukkit.xereo.net/).
*
* SpaceBukkit is free software: you can redistribute it and/or modify it under the terms of the
* Attribution-NonCommercial-ShareAlike Unported (CC BY-NC-SA) license as published by the Creative Common organization,
* either version 3.0 of the license, or (at your option) any later version.
*
* SpaceBukkit 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 Attribution-NonCommercial-ShareAlike
* Unported (CC BY-NC-SA) license for more details.
*
* You should have received a copy of the Attribution-NonCommercial-ShareAlike Unported (CC BY-NC-SA) license along with
* this program. If not, see <http://creativecommons.org/licenses/by-nc-sa/3.0/>.
*/
package me.neatmonster.spacebukkit;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLDecoder;
import java.util.List;
import me.neatmonster.spacebukkit.events.RequestEvent;
import me.neatmonster.spacebukkit.utilities.Utilities;
import me.neatmonster.spacemodule.api.InvalidArgumentsException;
import me.neatmonster.spacemodule.api.UnhandledActionException;
import org.bukkit.Bukkit;
import org.json.simple.JSONValue;
public class PanelListener extends Thread {
+
+ private boolean running = true;
@SuppressWarnings("unchecked")
private static Object interpret(final String string) throws InvalidArgumentsException, UnhandledActionException {
final int indexOfMethod = string.indexOf("?method=");
final int indexOfArguments = string.indexOf("&args=");
final int indexOfKey = string.indexOf("&key=");
final String method = string.substring(indexOfMethod + 8, indexOfArguments);
final String argumentsString = string.substring(indexOfArguments + 6, indexOfKey);
final List<Object> arguments = (List<Object>) JSONValue.parse(argumentsString);
try {
if (SpaceBukkit.getInstance().actionsManager.contains(method))
return SpaceBukkit.getInstance().actionsManager.execute(method, arguments.toArray());
else {
final RequestEvent event = new RequestEvent(method, arguments.toArray());
Bukkit.getPluginManager().callEvent(event);
return JSONValue.toJSONString(event.getResult());
}
} catch (final InvalidArgumentsException e) {
e.printStackTrace();
} catch (final UnhandledActionException e) {
e.printStackTrace();
}
return null;
}
private final int mode;
private ServerSocket serverSocket = null;
private Socket socket;
public PanelListener() {
mode = 0;
start();
}
public PanelListener(final Socket socket) {
mode = 1;
this.socket = socket;
start();
}
public int getMode() {
return mode;
}
@Override
public void run() {
if (mode == 0) {
try {
serverSocket = new ServerSocket(SpaceBukkit.getInstance().port);
} catch(IOException e) {
e.printStackTrace();
return;
}
- while (!serverSocket.isClosed()) {
+ while (running && !serverSocket.isClosed()) {
try {
final Socket clientSocket = serverSocket.accept();
new PanelListener(clientSocket);
} catch (final Exception e) {
if (!e.getMessage().contains("socket closed"))
e.printStackTrace();
}
}
} else {
try {
final BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String string = input.readLine();
string = URLDecoder.decode(string, "UTF-8");
string = string.substring(5, string.length() - 9);
final PrintWriter output = new PrintWriter(socket.getOutputStream());
if (string.startsWith("call") && string.contains("?method=") && string.contains("&args=")) {
final String method = string.substring(12, string.indexOf("&args="));
if (string.contains("&key=" + Utilities.crypt(method + SpaceBukkit.getInstance().salt))) {
final Object result = interpret(string);
if (result != null)
output.println(Utilities.addHeader(JSONValue.toJSONString(result)));
else
output.println(Utilities.addHeader(null));
} else
output.println(Utilities.addHeader("Incorrect Salt supplied. Access denied!"));
} else if (string.startsWith("ping"))
output.println(Utilities.addHeader("Pong!"));
else
output.println(Utilities.addHeader(null));
output.flush();
input.close();
output.close();
} catch (final Exception e) {
e.printStackTrace();
}
}
}
public void stopServer() throws IOException {
- if (serverSocket != null)
+ running = false;
+ if (serverSocket != null) {
serverSocket.close();
+ }
}
}
| false | false | null | null |
diff --git a/frontend/client/src/autotest/afe/JobDetailView.java b/frontend/client/src/autotest/afe/JobDetailView.java
index d730abb0..7dad0130 100644
--- a/frontend/client/src/autotest/afe/JobDetailView.java
+++ b/frontend/client/src/autotest/afe/JobDetailView.java
@@ -1,328 +1,322 @@
package autotest.afe;
import autotest.common.JsonRpcCallback;
import autotest.common.StaticDataRepository;
import autotest.common.Utils;
import autotest.common.table.DataTable;
import autotest.common.table.DynamicTable;
import autotest.common.table.ListFilter;
import autotest.common.table.SearchFilter;
import autotest.common.table.SimpleFilter;
import autotest.common.table.TableDecorator;
import autotest.common.table.DataTable.TableWidgetFactory;
import autotest.common.table.DynamicTable.DynamicTableListener;
import autotest.common.ui.DetailView;
import autotest.common.ui.NotifyManager;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
-import com.google.gwt.http.client.URL;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.Widget;
import java.util.Set;
public class JobDetailView extends DetailView {
private static final String[][] JOB_HOSTS_COLUMNS = {
{"hostname", "Host"}, {"status", "Status"},
{"host_status", "Host Status"}, {"host_locked", "Host Locked"},
{DataTable.CLICKABLE_WIDGET_COLUMN, ""}
};
public static final String NO_URL = "about:blank";
public static final int NO_JOB_ID = -1;
public static final int HOSTS_PER_PAGE = 30;
public interface JobDetailListener {
public void onHostSelected(String hostname);
public void onCloneJob(JSONValue result);
}
protected int jobId = NO_JOB_ID;
private JobStatusDataSource jobStatusDataSource = new JobStatusDataSource();
protected DynamicTable hostsTable = new DynamicTable(JOB_HOSTS_COLUMNS, jobStatusDataSource);
protected TableDecorator tableDecorator = new TableDecorator(hostsTable);
protected SimpleFilter jobFilter = new SimpleFilter();
protected Button abortButton = new Button("Abort job");
protected Button cloneButton = new Button("Clone job");
protected HTML tkoResultsHtml = new HTML();
protected ScrollPanel tkoResultsScroller = new ScrollPanel(tkoResultsHtml);
protected JobDetailListener listener;
public JobDetailView(JobDetailListener listener) {
this.listener = listener;
}
@Override
protected void fetchData() {
pointToResults(NO_URL, NO_URL);
JSONObject params = new JSONObject();
params.put("id", new JSONNumber(jobId));
rpcProxy.rpcCall("get_jobs_summary", params, new JsonRpcCallback() {
@Override
public void onSuccess(JSONValue result) {
JSONObject jobObject;
try {
jobObject = Utils.getSingleValueFromArray(result.isArray()).isObject();
}
catch (IllegalArgumentException exc) {
NotifyManager.getInstance().showError("No such job found");
resetPage();
return;
}
String name = jobObject.get("name").isString().stringValue();
String owner = jobObject.get("owner").isString().stringValue();
showText(name, "view_label");
showText(owner, "view_owner");
showField(jobObject, "priority", "view_priority");
showField(jobObject, "created_on", "view_created");
showField(jobObject, "control_type", "view_control_type");
showField(jobObject, "control_file", "view_control_file");
String synchType = jobObject.get("synch_type").isString().stringValue();
showText(synchType.toLowerCase(), "view_synch_type");
JSONObject counts = jobObject.get("status_counts").isObject();
String countString = AfeUtils.formatStatusCounts(counts, ", ");
showText(countString, "view_status");
abortButton.setVisible(!allFinishedCounts(counts));
String jobLogsId = jobId + "-" + owner;
pointToResults(getResultsURL(jobId), getLogsURL(jobLogsId));
String jobTitle = "Job: " + name + " (" + jobLogsId + ")";
displayObjectData(jobTitle);
jobFilter.setParameter("job", new JSONNumber(jobId));
hostsTable.refresh();
}
@Override
public void onError(JSONObject errorObject) {
super.onError(errorObject);
resetPage();
}
});
}
protected boolean allFinishedCounts(JSONObject statusCounts) {
Set<String> keys = statusCounts.keySet();
for (String key : keys) {
if (!(key.equals("Completed") ||
key.equals("Failed") ||
key.equals("Aborting") ||
key.equals("Abort") ||
key.equals("Aborted") ||
key.equals("Stopped")))
return false;
}
return true;
}
@Override
public void initialize() {
super.initialize();
idInput.setVisibleLength(5);
hostsTable.setRowsPerPage(HOSTS_PER_PAGE);
hostsTable.setClickable(true);
hostsTable.addListener(new DynamicTableListener() {
public void onRowClicked(int rowIndex, JSONObject row) {
JSONObject host = row.get("host").isObject();
String hostname = host.get("hostname").isString().stringValue();
listener.onHostSelected(hostname);
}
public void onTableRefreshed() {}
});
hostsTable.setWidgetFactory(new TableWidgetFactory() {
public Widget createWidget(int row, int cell, JSONObject hostQueueEntry) {
JSONValue jobValue = hostQueueEntry.get("job");
if (jobValue == null) {
return new HTML("");
}
String path = "/debug";
if (jobStatusDataSource.getNumResults() > 1) {
path = "/" + hostQueueEntry.get("hostname").isString().stringValue() + "/debug";
}
String html = "<a target=\"_blank\" href=\"";
JSONObject jobObject = jobValue.isObject();
- html += getLogsURL(jobId + "-" + jobObject.get("owner").isString().stringValue(),
- path);
+ html += Utils.getLogsURL(
+ jobId + "-" + jobObject.get("owner").isString().stringValue() + path);
html += "\">View Debug Logs</a>";
return new HTML(html);
}
});
tableDecorator.addPaginators();
addTableFilters();
RootPanel.get("job_hosts_table").add(tableDecorator);
abortButton.addClickListener(new ClickListener() {
public void onClick(Widget sender) {
abortJob();
}
});
RootPanel.get("view_abort").add(abortButton);
cloneButton.addClickListener(new ClickListener() {
public void onClick(Widget sender) {
cloneJob();
}
});
RootPanel.get("view_clone").add(cloneButton);
tkoResultsScroller.setStyleName("results-frame");
RootPanel.get("tko_results").add(tkoResultsScroller);
}
protected void addTableFilters() {
hostsTable.addFilter(jobFilter);
SearchFilter hostnameFilter = new SearchFilter("host__hostname");
hostnameFilter.setExactMatch(false);
ListFilter statusFilter = new ListFilter("status");
StaticDataRepository staticData = StaticDataRepository.getRepository();
JSONArray statuses = staticData.getData("job_statuses").isArray();
statusFilter.setChoices(Utils.JSONtoStrings(statuses));
tableDecorator.addFilter("Hostname", hostnameFilter);
tableDecorator.addFilter("Status", statusFilter);
}
protected void abortJob() {
JSONObject params = new JSONObject();
params.put("id", new JSONNumber(jobId));
rpcProxy.rpcCall("abort_job", params, new JsonRpcCallback() {
@Override
public void onSuccess(JSONValue result) {
refresh();
}
});
}
protected void cloneJob() {
JSONObject params = new JSONObject();
params.put("id", new JSONNumber(jobId));
rpcProxy.rpcCall("get_info_for_clone", params, new JsonRpcCallback() {
@Override
public void onSuccess(JSONValue result) {
listener.onCloneJob(result);
}
});
}
protected String getResultsURL(int jobId) {
return "/tko/compose_query.cgi?" +
"columns=test&rows=hostname&condition=tag%7E%27" +
Integer.toString(jobId) + "-%25%27&title=Report";
}
/**
* Get the path for a job's raw result files.
* @param jobLogsId id-owner, e.g. "172-showard"
*/
protected String getLogsURL(String jobLogsId) {
- return getLogsURL(jobLogsId, "");
- }
-
- protected String getLogsURL(String jobLogsId, String path) {
- String val = URL.encode("/results/" + jobLogsId + path);
- return "/tko/retrieve_logs.cgi?job=" + val;
+ return Utils.getLogsURL(jobLogsId);
}
protected void pointToResults(String resultsUrl, String logsUrl) {
DOM.setElementProperty(DOM.getElementById("results_link"),
"href", resultsUrl);
DOM.setElementProperty(DOM.getElementById("raw_results_link"),
"href", logsUrl);
if (resultsUrl.equals(NO_URL)) {
tkoResultsHtml.setHTML("");
return;
}
RequestBuilder requestBuilder =
new RequestBuilder(RequestBuilder.GET, resultsUrl + "&brief=1");
try {
requestBuilder.sendRequest("", new RequestCallback() {
public void onError(Request request, Throwable exception) {
tkoResultsHtml.setHTML("");
NotifyManager.getInstance().showError(
exception.getLocalizedMessage());
}
public void onResponseReceived(Request request,
Response response) {
tkoResultsHtml.setHTML(response.getText());
}
});
} catch (RequestException ex) {
NotifyManager.getInstance().showError(ex.getLocalizedMessage());
}
}
@Override
protected String getNoObjectText() {
return "No job selected";
}
@Override
protected String getFetchControlsElementId() {
return "job_id_fetch_controls";
}
@Override
protected String getDataElementId() {
return "view_data";
}
@Override
protected String getTitleElementId() {
return "view_title";
}
@Override
protected String getObjectId() {
if (jobId == NO_JOB_ID)
return NO_OBJECT;
return Integer.toString(jobId);
}
@Override
public String getElementId() {
return "view_job";
}
@Override
protected void setObjectId(String id) {
int newJobId;
try {
newJobId = Integer.parseInt(id);
}
catch (NumberFormatException exc) {
throw new IllegalArgumentException();
}
this.jobId = newJobId;
}
public void fetchJob(int jobId) {
fetchById(Integer.toString(jobId));
}
}
diff --git a/frontend/client/src/autotest/common/JsonRpcProxy.java b/frontend/client/src/autotest/common/JsonRpcProxy.java
index c0fa453c..060e5849 100644
--- a/frontend/client/src/autotest/common/JsonRpcProxy.java
+++ b/frontend/client/src/autotest/common/JsonRpcProxy.java
@@ -1,142 +1,144 @@
package autotest.common;
import autotest.common.ui.NotifyManager;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONException;
import com.google.gwt.json.client.JSONNull;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* A singleton class to facilitate RPC calls to the server.
*/
public class JsonRpcProxy {
public static final String AFE_URL = "/afe/server/rpc/";
public static final String TKO_URL = "/new_tko/server/rpc/";
private static String defaultUrl;
private static final Map<String,JsonRpcProxy> instanceMap = new HashMap<String,JsonRpcProxy>();
protected NotifyManager notify = NotifyManager.getInstance();
protected RequestBuilder requestBuilder;
public static void setDefaultUrl(String url) {
defaultUrl = url;
}
public static JsonRpcProxy getProxy(String url) {
if (!instanceMap.containsKey(url)) {
instanceMap.put(url, new JsonRpcProxy(url));
}
return instanceMap.get(url);
}
public static JsonRpcProxy getProxy() {
assert defaultUrl != null;
return getProxy(defaultUrl);
}
private JsonRpcProxy(String url) {
requestBuilder = new RequestBuilder(RequestBuilder.POST, url);
}
protected JSONArray processParams(JSONObject params) {
JSONArray result = new JSONArray();
JSONObject newParams = new JSONObject();
if (params != null) {
Set<String> keys = params.keySet();
for (String key : keys) {
if (params.get(key) != JSONNull.getInstance())
newParams.put(key, params.get(key));
}
}
result.set(0, newParams);
return result;
}
/**
* Make an RPC call.
* @param method name of the method to call
* @param params dictionary of parameters to pass
* @param callback callback to be notified of RPC call results
*/
public void rpcCall(String method, JSONObject params,
final JsonRpcCallback callback) {
JSONObject request = new JSONObject();
request.put("method", new JSONString(method));
request.put("params", processParams(params));
request.put("id", new JSONNumber(0));
notify.setLoading(true);
try {
requestBuilder.sendRequest(request.toString(),
new RpcHandler(callback));
}
catch (RequestException e) {
notify.showError("Unable to connect to server");
}
}
class RpcHandler implements RequestCallback {
private JsonRpcCallback callback;
public RpcHandler(JsonRpcCallback callback) {
this.callback = callback;
}
public void onError(Request request, Throwable exception) {
notify.showError("Unable to make RPC call", exception.toString());
}
public void onResponseReceived(Request request, Response response) {
notify.setLoading(false);
String responseText = response.getText();
int statusCode = response.getStatusCode();
if (statusCode != 200) {
notify.showError("Received error " +
Integer.toString(statusCode) + " " +
response.getStatusText(),
+ response.getHeadersAsString() + "\n\n" +
responseText);
+ return;
}
JSONValue responseValue = null;
try {
responseValue = JSONParser.parse(responseText);
}
catch (JSONException exc) {
notify.showError(exc.toString(), responseText);
return;
}
JSONObject responseObject = responseValue.isObject();
JSONValue error = responseObject.get("error");
if (error == null) {
notify.showError("Bad JSON response", responseText);
return;
}
else if (error.isObject() != null) {
callback.onError(error.isObject());
return;
}
JSONValue result = responseObject.get("result");
callback.onSuccess(result);
}
}
}
diff --git a/frontend/client/src/autotest/common/Utils.java b/frontend/client/src/autotest/common/Utils.java
index 269f0f78..db1740d0 100644
--- a/frontend/client/src/autotest/common/Utils.java
+++ b/frontend/client/src/autotest/common/Utils.java
@@ -1,143 +1,151 @@
package autotest.common;
import com.google.gwt.http.client.URL;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Utils {
private static final String[][] escapeMappings = {
{"&", "&"},
{">", ">"},
{"<", "<"},
{"\"", """},
{"'", "'"},
};
/**
* Converts a collection of Java <code>String</code>s into a <code>JSONArray
* </code> of <code>JSONString</code>s.
*/
public static JSONArray stringsToJSON(Collection<String> strings) {
JSONArray result = new JSONArray();
for(String s : strings) {
result.set(result.size(), new JSONString(s));
}
return result;
}
/**
* Converts a <code>JSONArray</code> of <code>JSONStrings</code> to an
* array of Java <code>Strings</code>.
*/
public static String[] JSONtoStrings(JSONArray strings) {
String[] result = new String[strings.size()];
for (int i = 0; i < strings.size(); i++) {
result[i] = strings.get(i).isString().stringValue();
}
return result;
}
/**
* Converts a <code>JSONArray</code> of <code>JSONObjects</code> to an
* array of Java <code>Strings</code> by grabbing the specified field from
* each object.
*/
public static String[] JSONObjectsToStrings(JSONArray objects, String field) {
String[] result = new String[objects.size()];
for (int i = 0; i < objects.size(); i++) {
JSONValue fieldValue = objects.get(i).isObject().get(field);
result[i] = fieldValue.isString().stringValue();
}
return result;
}
/**
* Get a value out of an array of size 1.
* @return array[0]
* @throws IllegalArgumentException if the array is not of size 1
*/
public static JSONValue getSingleValueFromArray(JSONArray array) {
if(array.size() != 1) {
throw new IllegalArgumentException("Array is not of size 1");
}
return array.get(0);
}
public static JSONObject copyJSONObject(JSONObject source) {
JSONObject dest = new JSONObject();
for(String key : source.keySet()) {
dest.put(key, source.get(key));
}
return dest;
}
public static String escape(String text) {
for (String[] mapping : escapeMappings) {
text = text.replaceAll(mapping[0], mapping[1]);
}
return text;
}
public static String unescape(String text) {
// must iterate in reverse order
for (int i = escapeMappings.length - 1; i >= 0; i--) {
text = text.replaceAll(escapeMappings[i][1], escapeMappings[i][0]);
}
return text;
}
public static <T> List<T> wrapObjectWithList(T object) {
List<T> list = new ArrayList<T>();
list.add(object);
return list;
}
public static String joinStrings(String joiner, List<String> strings) {
if (strings.size() == 0) {
return "";
}
StringBuilder result = new StringBuilder(strings.get(0));
for (int i = 1; i < strings.size(); i++) {
result.append(joiner);
result.append(strings.get(i));
}
return result.toString();
}
public static Map<String,String> decodeUrlArguments(String urlArguments) {
Map<String, String> arguments = new HashMap<String, String>();
String[] components = urlArguments.split("&");
for (String component : components) {
String[] parts = component.split("=");
if (parts.length > 2) {
throw new IllegalArgumentException();
}
String key = URL.decodeComponent(parts[0]);
String value = "";
if (parts.length == 2) {
value = URL.decodeComponent(parts[1]);
}
arguments.put(key, value);
}
return arguments;
}
public static String encodeUrlArguments(Map<String, String> arguments) {
List<String> components = new ArrayList<String>();
for (Map.Entry<String, String> entry : arguments.entrySet()) {
String key = URL.encodeComponent(entry.getKey());
String value = URL.encodeComponent(entry.getValue());
components.add(key + "=" + value);
}
return joinStrings("&", components);
}
+
+ /**
+ * @param path should be of the form "123-showard/status.log" or just "123-showard"
+ */
+ public static String getLogsURL(String path) {
+ String val = URL.encode("/results/" + path);
+ return "/tko/retrieve_logs.cgi?job=" + val;
+ }
}
| false | false | null | null |
diff --git a/proxy/src/main/java/org/fedoraproject/candlepin/servlet/filter/auth/BasicAuthViaUserServiceFilter.java b/proxy/src/main/java/org/fedoraproject/candlepin/servlet/filter/auth/BasicAuthViaUserServiceFilter.java
index c9ce14b2f..c6961f1a7 100644
--- a/proxy/src/main/java/org/fedoraproject/candlepin/servlet/filter/auth/BasicAuthViaUserServiceFilter.java
+++ b/proxy/src/main/java/org/fedoraproject/candlepin/servlet/filter/auth/BasicAuthViaUserServiceFilter.java
@@ -1,118 +1,120 @@
/**
* Copyright (c) 2009 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package org.fedoraproject.candlepin.servlet.filter.auth;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.fedoraproject.candlepin.config.Config;
import org.fedoraproject.candlepin.resource.ForbiddenException;
import org.fedoraproject.candlepin.service.UserServiceAdapter;
import com.google.inject.Inject;
/**
* BasicAuthViaUserServiceFilter
*/
public class BasicAuthViaUserServiceFilter implements Filter {
private Logger log = Logger.getLogger(BasicAuthViaDbFilter.class);
private Config config = null;
private UserServiceAdapter userServiceAdapter;
@Inject
public BasicAuthViaUserServiceFilter(Config config, UserServiceAdapter userServiceAdapter) {
this.config = config;
this.userServiceAdapter = userServiceAdapter;
}
public BasicAuthViaUserServiceFilter() {
config = new Config();
}
public void init(FilterConfig filterConfig) throws ServletException {
//this.filterConfig = filterConfig;
}
public void destroy() {
//this.filterConfig = null;
}
// config has to be overridable for testing
public void setConfig(Config configuration) {
this.config = configuration;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
log.debug("in basic auth filter");
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
if (httpRequest.getMethod().equals("POST")) {
processPost(request, response, chain, httpRequest, httpResponse);
}
else {
// Anything that is not a POST is passed through
chain.doFilter(request, response);
}
log.debug("leaving basic auth filter");
}
private void processPost(ServletRequest request, ServletResponse response,
FilterChain chain, HttpServletRequest httpRequest,
HttpServletResponse httpResponse) {
String auth = httpRequest.getHeader("Authorization");
if (auth != null && auth.toUpperCase().startsWith("BASIC ")) {
String userpassEncoded = auth.substring(6);
String[] userpass = new String(Base64.decodeBase64(userpassEncoded)).split(":");
try {
- if(doAuth(userpass[0], userpass[1])){
+ if (doAuth(userpass[0], userpass[1])) {
request.setAttribute("username", userpass[0]);
chain.doFilter(request, response);
- }else{
+ }
+ else {
httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
}
- }catch (Exception ex) {
+ }
+ catch (Exception ex) {
log.error(ex.getMessage());
httpResponse.setStatus(HttpServletResponse.SC_BAD_GATEWAY);
}
}
else {
// Anything that is a POST that is not using BASIC auth, then it's
// forbidden
httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
}
}
private boolean doAuth(String username, String password) throws ForbiddenException {
return userServiceAdapter.validateUser(username, password);
}
}
| false | true | private void processPost(ServletRequest request, ServletResponse response,
FilterChain chain, HttpServletRequest httpRequest,
HttpServletResponse httpResponse) {
String auth = httpRequest.getHeader("Authorization");
if (auth != null && auth.toUpperCase().startsWith("BASIC ")) {
String userpassEncoded = auth.substring(6);
String[] userpass = new String(Base64.decodeBase64(userpassEncoded)).split(":");
try {
if(doAuth(userpass[0], userpass[1])){
request.setAttribute("username", userpass[0]);
chain.doFilter(request, response);
}else{
httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
}
}catch (Exception ex) {
log.error(ex.getMessage());
httpResponse.setStatus(HttpServletResponse.SC_BAD_GATEWAY);
}
}
else {
// Anything that is a POST that is not using BASIC auth, then it's
// forbidden
httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
}
}
| private void processPost(ServletRequest request, ServletResponse response,
FilterChain chain, HttpServletRequest httpRequest,
HttpServletResponse httpResponse) {
String auth = httpRequest.getHeader("Authorization");
if (auth != null && auth.toUpperCase().startsWith("BASIC ")) {
String userpassEncoded = auth.substring(6);
String[] userpass = new String(Base64.decodeBase64(userpassEncoded)).split(":");
try {
if (doAuth(userpass[0], userpass[1])) {
request.setAttribute("username", userpass[0]);
chain.doFilter(request, response);
}
else {
httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
}
}
catch (Exception ex) {
log.error(ex.getMessage());
httpResponse.setStatus(HttpServletResponse.SC_BAD_GATEWAY);
}
}
else {
// Anything that is a POST that is not using BASIC auth, then it's
// forbidden
httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
}
}
|
diff --git a/src/scheduler/Scheduler.java b/src/scheduler/Scheduler.java
index 4c9ead2..9835497 100644
--- a/src/scheduler/Scheduler.java
+++ b/src/scheduler/Scheduler.java
@@ -1,105 +1,108 @@
package scheduler;
import java.util.*;
import strategy.*;
/**
* main class
*
* @assumption
* 1. processes' ids are continuous, start from 0 to n.
*
* @author Yaxing Chen(N16929794, [email protected])
*
*/
public class Scheduler {
public static void main(String[] args) {
ArrayList<Process> proc = null;
Status[] procStatus = null; // record realtime procStatus, for improving efficiency.
// Status (enum)
//@see Status.java
String inputFile = "";
int strategy = -1;
int mode = 0;
+ args = new String[1];
+ args[0] = "inp2.txt";
+
try {
if(args == null || args.length == 0) {
throw new Exception();
}
inputFile = args[0];
if(args.length >= 2) {
strategy = Integer.parseInt(args[1]);
}
if(args.length == 3) {
mode = Integer.parseInt(args[2]);
}
if(strategy > 2 || (strategy < 0 && strategy != -1)) {
throw new Exception();
}
if(mode != 0 && mode != 1) {
throw new Exception();
}
} catch(Exception e) {
invalidParam();
}
//System.out.println(Tool.read(args[0]));
proc = Tool.fetch(Tool.read(inputFile));
procStatus = new Status[proc.size()];
for(int i = 0; i < procStatus.length; i ++) {
procStatus[i] = Status.NEW;
}
if(strategy >= 0) {
exec(strategy, proc, procStatus, false);
}
else if(strategy == -1) {
/**
* if perform multi-strategies once, need deep copy
*/
exec(0, proc, procStatus, true);
exec(1, proc, procStatus, true);
exec(2, proc, procStatus, true);
}
}
private static void invalidParam() {
System.out.println("usage: Scheduler.jar <input file path> [strategy] [mode]");
System.out.println(" strategy: ");
System.out.println(" -1[default]: all");
System.out.println(" 0: fcfs");
System.out.println(" 1: rr");
System.out.println(" 2: srjf");
System.out.println(" mode: (invalid for rr)");
System.out.println(" 1[default]: preemptive");
System.out.println(" 0: un-preemptive");
System.exit(0);
}
private static void exec(int strategy, ArrayList<Process> proc, Status[] procStatus, boolean needDeepCopy) {
String outputFile = "";
Strategy ctrl = null;
switch(strategy) {
case 0:
ctrl = new FCFS();
outputFile = "output_fcfs.txt";
break;
case 1:
ctrl = new RR();
outputFile = "output_rr.txt";
break;
case 2:
ctrl = new SRJF();
outputFile = "output_srjf.txt";
break;
default:
break;
}
ctrl.start(proc, procStatus, needDeepCopy);
Tool.writeFile(outputFile);
return;
}
}
\ No newline at end of file
diff --git a/src/strategy/Strategy.java b/src/strategy/Strategy.java
index c232d4e..937d9fc 100644
--- a/src/strategy/Strategy.java
+++ b/src/strategy/Strategy.java
@@ -1,231 +1,234 @@
package strategy;
import java.util.*;
import scheduler.*;
import scheduler.Process;
/**
* Super class of scheduler strategies
*
* @author Yaxing Chen
*
*/
abstract public class Strategy {
/**
* process list
*/
protected ArrayList<Process> proc = null;
/**
* tracking each process's status
* index is process id
* @see Status
*/
protected Status[] procStatus = null;
/**
* running register
* current running process id
* if -1 then no running process, CPU is idle
*/
protected int running = -1;
/**
* ready queue
* ids of ready processes
* sorted by certain order based on different strategies (lower to higher)
*
* FCFS: sorted by arrival time
* SJF: sorted by remaining time
* RR: sorted by process id
*/
protected ArrayList<Integer> readyQ = new ArrayList<Integer>();
/**
* blocked queue
* ids of blocked processes
* sorted by certain order based on different strategies
*/
protected ArrayList<Integer> blockedQ = new ArrayList<Integer>();
/**
* cpu cycle counter
*/
protected int cycle = 0;
/**
* idle cycle counter
*/
protected int idleCycle = 0;
protected boolean isPreemptive = true;
/**
* buffer for output from each cycle
*/
protected StringBuilder buf = new StringBuilder();
/**
* used when perform multiple strategies once on the same input
* need to deep copy so that origin info would not be altered
* @param originProc
* @param originProcStatus
*/
private void deepCopy(ArrayList<Process> originProc, Status[] originProcStatus) {
this.proc = new ArrayList<Process>();
this.procStatus = new Status[originProcStatus.length];
for(Process p : originProc) {
this.proc.add(p.clone());
}
for(int i = 0; i < originProcStatus.length; i ++) {
this.procStatus[i] = originProcStatus[i];
}
}
/**
* schedule control func
* @param proc process table
* @param procStatus process status table, for efficiently outputing
*/
public ArrayList<Process> start(ArrayList<Process> originProc, Status[] originProcStatus, boolean needDeepCopy) {
if(!needDeepCopy) {
this.proc = originProc;
this.procStatus = originProcStatus;
}
else {
deepCopy(originProc, originProcStatus);
}
for(; ; cycle ++) {
handleNew();
handleBlockedQ();
handleRunning();
if(endChk()) {
end();
break;
}
Tool.writeBuffer(cycle + buf.toString());
buf.setLength(0);
}
return proc;
}
/**
* check if there is new comming process
* if so, move to ready queue
*/
protected void handleNew() {
for(int i = 0; i < proc.size(); i ++) {
Process curProc = proc.get(i);
if(curProc.arrivalTime <= cycle && procStatus[curProc.id] == Status.NEW) {
procStatus[curProc.id] = Status.READY;
this.insertIntoQueue(curProc.id, readyQ);
curProc.startCycle = cycle;
}
}
}
/**
* handle blocked queue
*
* check blocked process, if finished i/o time, move to ready queue
*/
protected void handleBlockedQ() {
if(blockedQ == null || blockedQ.size() == 0) {
return;
}
boolean remove = false;
for(int i = 0; i < blockedQ.size(); i ++) {
if(proc.get(blockedQ.get(i)).ioTime-- <= 0) {
this.insertIntoQueue(blockedQ.get(i), readyQ);
this.procStatus[proc.get(blockedQ.get(i)).id] = Status.READY;
blockedQ.set(i, null);
remove = true;
}
}
if(!remove) {
return;
}
this.removeElesFromList(blockedQ);
}
/**
* check running process
*
* decide whether to switch running process
*
* different method for different strategies
*/
abstract protected void handleRunning();
/**
* based on different strategies, check & handle preemptive for each cycle
*/
abstract protected boolean chkPreemptive();
/**
* insert into a designated queue, while maintaining order by certain attribute,
* based on different strategies
* insertion sort
* FCFS: order by arrival time
* SJF: remaing cpu time
* RR: id
*/
abstract protected void insertIntoQueue(int procId, ArrayList<Integer> queue);
/**
* remove given ids from list
* @param ids
* @param list
*/
protected void removeElesFromList(ArrayList<Integer> list) {
for(int i = 0; i < list.size(); i ++) {
if(list.get(i) == null) {
list.remove(i);
i = 0;
}
}
}
/**
* after each cycle, check whether all processes are finished or not
* at the same time, print out all alive processes' status
* @return boolean true: end, false: continue
*/
protected boolean endChk() {
boolean end = true;
for(int i = 0; i < procStatus.length; i ++) {
Status s = procStatus[i];
if(s == null) {
end &= true;
}
else {
+ end &= false;
if(s == Status.NEW) {
continue;
}
buf.append(" " + i + ":" + s);
- end &= false;
}
}
+ if(buf.length() == 0) {
+ buf.append(" CPU IDLE");
+ }
return end;
}
/**
* record summary scheduler information
*/
protected void end() {
Tool.writeBuffer("");
Tool.writeBuffer("Finishing time: " + --cycle);
Double util = (1 - new Double((idleCycle - 1)) / new Double(cycle + 1));
java.text.DecimalFormat format = new java.text.DecimalFormat("#0.00");
Tool.writeBuffer("CPU utilization: " + format.format(util));
for(int i = 0; i < proc.size(); i ++) {
int turnaround = proc.get(i).finishCycle - proc.get(i).arrivalTime + 1;
Tool.writeBuffer("Turnaround process " + proc.get(i).id + ": " + turnaround);
}
}
}
| false | false | null | null |
diff --git a/tycho-plugins/repository-utils/src/main/java/org/jboss/tools/tycho/sitegenerator/FetchSourcesFromManifests.java b/tycho-plugins/repository-utils/src/main/java/org/jboss/tools/tycho/sitegenerator/FetchSourcesFromManifests.java
index 9b4a472..46eb84b 100644
--- a/tycho-plugins/repository-utils/src/main/java/org/jboss/tools/tycho/sitegenerator/FetchSourcesFromManifests.java
+++ b/tycho-plugins/repository-utils/src/main/java/org/jboss/tools/tycho/sitegenerator/FetchSourcesFromManifests.java
@@ -1,482 +1,484 @@
/**
- * Copyright (c) 2014, Red Hat, Inc.
+ * Copyright (c) 2014-2015, Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is 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
*
* Contributor:
* Nick Boldt (Red Hat, Inc.) - initial API and implementation
******************************************************************************/
package org.jboss.tools.tycho.sitegenerator;
import java.io.BufferedInputStream;
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.OutputStream;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.maven.artifact.manager.WagonManager;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.wagon.Wagon;
import org.apache.maven.wagon.repository.Repository;
import org.codehaus.plexus.util.FileUtils;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
/**
* This class performs the following:
*
* a) for a list of projects and a single plugin in current repo
*
* b) retrieve the MANIFEST.MF file:
*
* org.jboss.tools.usage_1.2.100.Alpha2-v20140221-1555-B437.jar!/META-INF/
* MANIFEST.MF
*
* c) parse out the commitId from Eclipse-SourceReferences:
*
* Eclipse-SourceReferences: scm:git:https://github.com/jbosstools/jbosst
* ools-base.git;path="usage/plugins/org.jboss.tools.usage";commitId=184
* e18cc3ac7c339ce406974b6a4917f73909cc4
*
* d) turn those into SHAs, eg., 184e18cc3ac7c339ce406974b6a4917f73909cc4
*
* e) fetch source zips for those SHAs, eg.,
* https://github.com/jbosstools/jbosstools-base/archive/184e18cc3ac7c339ce406974b6a4917f73909cc4.zip and save as
* jbosstools-base_184e18cc3ac7c339ce406974b6a4917f73909cc4_sources.zip
*
* digest file listing:
*
* github project, plugin, version, SHA, origin/branch@SHA, remote zipfile, local zipfile
*
* jbosstools-base, org.jboss.tools.usage, 1.2.100.Alpha2-v20140221-1555-B437, 184e18cc3ac7c339ce406974b6a4917f73909cc4,
* origin/jbosstools-4.1.x@184e18cc3ac7c339ce406974b6a4917f73909cc4, https://github.com/jbosstools/jbosstools-base/archive/184e18cc3ac7c339ce406974b6a4917f73909cc4.zip,
* jbosstools-base_184e18cc3ac7c339ce406974b6a4917f73909cc4_sources.zip
*
* f) unpack each source zip and combine them into a single zip
*/
@Mojo(name = "fetch-sources-from-manifests", defaultPhase = LifecyclePhase.PACKAGE)
public class FetchSourcesFromManifests extends AbstractMojo {
// Two modes of operation when merging zips: either store them in cache folder, or just delete them
private static final int CACHE_ZIPS = 1;
private static final int PURGE_ZIPS = 2;
@Parameter(property = "project", required = true, readonly = true)
private MavenProject project;
/**
* Map of projects to plugins, so we know where to get the SHA (git
* revision)
*
* sourceFetchMap>
* jbosstools-aerogear>org.jboss.tools.aerogear.hybrid.core</jbosstools-aerogear>
* jbosstools-arquillian>org.jboss.tools.arquillian.core</jbosstools-arquillian>
* jbosstools-base>org.jboss.tools.common</jbosstools-base>
* jbosstools-birt>org.jboss.tools.birt.core</jbosstools-birt>
* jbosstools-central>org.jboss.tools.central</jbosstools-central>
* jbosstools-forge>org.jboss.tools.forge.core</jbosstools-forge>
* jbosstools-freemarker>org.jboss.ide.eclipse.freemarker</jbosstools-freemarker>
* jbosstools-gwt>org.jboss.tools.gwt.core</jbosstools-gwt>
* jbosstools-hibernate>org.hibernate.eclipse</jbosstools-hibernate>
* jbosstools-javaee>org.jboss.tools.jsf</jbosstools-javaee>
* jbosstools-jst>org.jboss.tools.jst.web</jbosstools-jst>
* jbosstools-livereload>org.jboss.tools.livereload.core</jbosstools-livereload>
* jbosstools-openshift>org.jboss.tools.openshift.egit.core</jbosstools-openshift>
* jbosstools-portlet>org.jboss.tools.portlet.core</jbosstools-portlet>
* jbosstools-server>org.jboss.ide.eclipse.as.core</jbosstools-server>
* jbosstools-vpe>org.jboss.tools.vpe</jbosstools-vpe>
* jbosstools-webservices>org.jboss.tools.ws.core</jbosstools-webservices>
* /sourceFetchMap>
*/
@Parameter
private Map<String, String> sourceFetchMap;
/**
* Alternative location to look for zips. Here is the order to process zip
* research
*
* 1. Look for zip in zipCacheFolder
* 2. Look for zip in outputFolder
* 3. Look for zip at expected URL
*/
@Parameter(property = "fetch-sources-from-manifests.zipCacheFolder", defaultValue = "${basedir}/cache")
private File zipCacheFolder;
/**
* Location where to put zips
*
* @parameter default-value="${basedir}/zips" property="fetch-sources-from-manifests.outputFolder"
*/
@Parameter(property = "fetch-sources-from-manifests.outputFolder", defaultValue = "${basedir}/zips")
private File outputFolder;
// the zip file to be created; default is "jbosstools-src.zip" but can override here
@Parameter(property = "fetch-sources-from-manifests.sourcesZip", defaultValue = "${project.build.directory}/fullSite/all/jbosstools-src.zip")
private File sourcesZip;
// the folder at the root of the zip; default is "jbosstools-src.zip!sources/" but can override here
@Parameter(property = "fetch-sources-from-manifests.sourcesZipRootFolder", defaultValue="sources")
private String sourcesZipRootFolder;
@Parameter(property = "fetch-sources-from-manifests.columnSeparator", defaultValue = ",")
private String columnSeparator;
@Parameter(property = "fetch-sources-from-manifests.skip", defaultValue = "false")
private boolean skip;
/**
* @component
*/
@Component
private WagonManager wagonManager;
private String MANIFEST = "MANIFEST.MF";
public void execute() throws MojoExecutionException, MojoFailureException {
if (this.zipCacheFolder == null) {
this.zipCacheFolder = new File(project.getBasedir() + File.separator + "cache" + File.separator);
}
if (this.zipCacheFolder != null && !this.zipCacheFolder.isDirectory()) {
try {
if (!this.zipCacheFolder.exists()) {
this.zipCacheFolder.mkdirs();
}
} catch (Exception ex) {
throw new MojoExecutionException("'zipCacheFolder' must be a directory", ex);
}
}
if (this.outputFolder == null) {
this.outputFolder = new File(project.getBasedir() + File.separator + "zips" + File.separator);
}
if (this.outputFolder.equals(this.zipCacheFolder)) {
throw new MojoExecutionException("zipCacheFolder and outputFolder can not be the same folder");
}
File zipsDirectory = new File(this.outputFolder, "all");
if (!zipsDirectory.exists()) {
zipsDirectory.mkdirs();
}
Set<File> zipFiles = new HashSet<File>();
Properties allBuildProperties = new Properties();
File digestFile = new File(this.outputFolder, "ALL_REVISIONS.txt");
FileWriter dfw;
StringBuffer sb = new StringBuffer();
String branch = project.getProperties().getProperty("mvngit.branch");
sb.append("-=> " + project.getGroupId() + ":" + project.getArtifactId() + ":" + project.getVersion() + columnSeparator + branch + " <=-\n");
String pluginPath = project.getBasedir() + File.separator + "target" + File.separator + "repository" + File.separator + "plugins";
String sep = " " + columnSeparator + " ";
for (String projectName : this.sourceFetchMap.keySet()) {
String pluginName = this.sourceFetchMap.get(projectName);
// jbosstools-base = org.jboss.tools.common
// getLog().info(projectName + " = " + pluginName);
// find the first matching plugin jar, eg., target/repository/plugins/org.jboss.tools.common_3.6.0.Alpha2-v20140304-0055-B440.jar
File[] matchingFiles = listFilesMatching(new File(pluginPath), pluginName + "_.+\\.jar");
// for (File file : matchingFiles) getLog().debug(file.toString());
if (matchingFiles.length < 1) {
throw new MojoExecutionException("No matching plugin found in " + pluginPath + " for " + pluginName + "_.+\\.jar.\nCheck your pom.xml for this line: <" + projectName + ">" + pluginName + "</" + projectName + ">");
}
File jarFile = matchingFiles[0];
File manifestFile = null;
try {
FileInputStream fin = new FileInputStream(jarFile);
manifestFile = File.createTempFile(MANIFEST, "");
OutputStream out = new FileOutputStream(manifestFile);
BufferedInputStream bin = new BufferedInputStream(fin);
ZipInputStream zin = new ZipInputStream(bin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
// getLog().info(ze.getName());
if (ze.getName().equals("META-INF/" + MANIFEST)) {
// getLog().info("Found " + ze.getName() + " in " +
// jarFile);
byte[] buffer = new byte[8192];
int len;
while ((len = zin.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.close();
break;
}
}
zin.close();
// getLog().info("Saved " + jarFile + "!/META-INF/" + MANIFEST);
} catch (Exception ex) {
throw new MojoExecutionException("Error extracting " + MANIFEST + " from " + jarFile, ex);
}
// retrieve the MANIFEST.MF file, eg., org.jboss.tools.usage_1.2.100.Alpha2-v20140221-1555-B437.jar!/META-INF/MANIFEST.MF
Manifest manifest;
try {
manifest = new Manifest(new FileInputStream(manifestFile));
} catch (Exception ex) {
throw new MojoExecutionException("Error while reading manifest file " + MANIFEST, ex);
}
// parse out the commitId from Eclipse-SourceReferences:
// scm:git:https://github.com/jbosstools/jbosstools-base.git;path="usage/plugins/org.jboss.tools.usage";commitId=184e18cc3ac7c339ce406974b6a4917f73909cc4
Attributes attr = manifest.getMainAttributes();
String ESR = null;
String SHA = null;
ESR = attr.getValue("Eclipse-SourceReferences");
// getLog().info(ESR);
if (ESR != null) {
SHA = ESR.substring(ESR.lastIndexOf(";commitId=") + 10);
// getLog().info(SHA);
} else {
SHA = "UNKNOWN";
}
// cleanup
manifestFile.delete();
// fetch github source archive for that SHA, eg., https://github.com/jbosstools/jbosstools-base/archive/184e18cc3ac7c339ce406974b6a4917f73909cc4.zip
// to jbosstools-base_184e18cc3ac7c339ce406974b6a4917f73909cc4_sources.zip
String URL = "";
String outputZipName = "";
try {
if (SHA == null || SHA.equals("UNKNOWN")) {
getLog().warn("Cannot fetch " + projectName + " sources: no Eclipse-SourceReferences in " + removePrefix(jarFile.toString(), pluginPath) + " " + MANIFEST);
} else {
URL = "https://github.com/jbosstools/" + projectName + "/archive/" + SHA + ".zip";
outputZipName = projectName + "_" + SHA + "_sources.zip";
File outputZipFile = new File(zipsDirectory, outputZipName);
boolean diduseCache = false;
if (this.zipCacheFolder != null && this.zipCacheFolder.exists()) {
File cachedZip = new File(this.zipCacheFolder, outputZipName);
if (cachedZip.exists()) {
FileUtils.copyFile(cachedZip, outputZipFile);
getLog().debug("Copied " + removePrefix(outputZipFile.getAbsolutePath(), project.getBasedir().toString()));
getLog().debug(" From " + removePrefix(cachedZip.getAbsolutePath(), project.getBasedir().toString()));
diduseCache = true;
}
}
// scrub out old versions that we don't want in the cache anymore
File[] matchingSourceZips = listFilesMatching(zipsDirectory, projectName + "_.+\\.zip");
for (int i = 0; i < matchingSourceZips.length; i++) {
// don't delete the file we want, only all others matching projectName_.zip
if (!outputZipFile.getName().equals(matchingSourceZips[i].getName())) {
getLog().warn("Delete " + matchingSourceZips[i].getName());
matchingSourceZips[i].delete();
}
}
File[] matchingSourceMD5s = listFilesMatching(zipsDirectory, projectName + "_.+\\.zip\\.MD5");
for (int i = 0; i < matchingSourceMD5s.length; i++) {
// don't delete the file we want, only all others matching projectName_.zip or .MD5
if (!(outputZipFile.getName() + ".MD5").equals(matchingSourceMD5s[i].getName())) {
getLog().warn("Delete " + matchingSourceMD5s[i].getName());
matchingSourceMD5s[i].delete();
}
}
String outputZipFolder = outputZipFile.toString().replaceAll("_sources.zip","");
if (!diduseCache && (!outputZipFile.exists() || !(new File(outputZipFolder).exists()))) {
doGet(URL, outputZipFile, true);
}
allBuildProperties.put(outputZipName + ".filename", outputZipName);
allBuildProperties.put(outputZipName + ".filesize", Long.toString(outputZipName.length()));
zipFiles.add(new File(outputZipName));
}
} catch (Exception ex) {
throw new MojoExecutionException("Error while downloading github source archive", ex);
}
// github project, plugin, version, SHA, origin/branch@SHA, remote zipfile, local zipfile
String revisionLine = projectName + sep + pluginName + sep + getQualifier(pluginName, jarFile.toString(), true) + sep + SHA + sep + "origin/" + branch + "@" + SHA + sep + URL + sep + outputZipName + "\n";
// getLog().info(revisionLine);
sb.append(revisionLine);
}
// JBDS-3364 JBDS-3208 JBIDE-19467 when not using publish.sh, unpack downloaded source zips and combine them into a single zip
createCombinedZipFile(zipFiles, CACHE_ZIPS);
// getLog().info("Generating aggregate site metadata");
try {
{
File buildPropertiesAllXml = new File(this.outputFolder, "build.properties.all.xml");
if (!buildPropertiesAllXml.exists()) {
buildPropertiesAllXml.createNewFile();
}
FileOutputStream xmlOut = new FileOutputStream(buildPropertiesAllXml);
allBuildProperties.storeToXML(xmlOut, null);
xmlOut.close();
}
{
File buildPropertiesFileTxt = new File(this.outputFolder, "build.properties.file.txt");
if (!buildPropertiesFileTxt.exists()) {
buildPropertiesFileTxt.createNewFile();
}
FileOutputStream textOut = new FileOutputStream(buildPropertiesFileTxt);
allBuildProperties.store(textOut, null);
textOut.close();
}
} catch (Exception ex) {
throw new MojoExecutionException("Error while creating 'metadata' files", ex);
}
try {
dfw = new FileWriter(digestFile);
dfw.write(sb.toString());
dfw.close();
} catch (Exception ex) {
throw new MojoExecutionException("Error writing to " + digestFile.toString(), ex);
}
// getLog().info("Written to " + digestFile.toString() + ":\n\n" + sb.toString());
}
/*
* Given a set of zip files, unpack them and merge them into a single combined source zip
* If mode == PURGE_ZIPS, delete zips to save disk space, keeping only the combined zip
* If mode == CACHE_ZIPS, move zips into cache folder
*
*/
private void createCombinedZipFile(Set<File> zipFiles, int mode)
throws MojoExecutionException {
File zipsDirectory = new File(this.outputFolder, "all");
String combinedZipName = sourcesZip.getAbsolutePath();
ZipFile combinedZipFile = null;
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_FAST);
parameters.setEncryptFiles(false);
try {
combinedZipFile = new ZipFile(combinedZipName);
} catch (ZipException ex) {
throw new MojoExecutionException ("Error creating " + combinedZipName, ex);
}
String fullUnzipPath = zipsDirectory.getAbsolutePath() + File.separator + sourcesZipRootFolder;
// unpack the zips into a temp folder
for (File outputFile : zipFiles) {
try {
String zipFileName = zipsDirectory.getAbsolutePath() + File.separator + outputFile.getName();
getLog().debug("Unpacking: " + zipFileName);
getLog().debug("Unpack to: " + fullUnzipPath);
// unpack zip
(new ZipFile(zipFileName)).extractAll(fullUnzipPath);
File zipFile = new File(zipFileName);
if (mode == PURGE_ZIPS) {
// delete downloaded zip
getLog().debug("Delete zip: " + zipFileName);
zipFile.delete();
}
else if (mode == CACHE_ZIPS)
{
// move downloaded zip into cache folder
getLog().debug("Cache " + zipFileName + " in " + this.zipCacheFolder);
zipFile.renameTo(new File(this.zipCacheFolder,zipFile.getName()));
}
} catch (ZipException ex) {
throw new MojoExecutionException ("Error unpacking " + outputFile.toString() + " to " + fullUnzipPath, ex);
}
}
- // pack the sources into a new zip
+ // TODO: JBIDE-19814 - include local sources in jbosstools-project-SHA folder (jbosstools-build-sites or jbdevstudio-product)
+ // TODO: compute SHA from .git metadata if not available from a plugin's MANIFEST.MF
+
+ // TODO: JBIDE-19798 - include buildinfo.json from target/repository/ or target/fullSite/all/repo/
+
+ // TODO: include upstream buildinfo.json files from all the projects, too, renamed as jbosstools-projectname-buildinfo.json in root folder
+
+ // pack the unzipped sources into the new zip
try {
getLog().debug("Pack from: " + fullUnzipPath);
combinedZipFile.addFolder(fullUnzipPath, parameters);
getLog().debug("Packed to: " + combinedZipFile.getFile().getAbsolutePath());
double filesize = combinedZipFile.getFile().length();
getLog().debug("Pack size: " + (filesize >= 1024 * 1024 ? String.format("%.1f", filesize / 1024 / 1024) + " M" : String.format("%.1f", filesize / 1024) + " k"));
} catch (ZipException e) {
throw new MojoExecutionException ("Error packing " + combinedZipFile, e);
}
// delete temp folder with sources
try {
getLog().debug("Delete dir: " + fullUnzipPath);
FileUtils.deleteDirectory(new File(fullUnzipPath));
} catch (IOException ex) {
throw new MojoExecutionException ("IO Exception:", ex);
}
}
private String removePrefix(String stringToTrim, String prefix) {
return stringToTrim.substring(stringToTrim.lastIndexOf(prefix) + prefix.length() + 1);
}
// given: pluginName = org.jboss.tools.common
// given: jarFileName =
// target/repository/plugins/org.jboss.tools.common_3.6.0.Alpha2-v20140304-0055-B440.jar
// return 3.6.0.Alpha2-v20140304-0055-B440 (if full = true)
// return Alpha2-v20140304-0055-B440 (if full = false)
private String getQualifier(String pluginName, String jarFileName, boolean full) {
// trim .../pluginName prefix
String qualifier = removePrefix(jarFileName, pluginName);
// trim .jar suffix
qualifier = qualifier.substring(0, qualifier.length() - 4);
// getLog().info("qualifier[0] = " + qualifier);
return full ? qualifier : qualifier.replaceAll("^(\\d+\\.\\d+\\.\\d+\\.)", "");
}
// thanks to
// http://stackoverflow.com/questions/2928680/regex-for-files-in-a-directory
public static File[] listFilesMatching(File root, String regex) throws MojoExecutionException {
if (!root.isDirectory()) {
throw new MojoExecutionException(root + " is not a directory.");
}
final Pattern p = Pattern.compile(regex);
return root.listFiles(new FileFilter() {
public boolean accept(File file) {
return p.matcher(file.getName()).matches();
}
});
}
- // sourced from
- // https://github.com/maven-download-plugin/maven-download-plugin/blob/master/download-maven-plugin/src/main/java/com/googlecode/WGet.java
- private void doGet(String url, File outputFile) throws Exception {
- doGet(url,outputFile,false);
- }
-
+ // sourced from https://github.com/maven-download-plugin/maven-download-plugin/blob/master/download-maven-plugin/src/main/java/com/googlecode/WGet.java
private void doGet(String url, File outputFile, boolean unpack) throws Exception {
String[] segments = url.split("/");
String file = segments[segments.length - 1];
String repoUrl = url.substring(0, url.length() - file.length() - 1);
Repository repository = new Repository(repoUrl, repoUrl);
Wagon wagon = this.wagonManager.getWagon(repository.getProtocol());
// TODO: this should be retrieved from wagonManager
// com.googlecode.ConsoleDownloadMonitor downloadMonitor = new com.googlecode.ConsoleDownloadMonitor();
// wagon.addTransferListener(downloadMonitor);
wagon.connect(repository, this.wagonManager.getProxy(repository.getProtocol()));
wagon.get(file, outputFile);
wagon.disconnect();
// wagon.removeTransferListener(downloadMonitor);
double filesize = outputFile.length();
getLog().info("Downloaded: " + outputFile.getName() + " (" + (filesize >= 1024 * 1024 ? String.format("%.1f", filesize / 1024 / 1024) + " M)" : String.format("%.1f", filesize / 1024) + " k)"));
}
}
diff --git a/tycho-plugins/repository-utils/src/main/java/org/jboss/tools/tycho/sitegenerator/GenerateDirectoryXmlMojo.java b/tycho-plugins/repository-utils/src/main/java/org/jboss/tools/tycho/sitegenerator/GenerateDirectoryXmlMojo.java
index e164e2b..be5f16c 100644
--- a/tycho-plugins/repository-utils/src/main/java/org/jboss/tools/tycho/sitegenerator/GenerateDirectoryXmlMojo.java
+++ b/tycho-plugins/repository-utils/src/main/java/org/jboss/tools/tycho/sitegenerator/GenerateDirectoryXmlMojo.java
@@ -1,72 +1,72 @@
/**
- * Copyright (c) 2014, Red Hat, Inc.
+ * Copyright (c) 2014-2015, Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is 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
*
* Contributor:
* Mickael Istria (Red Hat, Inc.) - initial API and implementation
******************************************************************************/
package org.jboss.tools.tycho.sitegenerator;
import java.io.File;
import org.apache.commons.io.FileUtils;
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.apache.maven.project.MavenProject;
import org.eclipse.tycho.PackagingType;
@Mojo(defaultPhase = LifecyclePhase.PACKAGE, name = "generate-discovery-site")
public class GenerateDirectoryXmlMojo extends AbstractMojo {
@Parameter(property = "project", required = true, readonly = true)
private MavenProject project;
@Parameter(defaultValue = "${project.build.directory}/discovery-site/")
private File outputDirectory;
@Parameter
private String discoveryFileName;
public void execute() throws MojoExecutionException, MojoFailureException {
if (! PackagingType.TYPE_ECLIPSE_REPOSITORY.equals(this.project.getPackaging())) {
return;
}
if (!this.outputDirectory.exists()) {
this.outputDirectory.mkdirs();
}
File repositoryPluginsFolder = new File(project.getBuild().getDirectory(), "repository/plugins");
File discoveryPluginsFolder = new File(this.outputDirectory, "plugins");
StringBuilder directoryXml = new StringBuilder();
directoryXml.append("<?xml version='1.0' encoding='UTF-8'?>\n");
directoryXml.append("<directory xmlns='http://www.eclipse.org/mylyn/discovery/directory/'>\n");
for (File plugin : repositoryPluginsFolder.listFiles()) {
directoryXml.append(" <entry url='plugins/");
directoryXml.append(plugin.getName());
directoryXml.append("' permitCategories='true'/>");
directoryXml.append('\n');
try {
FileUtils.copyFileToDirectory(plugin, discoveryPluginsFolder);
} catch (Exception ex) {
throw new MojoFailureException(ex.getMessage(), ex);
}
}
directoryXml.append("</directory>");
if (this.discoveryFileName == null) {
this.discoveryFileName = this.project.getArtifactId() + ".xml";
}
try {
FileUtils.writeStringToFile(new File(this.outputDirectory, this.discoveryFileName), directoryXml.toString());
} catch (Exception ex) {
throw new MojoFailureException(ex.getMessage(), ex);
}
}
}
diff --git a/tycho-plugins/target-platform-utils/src/main/java/org/jboss/tools/tycho/targets/FixVersionsMojo.java b/tycho-plugins/target-platform-utils/src/main/java/org/jboss/tools/tycho/targets/FixVersionsMojo.java
index fde5f58..b8d211c 100644
--- a/tycho-plugins/target-platform-utils/src/main/java/org/jboss/tools/tycho/targets/FixVersionsMojo.java
+++ b/tycho-plugins/target-platform-utils/src/main/java/org/jboss/tools/tycho/targets/FixVersionsMojo.java
@@ -1,211 +1,211 @@
/*******************************************************************************
- * Copyright (c) 2013-2014 Red Hat, Inc and others.
+ * Copyright (c) 2013-2015 Red Hat, Inc 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:
* Mickael Istria (Red Hat) - initial API and implementation
*******************************************************************************/
package org.jboss.tools.tycho.targets;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.logging.Logger;
import org.eclipse.sisu.equinox.EquinoxServiceFactory;
import org.eclipse.tycho.artifacts.TargetPlatform;
import org.eclipse.tycho.core.resolver.shared.IncludeSourceMode;
import org.eclipse.tycho.core.resolver.shared.MavenRepositoryLocation;
import org.eclipse.tycho.osgi.adapters.MavenLoggerAdapter;
import org.eclipse.tycho.p2.resolver.TargetDefinitionFile;
import org.eclipse.tycho.p2.resolver.facade.P2ResolutionResult;
import org.eclipse.tycho.p2.resolver.facade.P2Resolver;
import org.eclipse.tycho.p2.resolver.facade.P2ResolverFactory;
import org.eclipse.tycho.p2.target.facade.TargetDefinition.InstallableUnitLocation;
import org.eclipse.tycho.p2.target.facade.TargetDefinition.Location;
import org.eclipse.tycho.p2.target.facade.TargetDefinition.Repository;
import org.eclipse.tycho.p2.target.facade.TargetDefinition.Unit;
import org.eclipse.tycho.p2.target.facade.TargetPlatformConfigurationStub;
import org.osgi.framework.Version;
/**
* @author mistria
*/
@Mojo(name = "fix-versions", requiresProject = false, defaultPhase = LifecyclePhase.GENERATE_RESOURCES)
public class FixVersionsMojo extends AbstractMojo {
@Parameter(property = "targetFile")
private File targetFile;
@Parameter(property = "project")
private MavenProject project;
@Component
protected EquinoxServiceFactory equinox;
@Component
private Logger plexusLogger;
@SuppressWarnings("deprecation")
public void execute() throws MojoExecutionException, MojoFailureException {
if (this.targetFile == null) {
if (this.project != null && this.project.getPackaging().equals("eclipse-target-definition")) {
this.targetFile = new File(this.project.getBasedir(), this.project.getArtifactId() + ".target");
}
}
if (this.targetFile == null) {
throw new MojoFailureException("You need to set a <targetFile/> for packaging types that are not 'eclipse-target-definition'");
}
if (!this.targetFile.isFile()) {
throw new MojoFailureException("Specified target file " + this.targetFile.getAbsolutePath() + " is not a valid file");
}
File outputFile = new File(targetFile.getParentFile(), targetFile.getName() + "_update_hints.txt");
FileOutputStream fos = null;
try {
outputFile.createNewFile();
fos = new FileOutputStream(outputFile);
P2ResolverFactory resolverFactory = this.equinox.getService(P2ResolverFactory.class);
TargetDefinitionFile targetDef;
try {
targetDef = TargetDefinitionFile.read(this.targetFile, IncludeSourceMode.ignore);
} catch (Exception ex) {
throw new MojoExecutionException(ex.getMessage(), ex);
}
for (Location location : targetDef.getLocations()) {
if (!(location instanceof InstallableUnitLocation)) {
getLog().warn("Location type " + location.getClass().getSimpleName() + " not supported");
continue;
}
InstallableUnitLocation loc = (InstallableUnitLocation) location;
TargetPlatformConfigurationStub tpConfig = new TargetPlatformConfigurationStub();
for (Repository repo : loc.getRepositories()) {
String id = repo.getId();
if (repo.getId() == null || repo.getId().isEmpty()) {
id = repo.getLocation().toString();
}
tpConfig.addP2Repository(new MavenRepositoryLocation(id, repo.getLocation()));
}
TargetPlatform site = resolverFactory.getTargetPlatformFactory().createTargetPlatform(
tpConfig, new MockExecutionEnvironment(), null, null);
P2Resolver resolver = resolverFactory.createResolver(new MavenLoggerAdapter(this.plexusLogger, true));
for (Unit unit : loc.getUnits()) {
getLog().info("checking " + unit.getId());
String version = findBestMatchingVersion(site, resolver, unit);
if (!version.equals(unit.getVersion())) {
String message = unit.getId() + " ->" + version;
getLog().info(message);
fos.write(message.getBytes());
fos.write('\n');
}
if (unit instanceof TargetDefinitionFile.Unit) {
// That's deprecated, but so cool (and no other way to do it except doing parsing by hand)
((TargetDefinitionFile.Unit)unit).setVersion(version);
}
}
}
TargetDefinitionFile.write(targetDef, new File(targetFile.getParent(), targetFile.getName() + "_fixedVersion.target"));
} catch (FileNotFoundException ex) {
throw new MojoExecutionException("Error while opening output file " + outputFile, ex);
} catch (IOException ex) {
throw new MojoExecutionException("Can't write to file " + outputFile, ex);
} finally {
if (fos != null) {
try {
fos.close();
} catch (Exception ex) {
throw new MojoExecutionException("IO error", ex);
}
}
}
}
private String findBestMatchingVersion(TargetPlatform site, P2Resolver resolver, Unit unit) throws MojoFailureException, MojoExecutionException {
String version = unit.getVersion();
P2ResolutionResult currentIUResult = resolver.resolveInstallableUnit(site, unit.getId(), toQueryExactVersion(version));
if (currentIUResult.getArtifacts().isEmpty() && currentIUResult.getNonReactorUnits().isEmpty()) {
currentIUResult = resolver.resolveInstallableUnit(site, unit.getId(), toQueryIgnoreQualifier(version));
if (currentIUResult.getArtifacts().isEmpty() && currentIUResult.getNonReactorUnits().isEmpty()) {
currentIUResult = resolver.resolveInstallableUnit(site, unit.getId(), toQueryIgnoreMicro(version));
if (currentIUResult.getArtifacts().isEmpty() && currentIUResult.getNonReactorUnits().isEmpty()) {
currentIUResult = resolver.resolveInstallableUnit(site, unit.getId(), toQueryIgnoreMinor(version));
if (currentIUResult.getArtifacts().isEmpty() && currentIUResult.getNonReactorUnits().isEmpty()) {
currentIUResult = resolver.resolveInstallableUnit(site, unit.getId(), "0.0.0");
}
}
}
}
if (currentIUResult.getArtifacts().size() > 0) {
return currentIUResult.getArtifacts().iterator().next().getVersion();
} else if (currentIUResult.getNonReactorUnits().size() > 0) {
Object foundItem = currentIUResult.getNonReactorUnits().iterator().next();
// foundItem is most probably a p2 internal InstallableUnit (type not accessible from Tycho). Let's do some introspection
try {
Method getVersionMethod = foundItem.getClass().getMethod("getVersion");
Object foundVersion = getVersionMethod.invoke(foundItem);
return foundVersion.toString();
} catch (Exception ex) {
throw new MojoExecutionException("Unsupported search result " + foundItem.getClass(), ex);
}
} else {
throw new MojoFailureException("Could not find any IU for " + unit.getId());
}
}
private String toQueryExactVersion(String version) {
return "[" + version + "," + version + "]";
}
private String toQueryIgnoreMinor(String version) {
Version osgiVersion = new Version(version);
StringBuilder res = new StringBuilder();
res.append("[");
res.append(osgiVersion.getMajor()); res.append(".0.0");
res.append(",");
res.append(osgiVersion.getMajor() + 1); res.append(".0.0");
res.append(")");
return res.toString();
}
private String toQueryIgnoreMicro(String version) {
Version osgiVersion = new Version(version);
StringBuilder res = new StringBuilder();
res.append("[");
res.append(osgiVersion.getMajor()); res.append("."); res.append(osgiVersion.getMinor()); res.append(".0");
res.append(",");
res.append(osgiVersion.getMajor()); res.append("."); res.append(osgiVersion.getMinor() + 1); res.append(".0");
res.append(")");
return res.toString();
}
private String toQueryIgnoreQualifier(String version) {
Version osgiVersion = new Version(version);
StringBuilder res = new StringBuilder();
res.append("[");
res.append(osgiVersion.getMajor()); res.append("."); res.append(osgiVersion.getMinor()); res.append("."); res.append(osgiVersion.getMicro());
res.append(",");
res.append(osgiVersion.getMajor()); res.append("."); res.append(osgiVersion.getMinor()); res.append("."); res.append(osgiVersion.getMicro() + 1);
res.append(")");
return res.toString();
}
}
| false | false | null | null |
diff --git a/src/main/java/com/alta189/deskbin/gui/OptionsDialog.java b/src/main/java/com/alta189/deskbin/gui/OptionsDialog.java
index d651b16..f434108 100644
--- a/src/main/java/com/alta189/deskbin/gui/OptionsDialog.java
+++ b/src/main/java/com/alta189/deskbin/gui/OptionsDialog.java
@@ -1,104 +1,99 @@
/*
* This file is part of DeskBin.
*
* Copyright (c) 2012, alta189 <http://github.com/alta189/DeskBin/>
* DeskBin is licensed under the GNU Lesser General Public License.
*
* DeskBin 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 3 of the License, or
* (at your option) any later version.
*
* DeskBin 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. If not, see <http://www.gnu.org/licenses/>.
*/
package com.alta189.deskbin.gui;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
-
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
-import javax.swing.JTable;
-import com.alta189.deskbin.DeskBin;
import com.alta189.deskbin.util.UIUtil;
-import com.alta189.deskbin.util.yaml.YAMLProcessor;
public class OptionsDialog extends JDialog {
private JTabbedPane tabs;
private List<OptionsPanel> optionsPanels = new ArrayList<OptionsPanel>();
public OptionsDialog(String title, Map<String, OptionsPanel> optionsPanels) {
setTitle(title);
setResizable(false);
buildUserInterface(optionsPanels);
pack();
setSize(400, 500);
}
private <T extends OptionsPanel> T wrap(T panel) {
optionsPanels.add(panel);
return panel;
}
public void buildUserInterface(Map<String, OptionsPanel> optionsPanels) {
final OptionsDialog self = this;
JPanel container = new JPanel();
container.setBorder(BorderFactory.createEmptyBorder(8, 8, 5, 8));
container.setLayout(new BorderLayout(3, 3));
tabs = new JTabbedPane();
for (String title : optionsPanels.keySet()) {
tabs.add(title, wrap(optionsPanels.get(title)));
}
container.add(tabs, BorderLayout.CENTER);
JPanel buttonsPanel = new JPanel();
buttonsPanel.setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 5));
JButton okButton = new JButton("OK");
JButton cancelButton = new JButton("Cancel");
UIUtil.equalWidth(okButton, cancelButton);
buttonsPanel.add(okButton);
buttonsPanel.add(cancelButton);
container.add(buttonsPanel, BorderLayout.SOUTH);
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
self.save();
self.dispose();
}
});
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
self.dispose();
}
});
self.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
add(container, BorderLayout.CENTER);
}
-
+
public void save() {
for (OptionsPanel panel : optionsPanels) {
panel.save();
}
}
-
}
| false | false | null | null |
diff --git a/src/com/android/email/activity/MessageViewFragmentBase.java b/src/com/android/email/activity/MessageViewFragmentBase.java
index 8bf08f5e..58a3d458 100644
--- a/src/com/android/email/activity/MessageViewFragmentBase.java
+++ b/src/com/android/email/activity/MessageViewFragmentBase.java
@@ -1,1964 +1,1965 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.email.activity;
import android.app.Activity;
import android.app.DownloadManager;
import android.app.Fragment;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.Loader;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.ContactsContract;
import android.provider.ContactsContract.QuickContact;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.Log;
import android.util.Patterns;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.android.email.AttachmentInfo;
import com.android.email.Controller;
import com.android.email.ControllerResultUiThreadWrapper;
import com.android.email.Email;
import com.android.email.Preferences;
import com.android.email.R;
import com.android.email.Throttle;
import com.android.email.mail.internet.EmailHtmlUtil;
import com.android.email.service.AttachmentDownloadService;
import com.android.emailcommon.Logging;
import com.android.emailcommon.mail.Address;
import com.android.emailcommon.mail.MessagingException;
import com.android.emailcommon.provider.Account;
import com.android.emailcommon.provider.EmailContent.Attachment;
import com.android.emailcommon.provider.EmailContent.Body;
import com.android.emailcommon.provider.EmailContent.Message;
import com.android.emailcommon.provider.Mailbox;
import com.android.emailcommon.utility.AttachmentUtilities;
import com.android.emailcommon.utility.EmailAsyncTask;
import com.android.emailcommon.utility.Utility;
import com.google.common.collect.Maps;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Formatter;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// TODO Better handling of config changes.
// - Retain the content; don't kick 3 async tasks every time
/**
* Base class for {@link MessageViewFragment} and {@link MessageFileViewFragment}.
*/
public abstract class MessageViewFragmentBase extends Fragment implements View.OnClickListener {
private static final String BUNDLE_KEY_CURRENT_TAB = "MessageViewFragmentBase.currentTab";
private static final String BUNDLE_KEY_PICTURE_LOADED = "MessageViewFragmentBase.pictureLoaded";
private static final int PHOTO_LOADER_ID = 1;
protected Context mContext;
// Regex that matches start of img tag. '<(?i)img\s+'.
private static final Pattern IMG_TAG_START_REGEX = Pattern.compile("<(?i)img\\s+");
// Regex that matches Web URL protocol part as case insensitive.
private static final Pattern WEB_URL_PROTOCOL = Pattern.compile("(?i)http|https://");
private static int PREVIEW_ICON_WIDTH = 62;
private static int PREVIEW_ICON_HEIGHT = 62;
private TextView mSubjectView;
private TextView mFromNameView;
private TextView mFromAddressView;
private TextView mDateTimeView;
private TextView mAddressesView;
private WebView mMessageContentView;
private LinearLayout mAttachments;
private View mTabSection;
private ImageView mFromBadge;
private ImageView mSenderPresenceView;
private View mMainView;
private View mLoadingProgress;
private View mDetailsCollapsed;
private View mDetailsExpanded;
private boolean mDetailsFilled;
private TextView mMessageTab;
private TextView mAttachmentTab;
private TextView mInviteTab;
// It is not really a tab, but looks like one of them.
private TextView mShowPicturesTab;
private ViewGroup mAlwaysShowPicturesContainer;
private View mAlwaysShowPicturesButton;
private View mAttachmentsScroll;
private View mInviteScroll;
private long mAccountId = Account.NO_ACCOUNT;
private long mMessageId = Message.NO_MESSAGE;
private Message mMessage;
private Controller mController;
private ControllerResultUiThreadWrapper<ControllerResults> mControllerCallback;
// contains the HTML body. Is used by LoadAttachmentTask to display inline images.
// is null most of the time, is used transiently to pass info to LoadAttachementTask
private String mHtmlTextRaw;
// contains the HTML content as set in WebView.
private String mHtmlTextWebView;
private boolean mIsMessageLoadedForTest;
private MessageObserver mMessageObserver;
private static final int CONTACT_STATUS_STATE_UNLOADED = 0;
private static final int CONTACT_STATUS_STATE_UNLOADED_TRIGGERED = 1;
private static final int CONTACT_STATUS_STATE_LOADED = 2;
private int mContactStatusState;
private Uri mQuickContactLookupUri;
/** Flag for {@link #mTabFlags}: Message has attachment(s) */
protected static final int TAB_FLAGS_HAS_ATTACHMENT = 1;
/**
* Flag for {@link #mTabFlags}: Message contains invite. This flag is only set by
* {@link MessageViewFragment}.
*/
protected static final int TAB_FLAGS_HAS_INVITE = 2;
/** Flag for {@link #mTabFlags}: Message contains pictures */
protected static final int TAB_FLAGS_HAS_PICTURES = 4;
/** Flag for {@link #mTabFlags}: "Show pictures" has already been pressed */
protected static final int TAB_FLAGS_PICTURE_LOADED = 8;
/**
* Flags to control the tabs.
* @see #updateTabs(int)
*/
private int mTabFlags;
/** # of attachments in the current message */
private int mAttachmentCount;
// Use (random) large values, to avoid confusion with TAB_FLAGS_*
protected static final int TAB_MESSAGE = 101;
protected static final int TAB_INVITE = 102;
protected static final int TAB_ATTACHMENT = 103;
private static final int TAB_NONE = 0;
/** Current tab */
private int mCurrentTab = TAB_NONE;
/**
* Tab that was selected in the previous activity instance.
* Used to restore the current tab after screen rotation.
*/
private int mRestoredTab = TAB_NONE;
private boolean mRestoredPictureLoaded;
private final EmailAsyncTask.Tracker mTaskTracker = new EmailAsyncTask.Tracker();
/**
* Zoom scales for webview. Values correspond to {@link Preferences#TEXT_ZOOM_TINY}..
* {@link Preferences#TEXT_ZOOM_HUGE}.
*/
private static final float[] ZOOM_SCALE_ARRAY = new float[] {0.8f, 0.9f, 1.0f, 1.2f, 1.5f};
public interface Callback {
/**
* Called when a link in a message is clicked.
*
* @param url link url that's clicked.
* @return true if handled, false otherwise.
*/
public boolean onUrlInMessageClicked(String url);
/**
* Called when the message specified doesn't exist, or is deleted/moved.
*/
public void onMessageNotExists();
/** Called when it starts loading a message. */
public void onLoadMessageStarted();
/** Called when it successfully finishes loading a message. */
public void onLoadMessageFinished();
/** Called when an error occurred during loading a message. */
public void onLoadMessageError(String errorMessage);
}
public static class EmptyCallback implements Callback {
public static final Callback INSTANCE = new EmptyCallback();
@Override public void onLoadMessageError(String errorMessage) {}
@Override public void onLoadMessageFinished() {}
@Override public void onLoadMessageStarted() {}
@Override public void onMessageNotExists() {}
@Override
public boolean onUrlInMessageClicked(String url) {
return false;
}
}
private Callback mCallback = EmptyCallback.INSTANCE;
@Override
public void onAttach(Activity activity) {
if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) {
Log.d(Logging.LOG_TAG, this + " onAttach");
}
super.onAttach(activity);
}
@Override
public void onCreate(Bundle savedInstanceState) {
if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) {
Log.d(Logging.LOG_TAG, this + " onCreate");
}
super.onCreate(savedInstanceState);
mContext = getActivity().getApplicationContext();
// Initialize components, but don't "start" them. Registering the controller callbacks
// and starting MessageObserver, should be done in onActivityCreated or later and be stopped
// in onDestroyView to prevent from getting callbacks when the fragment is in the back
// stack, but they'll start again when it's back from the back stack.
mController = Controller.getInstance(mContext);
mControllerCallback = new ControllerResultUiThreadWrapper<ControllerResults>(
new Handler(), new ControllerResults());
mMessageObserver = new MessageObserver(new Handler(), mContext);
if (savedInstanceState != null) {
restoreInstanceState(savedInstanceState);
}
}
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) {
Log.d(Logging.LOG_TAG, this + " onCreateView");
}
final View view = inflater.inflate(R.layout.message_view_fragment, container, false);
cleanupDetachedViews();
mSubjectView = (TextView) UiUtilities.getView(view, R.id.subject);
mFromNameView = (TextView) UiUtilities.getView(view, R.id.from_name);
mFromAddressView = (TextView) UiUtilities.getView(view, R.id.from_address);
mAddressesView = (TextView) UiUtilities.getView(view, R.id.addresses);
mDateTimeView = (TextView) UiUtilities.getView(view, R.id.datetime);
mMessageContentView = (WebView) UiUtilities.getView(view, R.id.message_content);
mAttachments = (LinearLayout) UiUtilities.getView(view, R.id.attachments);
mTabSection = UiUtilities.getView(view, R.id.message_tabs_section);
mFromBadge = (ImageView) UiUtilities.getView(view, R.id.badge);
mSenderPresenceView = (ImageView) UiUtilities.getView(view, R.id.presence);
mMainView = UiUtilities.getView(view, R.id.main_panel);
mLoadingProgress = UiUtilities.getView(view, R.id.loading_progress);
mDetailsCollapsed = UiUtilities.getView(view, R.id.sub_header_contents_collapsed);
mDetailsExpanded = UiUtilities.getView(view, R.id.sub_header_contents_expanded);
mFromNameView.setOnClickListener(this);
mFromAddressView.setOnClickListener(this);
mFromBadge.setOnClickListener(this);
mSenderPresenceView.setOnClickListener(this);
mMessageTab = UiUtilities.getView(view, R.id.show_message);
mAttachmentTab = UiUtilities.getView(view, R.id.show_attachments);
mShowPicturesTab = UiUtilities.getView(view, R.id.show_pictures);
mAlwaysShowPicturesButton = UiUtilities.getView(view, R.id.always_show_pictures_button);
mAlwaysShowPicturesContainer = UiUtilities.getView(
view, R.id.always_show_pictures_container);
// Invite is only used in MessageViewFragment, but visibility is controlled here.
mInviteTab = UiUtilities.getView(view, R.id.show_invite);
mMessageTab.setOnClickListener(this);
mAttachmentTab.setOnClickListener(this);
mShowPicturesTab.setOnClickListener(this);
mAlwaysShowPicturesButton.setOnClickListener(this);
mInviteTab.setOnClickListener(this);
mDetailsCollapsed.setOnClickListener(this);
mDetailsExpanded.setOnClickListener(this);
mAttachmentsScroll = UiUtilities.getView(view, R.id.attachments_scroll);
mInviteScroll = UiUtilities.getView(view, R.id.invite_scroll);
WebSettings webSettings = mMessageContentView.getSettings();
boolean supportMultiTouch = mContext.getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH);
webSettings.setDisplayZoomControls(!supportMultiTouch);
webSettings.setSupportZoom(true);
webSettings.setBuiltInZoomControls(true);
mMessageContentView.setWebViewClient(new CustomWebViewClient());
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) {
Log.d(Logging.LOG_TAG, this + " onActivityCreated");
}
super.onActivityCreated(savedInstanceState);
mController.addResultCallback(mControllerCallback);
resetView();
new LoadMessageTask(true).executeParallel();
UiUtilities.installFragment(this);
}
@Override
public void onStart() {
if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) {
Log.d(Logging.LOG_TAG, this + " onStart");
}
super.onStart();
}
@Override
public void onResume() {
if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) {
Log.d(Logging.LOG_TAG, this + " onResume");
}
super.onResume();
// We might have comes back from other full-screen activities. If so, we need to update
// the attachment tab as system settings may have been updated that affect which
// options are available to the user.
updateAttachmentTab();
}
@Override
public void onPause() {
if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) {
Log.d(Logging.LOG_TAG, this + " onPause");
}
super.onPause();
}
@Override
public void onStop() {
if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) {
Log.d(Logging.LOG_TAG, this + " onStop");
}
super.onStop();
}
@Override
public void onDestroyView() {
if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) {
Log.d(Logging.LOG_TAG, this + " onDestroyView");
}
UiUtilities.uninstallFragment(this);
mController.removeResultCallback(mControllerCallback);
cancelAllTasks();
// We should clean up the Webview here, but it can't release resources until it is
// actually removed from the view tree.
super.onDestroyView();
}
private void cleanupDetachedViews() {
// WebView cleanup must be done after it leaves the rendering tree, according to
// its contract
if (mMessageContentView != null) {
mMessageContentView.destroy();
mMessageContentView = null;
}
}
@Override
public void onDestroy() {
if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) {
Log.d(Logging.LOG_TAG, this + " onDestroy");
}
cleanupDetachedViews();
super.onDestroy();
}
@Override
public void onDetach() {
if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) {
Log.d(Logging.LOG_TAG, this + " onDetach");
}
super.onDetach();
}
@Override
public void onSaveInstanceState(Bundle outState) {
if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) {
Log.d(Logging.LOG_TAG, this + " onSaveInstanceState");
}
super.onSaveInstanceState(outState);
outState.putInt(BUNDLE_KEY_CURRENT_TAB, mCurrentTab);
outState.putBoolean(BUNDLE_KEY_PICTURE_LOADED, (mTabFlags & TAB_FLAGS_PICTURE_LOADED) != 0);
}
private void restoreInstanceState(Bundle state) {
if (Logging.DEBUG_LIFECYCLE && Email.DEBUG) {
Log.d(Logging.LOG_TAG, this + " restoreInstanceState");
}
// At this point (in onCreate) no tabs are visible (because we don't know if the message has
// an attachment or invite before loading it). We just remember the tab here.
// We'll make it current when the tab first becomes visible in updateTabs().
mRestoredTab = state.getInt(BUNDLE_KEY_CURRENT_TAB);
mRestoredPictureLoaded = state.getBoolean(BUNDLE_KEY_PICTURE_LOADED);
}
public void setCallback(Callback callback) {
mCallback = (callback == null) ? EmptyCallback.INSTANCE : callback;
}
private void cancelAllTasks() {
mMessageObserver.unregister();
mTaskTracker.cancellAllInterrupt();
}
protected final Controller getController() {
return mController;
}
protected final Callback getCallback() {
return mCallback;
}
public final Message getMessage() {
return mMessage;
}
protected final boolean isMessageOpen() {
return mMessage != null;
}
/**
* Returns the account id of the current message, or -1 if unknown (message not open yet, or
* viewing an EML message).
*/
public long getAccountId() {
return mAccountId;
}
/**
* Show/hide the content. We hide all the content (except for the bottom buttons) when loading,
* to avoid flicker.
*/
private void showContent(boolean showContent, boolean showProgressWhenHidden) {
makeVisible(mMainView, showContent);
makeVisible(mLoadingProgress, !showContent && showProgressWhenHidden);
}
+ // TODO: clean this up - most of this is not needed since the WebView and Fragment is not
+ // reused for multiple messages.
protected void resetView() {
showContent(false, false);
updateTabs(0);
setCurrentTab(TAB_MESSAGE);
if (mMessageContentView != null) {
blockNetworkLoads(true);
mMessageContentView.scrollTo(0, 0);
- mMessageContentView.clearView();
// Dynamic configuration of WebView
final WebSettings settings = mMessageContentView.getSettings();
settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
mMessageContentView.setInitialScale(getWebViewZoom());
}
mAttachmentsScroll.scrollTo(0, 0);
mInviteScroll.scrollTo(0, 0);
mAttachments.removeAllViews();
mAttachments.setVisibility(View.GONE);
initContactStatusViews();
}
/**
* Returns the zoom scale (in percent) which is a combination of the user setting
* (tiny, small, normal, large, huge) and the device density. The intention
* is for the text to be physically equal in size over different density
* screens.
*/
private int getWebViewZoom() {
float density = mContext.getResources().getDisplayMetrics().density;
int zoom = Preferences.getPreferences(mContext).getTextZoom();
return (int) (ZOOM_SCALE_ARRAY[zoom] * density * 100);
}
private void initContactStatusViews() {
mContactStatusState = CONTACT_STATUS_STATE_UNLOADED;
mQuickContactLookupUri = null;
showDefaultQuickContactBadgeImage();
}
private void showDefaultQuickContactBadgeImage() {
mFromBadge.setImageResource(R.drawable.ic_contact_picture);
}
protected final void addTabFlags(int tabFlags) {
updateTabs(mTabFlags | tabFlags);
}
private final void clearTabFlags(int tabFlags) {
updateTabs(mTabFlags & ~tabFlags);
}
private void setAttachmentCount(int count) {
mAttachmentCount = count;
if (mAttachmentCount > 0) {
addTabFlags(TAB_FLAGS_HAS_ATTACHMENT);
} else {
clearTabFlags(TAB_FLAGS_HAS_ATTACHMENT);
}
}
private static void makeVisible(View v, boolean visible) {
final int visibility = visible ? View.VISIBLE : View.GONE;
if ((v != null) && (v.getVisibility() != visibility)) {
v.setVisibility(visibility);
}
}
private static boolean isVisible(View v) {
return (v != null) && (v.getVisibility() == View.VISIBLE);
}
/**
* Update the visual of the tabs. (visibility, text, etc)
*/
private void updateTabs(int tabFlags) {
mTabFlags = tabFlags;
if (getView() == null) {
return;
}
boolean messageTabVisible = (tabFlags & (TAB_FLAGS_HAS_INVITE | TAB_FLAGS_HAS_ATTACHMENT))
!= 0;
makeVisible(mMessageTab, messageTabVisible);
makeVisible(mInviteTab, (tabFlags & TAB_FLAGS_HAS_INVITE) != 0);
makeVisible(mAttachmentTab, (tabFlags & TAB_FLAGS_HAS_ATTACHMENT) != 0);
final boolean hasPictures = (tabFlags & TAB_FLAGS_HAS_PICTURES) != 0;
final boolean pictureLoaded = (tabFlags & TAB_FLAGS_PICTURE_LOADED) != 0;
makeVisible(mShowPicturesTab, hasPictures && !pictureLoaded);
mAttachmentTab.setText(mContext.getResources().getQuantityString(
R.plurals.message_view_show_attachments_action,
mAttachmentCount, mAttachmentCount));
// Hide the entire section if no tabs are visible.
makeVisible(mTabSection, isVisible(mMessageTab) || isVisible(mInviteTab)
|| isVisible(mAttachmentTab) || isVisible(mShowPicturesTab)
|| isVisible(mAlwaysShowPicturesContainer));
// Restore previously selected tab after rotation
if (mRestoredTab != TAB_NONE && isVisible(getTabViewForFlag(mRestoredTab))) {
setCurrentTab(mRestoredTab);
mRestoredTab = TAB_NONE;
}
}
/**
* Set the current tab.
*
* @param tab any of {@link #TAB_MESSAGE}, {@link #TAB_ATTACHMENT} or {@link #TAB_INVITE}.
*/
private void setCurrentTab(int tab) {
mCurrentTab = tab;
// Hide & unselect all tabs
makeVisible(getTabContentViewForFlag(TAB_MESSAGE), false);
makeVisible(getTabContentViewForFlag(TAB_ATTACHMENT), false);
makeVisible(getTabContentViewForFlag(TAB_INVITE), false);
getTabViewForFlag(TAB_MESSAGE).setSelected(false);
getTabViewForFlag(TAB_ATTACHMENT).setSelected(false);
getTabViewForFlag(TAB_INVITE).setSelected(false);
makeVisible(getTabContentViewForFlag(mCurrentTab), true);
getTabViewForFlag(mCurrentTab).setSelected(true);
}
private View getTabViewForFlag(int tabFlag) {
switch (tabFlag) {
case TAB_MESSAGE:
return mMessageTab;
case TAB_ATTACHMENT:
return mAttachmentTab;
case TAB_INVITE:
return mInviteTab;
}
throw new IllegalArgumentException();
}
private View getTabContentViewForFlag(int tabFlag) {
switch (tabFlag) {
case TAB_MESSAGE:
return mMessageContentView;
case TAB_ATTACHMENT:
return mAttachmentsScroll;
case TAB_INVITE:
return mInviteScroll;
}
throw new IllegalArgumentException();
}
private void blockNetworkLoads(boolean block) {
if (mMessageContentView != null) {
mMessageContentView.getSettings().setBlockNetworkLoads(block);
}
}
private void setMessageHtml(String html) {
if (html == null) {
html = "";
}
if (mMessageContentView != null) {
mMessageContentView.loadDataWithBaseURL("email://", html, "text/html", "utf-8", null);
}
}
/**
* Handle clicks on sender, which shows {@link QuickContact} or prompts to add
* the sender as a contact.
*/
private void onClickSender() {
if (!isMessageOpen()) return;
final Address senderEmail = Address.unpackFirst(mMessage.mFrom);
if (senderEmail == null) return;
if (mContactStatusState == CONTACT_STATUS_STATE_UNLOADED) {
// Status not loaded yet.
mContactStatusState = CONTACT_STATUS_STATE_UNLOADED_TRIGGERED;
return;
}
if (mContactStatusState == CONTACT_STATUS_STATE_UNLOADED_TRIGGERED) {
return; // Already clicked, and waiting for the data.
}
if (mQuickContactLookupUri != null) {
QuickContact.showQuickContact(mContext, mFromBadge, mQuickContactLookupUri,
QuickContact.MODE_MEDIUM, null);
} else {
// No matching contact, ask user to create one
final Uri mailUri = Uri.fromParts("mailto", senderEmail.getAddress(), null);
final Intent intent = new Intent(ContactsContract.Intents.SHOW_OR_CREATE_CONTACT,
mailUri);
// Pass along full E-mail string for possible create dialog
intent.putExtra(ContactsContract.Intents.EXTRA_CREATE_DESCRIPTION,
senderEmail.toString());
// Only provide personal name hint if we have one
final String senderPersonal = senderEmail.getPersonal();
if (!TextUtils.isEmpty(senderPersonal)) {
intent.putExtra(ContactsContract.Intents.Insert.NAME, senderPersonal);
}
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(intent);
}
}
private static class ContactStatusLoaderCallbacks
implements LoaderCallbacks<ContactStatusLoader.Result> {
private static final String BUNDLE_EMAIL_ADDRESS = "email";
private final MessageViewFragmentBase mFragment;
public ContactStatusLoaderCallbacks(MessageViewFragmentBase fragment) {
mFragment = fragment;
}
public static Bundle createArguments(String emailAddress) {
Bundle b = new Bundle();
b.putString(BUNDLE_EMAIL_ADDRESS, emailAddress);
return b;
}
@Override
public Loader<ContactStatusLoader.Result> onCreateLoader(int id, Bundle args) {
return new ContactStatusLoader(mFragment.mContext,
args.getString(BUNDLE_EMAIL_ADDRESS));
}
@Override
public void onLoadFinished(Loader<ContactStatusLoader.Result> loader,
ContactStatusLoader.Result result) {
boolean triggered =
(mFragment.mContactStatusState == CONTACT_STATUS_STATE_UNLOADED_TRIGGERED);
mFragment.mContactStatusState = CONTACT_STATUS_STATE_LOADED;
mFragment.mQuickContactLookupUri = result.mLookupUri;
if (result.isUnknown()) {
mFragment.mSenderPresenceView.setVisibility(View.GONE);
} else {
mFragment.mSenderPresenceView.setVisibility(View.VISIBLE);
mFragment.mSenderPresenceView.setImageResource(result.mPresenceResId);
}
if (result.mPhoto != null) { // photo will be null if unknown.
mFragment.mFromBadge.setImageBitmap(result.mPhoto);
}
if (triggered) {
mFragment.onClickSender();
}
}
@Override
public void onLoaderReset(Loader<ContactStatusLoader.Result> loader) {
}
}
private void onSaveAttachment(MessageViewAttachmentInfo info) {
if (!Utility.isExternalStorageMounted()) {
/*
* Abort early if there's no place to save the attachment. We don't want to spend
* the time downloading it and then abort.
*/
Utility.showToast(getActivity(), R.string.message_view_status_attachment_not_saved);
return;
}
if (info.isFileSaved()) {
// Nothing to do - we have the file saved.
return;
}
File savedFile = performAttachmentSave(info);
if (savedFile != null) {
Utility.showToast(getActivity(), String.format(
mContext.getString(R.string.message_view_status_attachment_saved),
savedFile.getName()));
} else {
Utility.showToast(getActivity(), R.string.message_view_status_attachment_not_saved);
}
}
private File performAttachmentSave(MessageViewAttachmentInfo info) {
Attachment attachment = Attachment.restoreAttachmentWithId(mContext, info.mId);
Uri attachmentUri = AttachmentUtilities.getAttachmentUri(mAccountId, attachment.mId);
try {
File downloads = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS);
downloads.mkdirs();
File file = Utility.createUniqueFile(downloads, attachment.mFileName);
Uri contentUri = AttachmentUtilities.resolveAttachmentIdToContentUri(
mContext.getContentResolver(), attachmentUri);
InputStream in = mContext.getContentResolver().openInputStream(contentUri);
OutputStream out = new FileOutputStream(file);
IOUtils.copy(in, out);
out.flush();
out.close();
in.close();
String absolutePath = file.getAbsolutePath();
// Although the download manager can scan media files, scanning only happens after the
// user clicks on the item in the Downloads app. So, we run the attachment through
// the media scanner ourselves so it gets added to gallery / music immediately.
MediaScannerConnection.scanFile(mContext, new String[] {absolutePath},
null, null);
DownloadManager dm =
(DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
dm.addCompletedDownload(info.mName, info.mName,
false /* do not use media scanner */,
info.mContentType, absolutePath, info.mSize,
true /* show notification */);
// Cache the stored file information.
info.setSavedPath(absolutePath);
// Update our buttons.
updateAttachmentButtons(info);
return file;
} catch (IOException ioe) {
// Ignore. Callers will handle it from the return code.
}
return null;
}
private void onOpenAttachment(MessageViewAttachmentInfo info) {
if (info.mAllowInstall) {
// The package installer is unable to install files from a content URI; it must be
// given a file path. Therefore, we need to save it first in order to proceed
if (!info.mAllowSave || !Utility.isExternalStorageMounted()) {
Utility.showToast(getActivity(), R.string.message_view_status_attachment_not_saved);
return;
}
if (!info.isFileSaved()) {
if (performAttachmentSave(info) == null) {
// Saving failed for some reason - bail.
Utility.showToast(
getActivity(), R.string.message_view_status_attachment_not_saved);
return;
}
}
}
try {
Intent intent = info.getAttachmentIntent(mContext, mAccountId);
startActivity(intent);
} catch (ActivityNotFoundException e) {
Utility.showToast(getActivity(), R.string.message_view_display_attachment_toast);
}
}
private void onInfoAttachment(final MessageViewAttachmentInfo attachment) {
AttachmentInfoDialog dialog =
AttachmentInfoDialog.newInstance(getActivity(), attachment.mDenyFlags);
dialog.show(getActivity().getFragmentManager(), null);
}
private void onLoadAttachment(final MessageViewAttachmentInfo attachment) {
attachment.loadButton.setVisibility(View.GONE);
// If there's nothing in the download queue, we'll probably start right away so wait a
// second before showing the cancel button
if (AttachmentDownloadService.getQueueSize() == 0) {
// Set to invisible; if the button is still in this state one second from now, we'll
// assume the download won't start right away, and we make the cancel button visible
attachment.cancelButton.setVisibility(View.GONE);
// Create the timed task that will change the button state
new EmailAsyncTask<Void, Void, Void>(mTaskTracker) {
@Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(1000L);
} catch (InterruptedException e) { }
return null;
}
@Override
protected void onSuccess(Void result) {
// If the timeout completes and the attachment has not loaded, show cancel
if (!attachment.loaded) {
attachment.cancelButton.setVisibility(View.VISIBLE);
}
}
}.executeParallel();
} else {
attachment.cancelButton.setVisibility(View.VISIBLE);
}
attachment.showProgressIndeterminate();
mController.loadAttachment(attachment.mId, mMessageId, mAccountId);
}
private void onCancelAttachment(MessageViewAttachmentInfo attachment) {
// Don't change button states if we couldn't cancel the download
if (AttachmentDownloadService.cancelQueuedAttachment(attachment.mId)) {
attachment.loadButton.setVisibility(View.VISIBLE);
attachment.cancelButton.setVisibility(View.GONE);
attachment.hideProgress();
}
}
/**
* Called by ControllerResults. Show the "View" and "Save" buttons; hide "Load" and "Stop"
*
* @param attachmentId the attachment that was just downloaded
*/
private void doFinishLoadAttachment(long attachmentId) {
MessageViewAttachmentInfo info = findAttachmentInfo(attachmentId);
if (info != null) {
info.loaded = true;
updateAttachmentButtons(info);
}
}
private void showPicturesInHtml() {
boolean picturesAlreadyLoaded = (mTabFlags & TAB_FLAGS_PICTURE_LOADED) != 0;
if ((mMessageContentView != null) && !picturesAlreadyLoaded) {
blockNetworkLoads(false);
// TODO: why is this calling setMessageHtml just because the images can load now?
setMessageHtml(mHtmlTextWebView);
// Prompt the user to always show images from this sender.
makeVisible(UiUtilities.getView(getView(), R.id.always_show_pictures_container), true);
addTabFlags(TAB_FLAGS_PICTURE_LOADED);
}
}
private void showDetails() {
if (!isMessageOpen()) {
return;
}
if (!mDetailsFilled) {
String date = formatDate(mMessage.mTimeStamp, true);
final String SEPARATOR = "\n";
String to = Address.toString(Address.unpack(mMessage.mTo), SEPARATOR);
String cc = Address.toString(Address.unpack(mMessage.mCc), SEPARATOR);
String bcc = Address.toString(Address.unpack(mMessage.mBcc), SEPARATOR);
setDetailsRow(mDetailsExpanded, date, R.id.date, R.id.date_row);
setDetailsRow(mDetailsExpanded, to, R.id.to, R.id.to_row);
setDetailsRow(mDetailsExpanded, cc, R.id.cc, R.id.cc_row);
setDetailsRow(mDetailsExpanded, bcc, R.id.bcc, R.id.bcc_row);
mDetailsFilled = true;
}
mDetailsCollapsed.setVisibility(View.GONE);
mDetailsExpanded.setVisibility(View.VISIBLE);
}
private void hideDetails() {
mDetailsCollapsed.setVisibility(View.VISIBLE);
mDetailsExpanded.setVisibility(View.GONE);
}
private static void setDetailsRow(View root, String text, int textViewId, int rowViewId) {
if (TextUtils.isEmpty(text)) {
root.findViewById(rowViewId).setVisibility(View.GONE);
return;
}
((TextView) UiUtilities.getView(root, textViewId)).setText(text);
}
@Override
public void onClick(View view) {
if (!isMessageOpen()) {
return; // Ignore.
}
switch (view.getId()) {
case R.id.from_name:
case R.id.from_address:
case R.id.badge:
case R.id.presence:
onClickSender();
break;
case R.id.load:
onLoadAttachment((MessageViewAttachmentInfo) view.getTag());
break;
case R.id.info:
onInfoAttachment((MessageViewAttachmentInfo) view.getTag());
break;
case R.id.save:
onSaveAttachment((MessageViewAttachmentInfo) view.getTag());
break;
case R.id.open:
onOpenAttachment((MessageViewAttachmentInfo) view.getTag());
break;
case R.id.cancel:
onCancelAttachment((MessageViewAttachmentInfo) view.getTag());
break;
case R.id.show_message:
setCurrentTab(TAB_MESSAGE);
break;
case R.id.show_invite:
setCurrentTab(TAB_INVITE);
break;
case R.id.show_attachments:
setCurrentTab(TAB_ATTACHMENT);
break;
case R.id.show_pictures:
showPicturesInHtml();
break;
case R.id.always_show_pictures_button:
setShowImagesForSender();
break;
case R.id.sub_header_contents_collapsed:
showDetails();
break;
case R.id.sub_header_contents_expanded:
hideDetails();
break;
}
}
/**
* Start loading contact photo and presence.
*/
private void queryContactStatus() {
if (!isMessageOpen()) return;
initContactStatusViews(); // Initialize the state, just in case.
// Find the sender email address, and start presence check.
Address sender = Address.unpackFirst(mMessage.mFrom);
if (sender != null) {
String email = sender.getAddress();
if (email != null) {
getLoaderManager().restartLoader(PHOTO_LOADER_ID,
ContactStatusLoaderCallbacks.createArguments(email),
new ContactStatusLoaderCallbacks(this));
}
}
}
/**
* Called by {@link LoadMessageTask} and {@link ReloadMessageTask} to load a message in a
* subclass specific way.
*
* NOTE This method is called on a worker thread! Implementations must properly synchronize
* when accessing members.
*
* @param activity the parent activity. Subclass use it as a context, and to show a toast.
*/
protected abstract Message openMessageSync(Activity activity);
/**
* Called in a background thread to reload a new copy of the Message in case something has
* changed.
*/
protected Message reloadMessageSync(Activity activity) {
return openMessageSync(activity);
}
/**
* Async task for loading a single message outside of the UI thread
*/
private class LoadMessageTask extends EmailAsyncTask<Void, Void, Message> {
private final boolean mOkToFetch;
private Mailbox mMailbox;
/**
* Special constructor to cache some local info
*/
public LoadMessageTask(boolean okToFetch) {
super(mTaskTracker);
mOkToFetch = okToFetch;
}
@Override
protected Message doInBackground(Void... params) {
Activity activity = getActivity();
Message message = null;
if (activity != null) {
message = openMessageSync(activity);
}
if (message != null) {
mMailbox = Mailbox.restoreMailboxWithId(mContext, message.mMailboxKey);
if (mMailbox == null) {
message = null; // mailbox removed??
}
}
return message;
}
@Override
protected void onSuccess(Message message) {
if (message == null) {
resetView();
mCallback.onMessageNotExists();
return;
}
mMessageId = message.mId;
reloadUiFromMessage(message, mOkToFetch);
queryContactStatus();
onMessageShown(mMessageId, mMailbox);
RecentMailboxManager.getInstance(mContext).touch(mAccountId, message.mMailboxKey);
}
}
/**
* Kicked by {@link MessageObserver}. Reload the message and update the views.
*/
private class ReloadMessageTask extends EmailAsyncTask<Void, Void, Message> {
public ReloadMessageTask() {
super(mTaskTracker);
}
@Override
protected Message doInBackground(Void... params) {
Activity activity = getActivity();
if (activity == null) {
return null;
} else {
return reloadMessageSync(activity);
}
}
@Override
protected void onSuccess(Message message) {
if (message == null || message.mMailboxKey != mMessage.mMailboxKey) {
// Message deleted or moved.
mCallback.onMessageNotExists();
return;
}
mMessage = message;
updateHeaderView(mMessage);
}
}
/**
* Called when a message is shown to the user.
*/
protected void onMessageShown(long messageId, Mailbox mailbox) {
}
/**
* Called when the message body is loaded.
*/
protected void onPostLoadBody() {
}
/**
* Async task for loading a single message body outside of the UI thread
*/
private class LoadBodyTask extends EmailAsyncTask<Void, Void, String[]> {
private final long mId;
private boolean mErrorLoadingMessageBody;
private final boolean mAutoShowPictures;
/**
* Special constructor to cache some local info
*/
public LoadBodyTask(long messageId, boolean autoShowPictures) {
super(mTaskTracker);
mId = messageId;
mAutoShowPictures = autoShowPictures;
}
@Override
protected String[] doInBackground(Void... params) {
try {
String text = null;
String html = Body.restoreBodyHtmlWithMessageId(mContext, mId);
if (html == null) {
text = Body.restoreBodyTextWithMessageId(mContext, mId);
}
return new String[] { text, html };
} catch (RuntimeException re) {
// This catches SQLiteException as well as other RTE's we've seen from the
// database calls, such as IllegalStateException
Log.d(Logging.LOG_TAG, "Exception while loading message body", re);
mErrorLoadingMessageBody = true;
return null;
}
}
@Override
protected void onSuccess(String[] results) {
if (results == null) {
if (mErrorLoadingMessageBody) {
Utility.showToast(getActivity(), R.string.error_loading_message_body);
}
resetView();
return;
}
reloadUiFromBody(results[0], results[1], mAutoShowPictures); // text, html
onPostLoadBody();
}
}
/**
* Async task for loading attachments
*
* Note: This really should only be called when the message load is complete - or, we should
* leave open a listener so the attachments can fill in as they are discovered. In either case,
* this implementation is incomplete, as it will fail to refresh properly if the message is
* partially loaded at this time.
*/
private class LoadAttachmentsTask extends EmailAsyncTask<Long, Void, Attachment[]> {
public LoadAttachmentsTask() {
super(mTaskTracker);
}
@Override
protected Attachment[] doInBackground(Long... messageIds) {
return Attachment.restoreAttachmentsWithMessageId(mContext, messageIds[0]);
}
@Override
protected void onSuccess(Attachment[] attachments) {
try {
if (attachments == null) {
return;
}
boolean htmlChanged = false;
int numDisplayedAttachments = 0;
for (Attachment attachment : attachments) {
if (mHtmlTextRaw != null && attachment.mContentId != null
&& attachment.mContentUri != null) {
// for html body, replace CID for inline images
// Regexp which matches ' src="cid:contentId"'.
String contentIdRe =
"\\s+(?i)src=\"cid(?-i):\\Q" + attachment.mContentId + "\\E\"";
String srcContentUri = " src=\"" + attachment.mContentUri + "\"";
mHtmlTextRaw = mHtmlTextRaw.replaceAll(contentIdRe, srcContentUri);
htmlChanged = true;
} else {
addAttachment(attachment);
numDisplayedAttachments++;
}
}
setAttachmentCount(numDisplayedAttachments);
mHtmlTextWebView = mHtmlTextRaw;
mHtmlTextRaw = null;
if (htmlChanged) {
setMessageHtml(mHtmlTextWebView);
}
} finally {
showContent(true, false);
}
}
}
private static Bitmap getPreviewIcon(Context context, AttachmentInfo attachment) {
try {
return BitmapFactory.decodeStream(
context.getContentResolver().openInputStream(
AttachmentUtilities.getAttachmentThumbnailUri(
attachment.mAccountKey, attachment.mId,
PREVIEW_ICON_WIDTH,
PREVIEW_ICON_HEIGHT)));
} catch (Exception e) {
Log.d(Logging.LOG_TAG, "Attachment preview failed with exception " + e.getMessage());
return null;
}
}
/**
* Subclass of AttachmentInfo which includes our views and buttons related to attachment
* handling, as well as our determination of suitability for viewing (based on availability of
* a viewer app) and saving (based upon the presence of external storage)
*/
private static class MessageViewAttachmentInfo extends AttachmentInfo {
private Button openButton;
private Button saveButton;
private Button loadButton;
private Button infoButton;
private Button cancelButton;
private ImageView iconView;
private static final Map<AttachmentInfo, String> sSavedFileInfos = Maps.newHashMap();
// Don't touch it directly from the outer class.
private final ProgressBar mProgressView;
private boolean loaded;
private MessageViewAttachmentInfo(Context context, Attachment attachment,
ProgressBar progressView) {
super(context, attachment);
mProgressView = progressView;
}
/**
* Create a new attachment info based upon an existing attachment info. Display
* related fields (such as views and buttons) are copied from old to new.
*/
private MessageViewAttachmentInfo(Context context, MessageViewAttachmentInfo oldInfo) {
super(context, oldInfo);
openButton = oldInfo.openButton;
saveButton = oldInfo.saveButton;
loadButton = oldInfo.loadButton;
infoButton = oldInfo.infoButton;
cancelButton = oldInfo.cancelButton;
iconView = oldInfo.iconView;
mProgressView = oldInfo.mProgressView;
loaded = oldInfo.loaded;
}
public void hideProgress() {
// Don't use GONE, which'll break the layout.
if (mProgressView.getVisibility() != View.INVISIBLE) {
mProgressView.setVisibility(View.INVISIBLE);
}
}
public void showProgress(int progress) {
if (mProgressView.getVisibility() != View.VISIBLE) {
mProgressView.setVisibility(View.VISIBLE);
}
if (mProgressView.isIndeterminate()) {
mProgressView.setIndeterminate(false);
}
mProgressView.setProgress(progress);
}
public void showProgressIndeterminate() {
if (mProgressView.getVisibility() != View.VISIBLE) {
mProgressView.setVisibility(View.VISIBLE);
}
if (!mProgressView.isIndeterminate()) {
mProgressView.setIndeterminate(true);
}
}
/**
* Determines whether or not this attachment has a saved file in the external storage. That
* is, the user has at some point clicked "save" for this attachment.
*
* Note: this is an approximation and uses an in-memory cache that can get wiped when the
* process dies, and so is somewhat conservative. Additionally, the user can modify the file
* after saving, and so the file may not be the same (though this is unlikely).
*/
public boolean isFileSaved() {
String path = getSavedPath();
if (path == null) {
return false;
}
boolean savedFileExists = new File(path).exists();
if (!savedFileExists) {
// Purge the cache entry.
setSavedPath(null);
}
return savedFileExists;
}
private void setSavedPath(String path) {
if (path == null) {
sSavedFileInfos.remove(this);
} else {
sSavedFileInfos.put(this, path);
}
}
/**
* Returns an absolute file path for the given attachment if it has been saved. If one is
* not found, {@code null} is returned.
*
* Clients are expected to validate that the file at the given path is still valid.
*/
private String getSavedPath() {
return sSavedFileInfos.get(this);
}
@Override
protected Uri getUriForIntent(Context context, long accountId) {
// Prefer to act on the saved file for intents.
String path = getSavedPath();
return (path != null)
? Uri.parse("file://" + getSavedPath())
: super.getUriForIntent(context, accountId);
}
}
/**
* Updates all current attachments on the attachment tab.
*/
private void updateAttachmentTab() {
for (int i = 0, count = mAttachments.getChildCount(); i < count; i++) {
View view = mAttachments.getChildAt(i);
MessageViewAttachmentInfo oldInfo = (MessageViewAttachmentInfo)view.getTag();
MessageViewAttachmentInfo newInfo =
new MessageViewAttachmentInfo(getActivity(), oldInfo);
updateAttachmentButtons(newInfo);
view.setTag(newInfo);
}
}
/**
* Updates the attachment buttons. Adjusts the visibility of the buttons as well
* as updating any tag information associated with the buttons.
*/
private void updateAttachmentButtons(MessageViewAttachmentInfo attachmentInfo) {
ImageView attachmentIcon = attachmentInfo.iconView;
Button openButton = attachmentInfo.openButton;
Button saveButton = attachmentInfo.saveButton;
Button loadButton = attachmentInfo.loadButton;
Button infoButton = attachmentInfo.infoButton;
Button cancelButton = attachmentInfo.cancelButton;
if (!attachmentInfo.mAllowView) {
openButton.setVisibility(View.GONE);
}
if (!attachmentInfo.mAllowSave) {
saveButton.setVisibility(View.GONE);
}
if (!attachmentInfo.mAllowView && !attachmentInfo.mAllowSave) {
// This attachment may never be viewed or saved, so block everything
attachmentInfo.hideProgress();
openButton.setVisibility(View.GONE);
saveButton.setVisibility(View.GONE);
loadButton.setVisibility(View.GONE);
cancelButton.setVisibility(View.GONE);
infoButton.setVisibility(View.VISIBLE);
} else if (attachmentInfo.loaded) {
// If the attachment is loaded, show 100% progress
// Note that for POP3 messages, the user will only see "Open" and "Save",
// because the entire message is loaded before being shown.
// Hide "Load" and "Info", show "View" and "Save"
attachmentInfo.showProgress(100);
if (attachmentInfo.mAllowSave) {
saveButton.setVisibility(View.VISIBLE);
boolean isFileSaved = attachmentInfo.isFileSaved();
saveButton.setEnabled(!isFileSaved);
if (!isFileSaved) {
saveButton.setText(R.string.message_view_attachment_save_action);
} else {
saveButton.setText(R.string.message_view_attachment_saved);
}
}
if (attachmentInfo.mAllowView) {
// Set the attachment action button text accordingly
if (attachmentInfo.mContentType.startsWith("audio/") ||
attachmentInfo.mContentType.startsWith("video/")) {
openButton.setText(R.string.message_view_attachment_play_action);
} else if (attachmentInfo.mAllowInstall) {
openButton.setText(R.string.message_view_attachment_install_action);
} else {
openButton.setText(R.string.message_view_attachment_view_action);
}
openButton.setVisibility(View.VISIBLE);
}
if (attachmentInfo.mDenyFlags == AttachmentInfo.ALLOW) {
infoButton.setVisibility(View.GONE);
} else {
infoButton.setVisibility(View.VISIBLE);
}
loadButton.setVisibility(View.GONE);
cancelButton.setVisibility(View.GONE);
updatePreviewIcon(attachmentInfo);
} else {
// The attachment is not loaded, so present UI to start downloading it
// Show "Load"; hide "View", "Save" and "Info"
saveButton.setVisibility(View.GONE);
openButton.setVisibility(View.GONE);
infoButton.setVisibility(View.GONE);
// If the attachment is queued, show the indeterminate progress bar. From this point,.
// any progress changes will cause this to be replaced by the normal progress bar
if (AttachmentDownloadService.isAttachmentQueued(attachmentInfo.mId)) {
attachmentInfo.showProgressIndeterminate();
loadButton.setVisibility(View.GONE);
cancelButton.setVisibility(View.VISIBLE);
} else {
loadButton.setVisibility(View.VISIBLE);
cancelButton.setVisibility(View.GONE);
}
}
openButton.setTag(attachmentInfo);
saveButton.setTag(attachmentInfo);
loadButton.setTag(attachmentInfo);
infoButton.setTag(attachmentInfo);
cancelButton.setTag(attachmentInfo);
}
/**
* Copy data from a cursor-refreshed attachment into the UI. Called from UI thread.
*
* @param attachment A single attachment loaded from the provider
*/
private void addAttachment(Attachment attachment) {
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.message_view_attachment, null);
TextView attachmentName = (TextView) UiUtilities.getView(view, R.id.attachment_name);
TextView attachmentInfoView = (TextView) UiUtilities.getView(view, R.id.attachment_info);
ImageView attachmentIcon = (ImageView) UiUtilities.getView(view, R.id.attachment_icon);
Button openButton = (Button) UiUtilities.getView(view, R.id.open);
Button saveButton = (Button) UiUtilities.getView(view, R.id.save);
Button loadButton = (Button) UiUtilities.getView(view, R.id.load);
Button infoButton = (Button) UiUtilities.getView(view, R.id.info);
Button cancelButton = (Button) UiUtilities.getView(view, R.id.cancel);
ProgressBar attachmentProgress = (ProgressBar) UiUtilities.getView(view, R.id.progress);
MessageViewAttachmentInfo attachmentInfo = new MessageViewAttachmentInfo(
mContext, attachment, attachmentProgress);
// Check whether the attachment already exists
if (Utility.attachmentExists(mContext, attachment)) {
attachmentInfo.loaded = true;
}
attachmentInfo.openButton = openButton;
attachmentInfo.saveButton = saveButton;
attachmentInfo.loadButton = loadButton;
attachmentInfo.infoButton = infoButton;
attachmentInfo.cancelButton = cancelButton;
attachmentInfo.iconView = attachmentIcon;
updateAttachmentButtons(attachmentInfo);
view.setTag(attachmentInfo);
openButton.setOnClickListener(this);
saveButton.setOnClickListener(this);
loadButton.setOnClickListener(this);
infoButton.setOnClickListener(this);
cancelButton.setOnClickListener(this);
attachmentName.setText(attachmentInfo.mName);
attachmentInfoView.setText(UiUtilities.formatSize(mContext, attachmentInfo.mSize));
mAttachments.addView(view);
mAttachments.setVisibility(View.VISIBLE);
}
private MessageViewAttachmentInfo findAttachmentInfoFromView(long attachmentId) {
for (int i = 0, count = mAttachments.getChildCount(); i < count; i++) {
MessageViewAttachmentInfo attachmentInfo =
(MessageViewAttachmentInfo) mAttachments.getChildAt(i).getTag();
if (attachmentInfo.mId == attachmentId) {
return attachmentInfo;
}
}
return null;
}
/**
* Reload the UI from a provider cursor. {@link LoadMessageTask#onSuccess} calls it.
*
* Update the header views, and start loading the body.
*
* @param message A copy of the message loaded from the database
* @param okToFetch If true, and message is not fully loaded, it's OK to fetch from
* the network. Use false to prevent looping here.
*/
protected void reloadUiFromMessage(Message message, boolean okToFetch) {
mMessage = message;
mAccountId = message.mAccountKey;
mMessageObserver.register(ContentUris.withAppendedId(Message.CONTENT_URI, mMessage.mId));
updateHeaderView(mMessage);
// Handle partially-loaded email, as follows:
// 1. Check value of message.mFlagLoaded
// 2. If != LOADED, ask controller to load it
// 3. Controller callback (after loaded) should trigger LoadBodyTask & LoadAttachmentsTask
// 4. Else start the loader tasks right away (message already loaded)
if (okToFetch && message.mFlagLoaded != Message.FLAG_LOADED_COMPLETE) {
mControllerCallback.getWrappee().setWaitForLoadMessageId(message.mId);
mController.loadMessageForView(message.mId);
} else {
Address[] fromList = Address.unpack(mMessage.mFrom);
boolean autoShowImages = false;
for (Address sender : fromList) {
String email = sender.getAddress();
if (shouldShowImagesFor(email)) {
autoShowImages = true;
break;
}
}
mControllerCallback.getWrappee().setWaitForLoadMessageId(Message.NO_MESSAGE);
// Ask for body
new LoadBodyTask(message.mId, autoShowImages).executeParallel();
}
}
protected void updateHeaderView(Message message) {
mSubjectView.setText(message.mSubject);
final Address from = Address.unpackFirst(message.mFrom);
// Set sender address/display name
// Note we set " " for empty field, so TextView's won't get squashed.
// Otherwise their height will be 0, which breaks the layout.
if (from != null) {
final String fromFriendly = from.toFriendly();
final String fromAddress = from.getAddress();
mFromNameView.setText(fromFriendly);
mFromAddressView.setText(fromFriendly.equals(fromAddress) ? " " : fromAddress);
} else {
mFromNameView.setText(" ");
mFromAddressView.setText(" ");
}
mDateTimeView.setText(DateUtils.getRelativeTimeSpanString(mContext, message.mTimeStamp)
.toString());
// To/Cc/Bcc
final Resources res = mContext.getResources();
final SpannableStringBuilder ssb = new SpannableStringBuilder();
final String friendlyTo = Address.toFriendly(Address.unpack(message.mTo));
final String friendlyCc = Address.toFriendly(Address.unpack(message.mCc));
final String friendlyBcc = Address.toFriendly(Address.unpack(message.mBcc));
if (!TextUtils.isEmpty(friendlyTo)) {
Utility.appendBold(ssb, res.getString(R.string.message_view_to_label));
ssb.append(" ");
ssb.append(friendlyTo);
}
if (!TextUtils.isEmpty(friendlyCc)) {
ssb.append(" ");
Utility.appendBold(ssb, res.getString(R.string.message_view_cc_label));
ssb.append(" ");
ssb.append(friendlyCc);
}
if (!TextUtils.isEmpty(friendlyBcc)) {
ssb.append(" ");
Utility.appendBold(ssb, res.getString(R.string.message_view_bcc_label));
ssb.append(" ");
ssb.append(friendlyBcc);
}
mAddressesView.setText(ssb);
}
/**
* @return the given date/time in a human readable form. The returned string always have
* month and day (and year if {@code withYear} is set), so is usually long.
* Use {@link DateUtils#getRelativeTimeSpanString} instead to save the screen real estate.
*/
private String formatDate(long millis, boolean withYear) {
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb);
DateUtils.formatDateRange(mContext, formatter, millis, millis,
DateUtils.FORMAT_SHOW_DATE
| DateUtils.FORMAT_ABBREV_ALL
| DateUtils.FORMAT_SHOW_TIME
| (withYear ? DateUtils.FORMAT_SHOW_YEAR : DateUtils.FORMAT_NO_YEAR));
return sb.toString();
}
/**
* Reload the body from the provider cursor. This must only be called from the UI thread.
*
* @param bodyText text part
* @param bodyHtml html part
*
* TODO deal with html vs text and many other issues <- WHAT DOES IT MEAN??
*/
private void reloadUiFromBody(String bodyText, String bodyHtml, boolean autoShowPictures) {
String text = null;
mHtmlTextRaw = null;
boolean hasImages = false;
if (bodyHtml == null) {
text = bodyText;
/*
* Convert the plain text to HTML
*/
StringBuffer sb = new StringBuffer("<html><body>");
if (text != null) {
// Escape any inadvertent HTML in the text message
text = EmailHtmlUtil.escapeCharacterToDisplay(text);
// Find any embedded URL's and linkify
Matcher m = Patterns.WEB_URL.matcher(text);
while (m.find()) {
int start = m.start();
/*
* WEB_URL_PATTERN may match domain part of email address. To detect
* this false match, the character just before the matched string
* should not be '@'.
*/
if (start == 0 || text.charAt(start - 1) != '@') {
String url = m.group();
Matcher proto = WEB_URL_PROTOCOL.matcher(url);
String link;
if (proto.find()) {
// This is work around to force URL protocol part be lower case,
// because WebView could follow only lower case protocol link.
link = proto.group().toLowerCase() + url.substring(proto.end());
} else {
// Patterns.WEB_URL matches URL without protocol part,
// so added default protocol to link.
link = "http://" + url;
}
String href = String.format("<a href=\"%s\">%s</a>", link, url);
m.appendReplacement(sb, href);
}
else {
m.appendReplacement(sb, "$0");
}
}
m.appendTail(sb);
}
sb.append("</body></html>");
text = sb.toString();
} else {
text = bodyHtml;
mHtmlTextRaw = bodyHtml;
hasImages = IMG_TAG_START_REGEX.matcher(text).find();
}
// TODO this is not really accurate.
// - Images aren't the only network resources. (e.g. CSS)
// - If images are attached to the email and small enough, we download them at once,
// and won't need network access when they're shown.
if (hasImages) {
if (mRestoredPictureLoaded || autoShowPictures) {
blockNetworkLoads(false);
addTabFlags(TAB_FLAGS_PICTURE_LOADED); // Set for next onSaveInstanceState
// Make sure to reset the flag -- otherwise this will keep taking effect even after
// moving to another message.
mRestoredPictureLoaded = false;
} else {
addTabFlags(TAB_FLAGS_HAS_PICTURES);
}
}
setMessageHtml(text);
// Ask for attachments after body
new LoadAttachmentsTask().executeParallel(mMessage.mId);
mIsMessageLoadedForTest = true;
}
/**
* Overrides for WebView behaviors.
*/
private class CustomWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return mCallback.onUrlInMessageClicked(url);
}
}
private View findAttachmentView(long attachmentId) {
for (int i = 0, count = mAttachments.getChildCount(); i < count; i++) {
View view = mAttachments.getChildAt(i);
MessageViewAttachmentInfo attachment = (MessageViewAttachmentInfo) view.getTag();
if (attachment.mId == attachmentId) {
return view;
}
}
return null;
}
private MessageViewAttachmentInfo findAttachmentInfo(long attachmentId) {
View view = findAttachmentView(attachmentId);
if (view != null) {
return (MessageViewAttachmentInfo)view.getTag();
}
return null;
}
/**
* Controller results listener. We wrap it with {@link ControllerResultUiThreadWrapper},
* so all methods are called on the UI thread.
*/
private class ControllerResults extends Controller.Result {
private long mWaitForLoadMessageId;
public void setWaitForLoadMessageId(long messageId) {
mWaitForLoadMessageId = messageId;
}
@Override
public void loadMessageForViewCallback(MessagingException result, long accountId,
long messageId, int progress) {
if (messageId != mWaitForLoadMessageId) {
// We are not waiting for this message to load, so exit quickly
return;
}
if (result == null) {
switch (progress) {
case 0:
mCallback.onLoadMessageStarted();
// Loading from network -- show the progress icon.
showContent(false, true);
break;
case 100:
mWaitForLoadMessageId = -1;
mCallback.onLoadMessageFinished();
// reload UI and reload everything else too
// pass false to LoadMessageTask to prevent looping here
cancelAllTasks();
new LoadMessageTask(false).executeParallel();
break;
default:
// do nothing - we don't have a progress bar at this time
break;
}
} else {
mWaitForLoadMessageId = Message.NO_MESSAGE;
String error = mContext.getString(R.string.status_network_error);
mCallback.onLoadMessageError(error);
resetView();
}
}
@Override
public void loadAttachmentCallback(MessagingException result, long accountId,
long messageId, long attachmentId, int progress) {
if (messageId == mMessageId) {
if (result == null) {
showAttachmentProgress(attachmentId, progress);
switch (progress) {
case 100:
final MessageViewAttachmentInfo attachmentInfo =
findAttachmentInfoFromView(attachmentId);
if (attachmentInfo != null) {
updatePreviewIcon(attachmentInfo);
}
doFinishLoadAttachment(attachmentId);
break;
default:
// do nothing - we don't have a progress bar at this time
break;
}
} else {
MessageViewAttachmentInfo attachment = findAttachmentInfo(attachmentId);
if (attachment == null) {
// Called before LoadAttachmentsTask finishes.
// (Possible if you quickly close & re-open a message)
return;
}
attachment.cancelButton.setVisibility(View.GONE);
attachment.loadButton.setVisibility(View.VISIBLE);
attachment.hideProgress();
final String error;
if (result.getCause() instanceof IOException) {
error = mContext.getString(R.string.status_network_error);
} else {
error = mContext.getString(
R.string.message_view_load_attachment_failed_toast,
attachment.mName);
}
mCallback.onLoadMessageError(error);
}
}
}
private void showAttachmentProgress(long attachmentId, int progress) {
MessageViewAttachmentInfo attachment = findAttachmentInfo(attachmentId);
if (attachment != null) {
if (progress == 0) {
attachment.cancelButton.setVisibility(View.GONE);
}
attachment.showProgress(progress);
}
}
}
/**
* Class to detect update on the current message (e.g. toggle star). When it gets content
* change notifications, it kicks {@link ReloadMessageTask}.
*/
private class MessageObserver extends ContentObserver implements Runnable {
private final Throttle mThrottle;
private final ContentResolver mContentResolver;
private boolean mRegistered;
public MessageObserver(Handler handler, Context context) {
super(handler);
mContentResolver = context.getContentResolver();
mThrottle = new Throttle("MessageObserver", this, handler);
}
public void unregister() {
if (!mRegistered) {
return;
}
mThrottle.cancelScheduledCallback();
mContentResolver.unregisterContentObserver(this);
mRegistered = false;
}
public void register(Uri notifyUri) {
unregister();
mContentResolver.registerContentObserver(notifyUri, true, this);
mRegistered = true;
}
@Override
public boolean deliverSelfNotifications() {
return true;
}
@Override
public void onChange(boolean selfChange) {
if (mRegistered) {
mThrottle.onEvent();
}
}
/** This method is delay-called by {@link Throttle} on the UI thread. */
@Override
public void run() {
// This method is delay-called, so need to make sure if it's still registered.
if (mRegistered) {
new ReloadMessageTask().cancelPreviousAndExecuteParallel();
}
}
}
private void updatePreviewIcon(MessageViewAttachmentInfo attachmentInfo) {
new UpdatePreviewIconTask(attachmentInfo).executeParallel();
}
private class UpdatePreviewIconTask extends EmailAsyncTask<Void, Void, Bitmap> {
@SuppressWarnings("hiding")
private final Context mContext;
private final MessageViewAttachmentInfo mAttachmentInfo;
public UpdatePreviewIconTask(MessageViewAttachmentInfo attachmentInfo) {
super(mTaskTracker);
mContext = getActivity();
mAttachmentInfo = attachmentInfo;
}
@Override
protected Bitmap doInBackground(Void... params) {
return getPreviewIcon(mContext, mAttachmentInfo);
}
@Override
protected void onSuccess(Bitmap result) {
if (result == null) {
return;
}
mAttachmentInfo.iconView.setImageBitmap(result);
}
}
private boolean shouldShowImagesFor(String senderEmail) {
return Preferences.getPreferences(getActivity()).shouldShowImagesFor(senderEmail);
}
private void setShowImagesForSender() {
makeVisible(UiUtilities.getView(getView(), R.id.always_show_pictures_container), false);
Utility.showToast(getActivity(), R.string.message_view_always_show_pictures_confirmation);
// Force redraw of the container.
updateTabs(mTabFlags);
Address[] fromList = Address.unpack(mMessage.mFrom);
Preferences prefs = Preferences.getPreferences(getActivity());
for (Address sender : fromList) {
String email = sender.getAddress();
prefs.setSenderAsTrusted(email);
}
}
public boolean isMessageLoadedForTest() {
return mIsMessageLoadedForTest;
}
public void clearIsMessageLoadedForTest() {
mIsMessageLoadedForTest = true;
}
}
| false | false | null | null |
diff --git a/src/com/android/camera/ActivityBase.java b/src/com/android/camera/ActivityBase.java
index 1c89308a..e4243172 100644
--- a/src/com/android/camera/ActivityBase.java
+++ b/src/com/android/camera/ActivityBase.java
@@ -1,707 +1,707 @@
/*
* Copyright (C) 2009 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.camera;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.hardware.Camera.Parameters;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceGroup;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import com.android.camera.ui.LayoutChangeNotifier;
import com.android.camera.ui.PopupManager;
import com.android.gallery3d.app.AbstractGalleryActivity;
import com.android.gallery3d.app.AppBridge;
import com.android.gallery3d.app.GalleryActionBar;
import com.android.gallery3d.app.PhotoPage;
import com.android.gallery3d.common.ApiHelper;
import com.android.gallery3d.ui.ScreenNail;
import com.android.gallery3d.util.MediaSetUtils;
import java.io.File;
/**
* Superclass of camera activity.
*/
public abstract class ActivityBase extends AbstractGalleryActivity
implements LayoutChangeNotifier.Listener {
private static final String TAG = "ActivityBase";
private static final int CAMERA_APP_VIEW_TOGGLE_TIME = 100; // milliseconds
private static final String INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE =
"android.media.action.STILL_IMAGE_CAMERA_SECURE";
public static final String ACTION_IMAGE_CAPTURE_SECURE =
"android.media.action.IMAGE_CAPTURE_SECURE";
// The intent extra for camera from secure lock screen. True if the gallery
// should only show newly captured pictures. sSecureAlbumId does not
// increment. This is used when switching between camera, camcorder, and
// panorama. If the extra is not set, it is in the normal camera mode.
public static final String SECURE_CAMERA_EXTRA = "secure_camera";
private int mResultCodeForTesting;
private Intent mResultDataForTesting;
private OnScreenHint mStorageHint;
private View mSingleTapArea;
protected boolean mOpenCameraFail;
protected boolean mCameraDisabled;
protected CameraManager.CameraProxy mCameraDevice;
protected Parameters mParameters;
// The activity is paused. The classes that extend this class should set
// mPaused the first thing in onResume/onPause.
protected boolean mPaused;
protected GalleryActionBar mActionBar;
// Keep track of powershutter state
public static boolean mPowerShutter = false;
public static boolean mSmartCapture = false;
// Keep track of External Storage
public static boolean mStorageExternal;
public static boolean mNoExt = false;
public static boolean mStorageToggled = false;
// multiple cameras support
protected int mNumberOfCameras;
protected int mCameraId;
// The activity is going to switch to the specified camera id. This is
// needed because texture copy is done in GL thread. -1 means camera is not
// switching.
protected int mPendingSwitchCameraId = -1;
protected MyAppBridge mAppBridge;
protected ScreenNail mCameraScreenNail; // This shows camera preview.
// The view containing only camera related widgets like control panel,
// indicator bar, focus indicator and etc.
protected View mCameraAppView;
protected boolean mShowCameraAppView = true;
private Animation mCameraAppViewFadeIn;
private Animation mCameraAppViewFadeOut;
// Secure album id. This should be incremented every time the camera is
// launched from the secure lock screen. The id should be the same when
// switching between camera, camcorder, and panorama.
protected static int sSecureAlbumId;
// True if the camera is started from secure lock screen.
protected boolean mSecureCamera;
private static boolean sFirstStartAfterScreenOn = true;
private long mStorageSpace = Storage.LOW_STORAGE_THRESHOLD;
private static final int UPDATE_STORAGE_HINT = 0;
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UPDATE_STORAGE_HINT:
updateStorageHint();
return;
}
}
};
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_MEDIA_MOUNTED)
|| action.equals(Intent.ACTION_MEDIA_UNMOUNTED)
|| action.equals(Intent.ACTION_MEDIA_CHECKING)
|| action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) {
updateStorageSpaceAndHint();
}
}
};
// close activity when screen turns off
private BroadcastReceiver mScreenOffReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
finish();
}
};
private static BroadcastReceiver sScreenOffReceiver;
private static class ScreenOffReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
sFirstStartAfterScreenOn = true;
}
}
public static boolean isFirstStartAfterScreenOn() {
return sFirstStartAfterScreenOn;
}
public static void resetFirstStartAfterScreenOn() {
sFirstStartAfterScreenOn = false;
}
protected class CameraOpenThread extends Thread {
@Override
public void run() {
try {
mCameraDevice = Util.openCamera(ActivityBase.this, mCameraId);
mParameters = mCameraDevice.getParameters();
} catch (CameraHardwareException e) {
mOpenCameraFail = true;
} catch (CameraDisabledException e) {
mCameraDisabled = true;
}
}
}
@Override
public void onCreate(Bundle icicle) {
super.disableToggleStatusBar();
// Set a theme with action bar. It is not specified in manifest because
// we want to hide it by default. setTheme must happen before
// setContentView.
//
// This must be set before we call super.onCreate(), where the window's
// background is removed.
setTheme(R.style.Theme_Gallery);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
if (ApiHelper.HAS_ACTION_BAR) {
requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
} else {
requestWindowFeature(Window.FEATURE_NO_TITLE);
}
// Check if this is in the secure camera mode.
Intent intent = getIntent();
String action = intent.getAction();
if (INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE.equals(action)) {
mSecureCamera = true;
// Use a new album when this is started from the lock screen.
sSecureAlbumId++;
} else if (ACTION_IMAGE_CAPTURE_SECURE.equals(action)) {
mSecureCamera = true;
} else {
mSecureCamera = intent.getBooleanExtra(SECURE_CAMERA_EXTRA, false);
}
if (mSecureCamera) {
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
registerReceiver(mScreenOffReceiver, filter);
if (sScreenOffReceiver == null) {
sScreenOffReceiver = new ScreenOffReceiver();
getApplicationContext().registerReceiver(sScreenOffReceiver, filter);
}
}
super.onCreate(icicle);
}
public boolean isPanoramaActivity() {
return false;
}
protected void initPowerShutter(ComboPreferences prefs) {
prefs.setLocalId(getApplicationContext(), 0);
String val = prefs.getString(CameraSettings.KEY_POWER_SHUTTER,
getResources().getString(R.string.pref_camera_power_shutter_default));
mPowerShutter = val.equals(CameraSettings.VALUE_ON);
if (mPowerShutter && mShowCameraAppView) {
getWindow().addFlags(WindowManager.LayoutParams.PREVENT_POWER_KEY);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.PREVENT_POWER_KEY);
}
}
protected void initSmartCapture(ComboPreferences prefs) {
prefs.setLocalId(getApplicationContext(), 0);
String val = prefs.getString(CameraSettings.KEY_SMART_CAPTURE,
- getResources().getString(R.string.capital_off));
+ getResources().getString(R.string.setting_off_value));
mSmartCapture = val.equals(CameraSettings.VALUE_ON);
}
protected void initTrueView(ComboPreferences prefs) {
prefs.setLocalId(getApplicationContext(), 0);
String val = prefs.getString(CameraSettings.KEY_TRUE_VIEW,
- getResources().getString(R.string.capital_off));
+ getResources().getString(R.string.setting_off_value));
CameraScreenNail.mEnableAspectRatioClamping = val.equals(CameraSettings.VALUE_OFF);
}
protected SensorManager getSensorManager() {
return (SensorManager) getApplicationContext().getSystemService(Context.SENSOR_SERVICE);
}
// Initialize storage preferences
protected void initStoragePrefs(ComboPreferences prefs) {
prefs.setLocalId(getApplicationContext(), 0);
String val = prefs.getString(CameraSettings.KEY_STORAGE,
getResources().getString(R.string.pref_camera_storage_title_default));
mStorageToggled = ( mStorageExternal == val.equals(CameraSettings.VALUE_ON)) ? false : true;
mStorageExternal = val.equals(CameraSettings.VALUE_ON);
File extDCIM = new File(Storage.EXTMMC);
// Condition for External SD absence
if(extDCIM.exists()) mNoExt = false;
else {
mNoExt=true;
mStorageExternal = false;
}
}
@Override
protected void onResume() {
super.onResume();
installIntentFilter();
if (updateStorageHintOnResume()) {
updateStorageSpace();
mHandler.sendEmptyMessageDelayed(UPDATE_STORAGE_HINT, 200);
}
}
@Override
protected void onPause() {
super.onPause();
if (mStorageHint != null) {
mStorageHint.cancel();
mStorageHint = null;
}
unregisterReceiver(mReceiver);
}
@Override
public void setContentView(int layoutResID) {
super.setContentView(layoutResID);
// getActionBar() should be after setContentView
mActionBar = new GalleryActionBar(this);
mActionBar.hide();
}
@Override
public boolean onSearchRequested() {
return false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Prevent software keyboard or voice search from showing up.
if (keyCode == KeyEvent.KEYCODE_SEARCH
|| keyCode == KeyEvent.KEYCODE_MENU) {
if (event.isLongPress()) return true;
}
if (keyCode == KeyEvent.KEYCODE_MENU && mShowCameraAppView) {
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU && mShowCameraAppView) {
return true;
}
return super.onKeyUp(keyCode, event);
}
protected void setResultEx(int resultCode) {
mResultCodeForTesting = resultCode;
setResult(resultCode);
}
protected void setResultEx(int resultCode, Intent data) {
mResultCodeForTesting = resultCode;
mResultDataForTesting = data;
setResult(resultCode, data);
}
public int getResultCode() {
return mResultCodeForTesting;
}
public Intent getResultData() {
return mResultDataForTesting;
}
@Override
protected void onDestroy() {
PopupManager.removeInstance(this);
if (mSecureCamera) unregisterReceiver(mScreenOffReceiver);
super.onDestroy();
}
protected void installIntentFilter() {
// install an intent filter to receive SD card related events.
IntentFilter intentFilter =
new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING);
intentFilter.addDataScheme("file");
registerReceiver(mReceiver, intentFilter);
}
protected void updateStorageSpace() {
mStorageSpace = Storage.getAvailableSpace();
}
protected long getStorageSpace() {
return mStorageSpace;
}
protected void updateStorageSpaceAndHint() {
updateStorageSpace();
updateStorageHint(mStorageSpace);
}
protected void updateStorageHint() {
updateStorageHint(mStorageSpace);
}
protected boolean updateStorageHintOnResume() {
return true;
}
protected void updateStorageHint(long storageSpace) {
String message = null;
if (storageSpace == Storage.UNAVAILABLE) {
message = getString(R.string.no_storage);
} else if (storageSpace == Storage.PREPARING) {
message = getString(R.string.preparing_sd);
} else if (storageSpace == Storage.UNKNOWN_SIZE) {
message = getString(R.string.access_sd_fail);
} else if (storageSpace <= Storage.LOW_STORAGE_THRESHOLD) {
message = getString(R.string.spaceIsLow_content);
}
if (message != null) {
if (mStorageHint == null) {
mStorageHint = OnScreenHint.makeText(this, message);
} else {
mStorageHint.setText(message);
}
mStorageHint.show();
} else if (mStorageHint != null) {
mStorageHint.cancel();
mStorageHint = null;
}
}
protected void gotoGallery() {
// Move the next picture with capture animation. "1" means next.
mAppBridge.switchWithCaptureAnimation(1);
}
protected void recreateScreenNail() {
((CameraScreenNail) mCameraScreenNail).updateRenderSize();
notifyScreenNailChanged();
}
// Call this after setContentView.
public ScreenNail createCameraScreenNail(boolean getPictures) {
mCameraAppView = findViewById(R.id.camera_app_root);
Bundle data = new Bundle();
String path;
if (getPictures) {
if (mSecureCamera) {
path = "/secure/all/" + sSecureAlbumId;
} else {
path = "/local/all/" + Storage.generateBucketIdInt();
}
} else {
path = "/local/all/0"; // Use 0 so gallery does not show anything.
}
data.putString(PhotoPage.KEY_MEDIA_SET_PATH, path);
data.putString(PhotoPage.KEY_MEDIA_ITEM_PATH, path);
data.putBoolean(PhotoPage.KEY_SHOW_WHEN_LOCKED, mSecureCamera);
// Send an AppBridge to gallery to enable the camera preview.
if (mAppBridge != null) {
mCameraScreenNail.recycle();
}
mAppBridge = new MyAppBridge();
data.putParcelable(PhotoPage.KEY_APP_BRIDGE, mAppBridge);
if (getStateManager().getStateCount() == 0) {
getStateManager().startState(PhotoPage.class, data);
} else {
getStateManager().switchState(getStateManager().getTopState(),
PhotoPage.class, data);
}
mCameraScreenNail = mAppBridge.getCameraScreenNail();
return mCameraScreenNail;
}
// Call this after setContentView.
protected ScreenNail reuseCameraScreenNail(boolean getPictures) {
mCameraAppView = findViewById(R.id.camera_app_root);
Bundle data = new Bundle();
String path;
if (getPictures) {
if (mSecureCamera) {
path = "/secure/all/" + sSecureAlbumId;
} else {
path = "/local/all/" + Storage.generateBucketIdInt();
}
} else {
path = "/local/all/0"; // Use 0 so gallery does not show anything.
}
data.putString(PhotoPage.KEY_MEDIA_SET_PATH, path);
data.putString(PhotoPage.KEY_MEDIA_ITEM_PATH, path);
data.putBoolean(PhotoPage.KEY_SHOW_WHEN_LOCKED, mSecureCamera);
// Send an AppBridge to gallery to enable the camera preview.
if (mAppBridge == null) {
mAppBridge = new MyAppBridge();
}
data.putParcelable(PhotoPage.KEY_APP_BRIDGE, mAppBridge);
if (getStateManager().getStateCount() == 0) {
getStateManager().startState(PhotoPage.class, data);
}
mCameraScreenNail = mAppBridge.getCameraScreenNail();
return mCameraScreenNail;
}
private class HideCameraAppView implements Animation.AnimationListener {
@Override
public void onAnimationEnd(Animation animation) {
// We cannot set this as GONE because we want to receive the
// onLayoutChange() callback even when we are invisible.
mCameraAppView.setVisibility(View.INVISIBLE);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationStart(Animation animation) {
}
}
protected void updateCameraAppView() {
// Initialize the animation.
if (mCameraAppViewFadeIn == null) {
mCameraAppViewFadeIn = new AlphaAnimation(0f, 1f);
mCameraAppViewFadeIn.setDuration(CAMERA_APP_VIEW_TOGGLE_TIME);
mCameraAppViewFadeIn.setInterpolator(new DecelerateInterpolator());
mCameraAppViewFadeOut = new AlphaAnimation(1f, 0f);
mCameraAppViewFadeOut.setDuration(CAMERA_APP_VIEW_TOGGLE_TIME);
mCameraAppViewFadeOut.setInterpolator(new DecelerateInterpolator());
mCameraAppViewFadeOut.setAnimationListener(new HideCameraAppView());
}
if (mShowCameraAppView) {
mCameraAppView.setVisibility(View.VISIBLE);
// The "transparent region" is not recomputed when a sibling of
// SurfaceView changes visibility (unless it involves GONE). It's
// been broken since 1.0. Call requestLayout to work around it.
mCameraAppView.requestLayout();
mCameraAppView.startAnimation(mCameraAppViewFadeIn);
} else {
mCameraAppView.startAnimation(mCameraAppViewFadeOut);
}
}
protected void onFullScreenChanged(boolean full) {
if (mShowCameraAppView == full) return;
mShowCameraAppView = full;
if (mPaused || isFinishing()) return;
updateCameraAppView();
}
@Override
public GalleryActionBar getGalleryActionBar() {
return mActionBar;
}
// Preview frame layout has changed.
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom) {
if (mAppBridge == null) return;
int width = right - left;
int height = bottom - top;
if (ApiHelper.HAS_SURFACE_TEXTURE) {
CameraScreenNail screenNail = (CameraScreenNail) mCameraScreenNail;
if (Util.getDisplayRotation(this) % 180 == 0) {
screenNail.setPreviewFrameLayoutSize(width, height);
} else {
// Swap the width and height. Camera screen nail draw() is based on
// natural orientation, not the view system orientation.
screenNail.setPreviewFrameLayoutSize(height, width);
}
notifyScreenNailChanged();
}
}
protected void setSingleTapUpListener(View singleTapArea) {
mSingleTapArea = singleTapArea;
}
private boolean onSingleTapUp(int x, int y) {
// Ignore if listener is null or the camera control is invisible.
if (mSingleTapArea == null || !mShowCameraAppView) return false;
int[] relativeLocation = Util.getRelativeLocation((View) getGLRoot(),
mSingleTapArea);
x -= relativeLocation[0];
y -= relativeLocation[1];
if (x >= 0 && x < mSingleTapArea.getWidth() && y >= 0
&& y < mSingleTapArea.getHeight()) {
onSingleTapUp(mSingleTapArea, x, y);
return true;
}
return false;
}
protected void onSingleTapUp(View view, int x, int y) {
}
public void setSwipingEnabled(boolean enabled) {
mAppBridge.setSwipingEnabled(enabled);
}
public void notifyScreenNailChanged() {
mAppBridge.notifyScreenNailChanged();
}
protected void onPreviewTextureCopied() {
}
protected void onCaptureTextureCopied() {
}
protected void addSecureAlbumItemIfNeeded(boolean isVideo, Uri uri) {
if (mSecureCamera) {
int id = Integer.parseInt(uri.getLastPathSegment());
mAppBridge.addSecureAlbumItem(isVideo, id);
}
}
public boolean isSecureCamera() {
return mSecureCamera;
}
//////////////////////////////////////////////////////////////////////////
// The is the communication interface between the Camera Application and
// the Gallery PhotoPage.
//////////////////////////////////////////////////////////////////////////
class MyAppBridge extends AppBridge implements CameraScreenNail.Listener {
@SuppressWarnings("hiding")
private ScreenNail mCameraScreenNail;
private Server mServer;
@Override
public ScreenNail attachScreenNail() {
if (mCameraScreenNail == null) {
if (ApiHelper.HAS_SURFACE_TEXTURE) {
mCameraScreenNail = new CameraScreenNail(this);
} else {
Bitmap b = BitmapFactory.decodeResource(getResources(),
R.drawable.wallpaper_picker_preview);
mCameraScreenNail = new StaticBitmapScreenNail(b);
}
}
return mCameraScreenNail;
}
@Override
public void detachScreenNail() {
mCameraScreenNail = null;
}
public ScreenNail getCameraScreenNail() {
return mCameraScreenNail;
}
// Return true if the tap is consumed.
@Override
public boolean onSingleTapUp(int x, int y) {
return ActivityBase.this.onSingleTapUp(x, y);
}
// This is used to notify that the screen nail will be drawn in full screen
// or not in next draw() call.
@Override
public void onFullScreenChanged(boolean full) {
ActivityBase.this.onFullScreenChanged(full);
}
@Override
public void requestRender() {
getGLRoot().requestRenderForced();
}
@Override
public void onPreviewTextureCopied() {
ActivityBase.this.onPreviewTextureCopied();
}
@Override
public void onCaptureTextureCopied() {
ActivityBase.this.onCaptureTextureCopied();
}
@Override
public void setServer(Server s) {
mServer = s;
}
@Override
public boolean isPanorama() {
return ActivityBase.this.isPanoramaActivity();
}
@Override
public boolean isStaticCamera() {
return !ApiHelper.HAS_SURFACE_TEXTURE;
}
public void addSecureAlbumItem(boolean isVideo, int id) {
if (mServer != null) mServer.addSecureAlbumItem(isVideo, id);
}
private void setCameraRelativeFrame(Rect frame) {
if (mServer != null) mServer.setCameraRelativeFrame(frame);
}
private void switchWithCaptureAnimation(int offset) {
if (mServer != null) mServer.switchWithCaptureAnimation(offset);
}
private void setSwipingEnabled(boolean enabled) {
if (mServer != null) mServer.setSwipingEnabled(enabled);
}
private void notifyScreenNailChanged() {
if (mServer != null) mServer.notifyScreenNailChanged();
}
}
}
| false | false | null | null |
diff --git a/grails/src/persistence/org/codehaus/groovy/grails/orm/hibernate/cfg/GrailsDomainBinder.java b/grails/src/persistence/org/codehaus/groovy/grails/orm/hibernate/cfg/GrailsDomainBinder.java
index 57937d3e1..ee600024b 100644
--- a/grails/src/persistence/org/codehaus/groovy/grails/orm/hibernate/cfg/GrailsDomainBinder.java
+++ b/grails/src/persistence/org/codehaus/groovy/grails/orm/hibernate/cfg/GrailsDomainBinder.java
@@ -1,1989 +1,1989 @@
/* Copyright 2004-2005 the original author or authors.
*
* 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.codehaus.groovy.grails.orm.hibernate.cfg;
import groovy.lang.Closure;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.groovy.grails.commons.*;
import org.codehaus.groovy.grails.validation.ConstrainedProperty;
import org.hibernate.FetchMode;
import org.hibernate.MappingException;
import org.hibernate.cfg.ImprovedNamingStrategy;
import org.hibernate.cfg.Mappings;
import org.hibernate.cfg.NamingStrategy;
import org.hibernate.cfg.SecondPass;
import org.hibernate.id.PersistentIdentifierGenerator;
import org.hibernate.mapping.*;
import org.hibernate.mapping.Collection;
import org.hibernate.persister.entity.JoinedSubclassEntityPersister;
import org.hibernate.persister.entity.SingleTableEntityPersister;
import org.hibernate.usertype.UserType;
import org.hibernate.util.StringHelper;
import org.springframework.validation.Validator;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.util.*;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Handles the binding Grails domain classes and properties to the Hibernate runtime meta model.
* Based on the HbmBinder code in Hibernate core and influenced by AnnotationsBinder.
*
* @author Graeme Rocher
* @since 0.1
*
* Created: 06-Jul-2005
*/
public final class GrailsDomainBinder {
private static final String FOREIGN_KEY_SUFFIX = "_id";
private static final Log LOG = LogFactory.getLog( GrailsDomainBinder.class );
private static final NamingStrategy namingStrategy = ImprovedNamingStrategy.INSTANCE;
private static final String STRING_TYPE = "string";
private static final String EMPTY_PATH = "";
private static final char UNDERSCORE = '_';
private static final String CASCADE_ALL = "all";
private static final String CASCADE_SAVE_UPDATE = "save-update";
private static final String CASCADE_MERGE = "merge";
private static final String CASCADE_NONE = "none";
private static final String BACKTICK = "`";
private static final Map MAPPING_CACHE = new HashMap();
/**
* A Collection type, for the moment only Set is supported
*
* @author Graeme
*
*/
abstract static class CollectionType {
private Class clazz;
public abstract Collection create(GrailsDomainClassProperty property, PersistentClass owner,
String path, Mappings mappings) throws MappingException;
CollectionType(Class clazz) {
this.clazz = clazz;
}
public String toString() {
return clazz.getName();
}
private static CollectionType SET = new CollectionType(Set.class) {
public Collection create(GrailsDomainClassProperty property, PersistentClass owner, String path, Mappings mappings) throws MappingException {
org.hibernate.mapping.Set coll = new org.hibernate.mapping.Set(owner);
coll.setCollectionTable(owner.getTable());
bindCollection( property, coll, owner, mappings, path);
return coll;
}
};
private static CollectionType LIST = new CollectionType(List.class) {
public Collection create(GrailsDomainClassProperty property, PersistentClass owner, String path, Mappings mappings) throws MappingException {
org.hibernate.mapping.List coll = new org.hibernate.mapping.List(owner);
coll.setCollectionTable(owner.getTable());
bindCollection( property, coll, owner, mappings, path);
return coll;
}
};
private static CollectionType MAP = new CollectionType(Map.class) {
public Collection create(GrailsDomainClassProperty property, PersistentClass owner, String path, Mappings mappings) throws MappingException {
org.hibernate.mapping.Map map = new org.hibernate.mapping.Map(owner);
bindCollection(property, map, owner, mappings, path);
return map;
}
};
private static final Map INSTANCES = new HashMap();
static {
INSTANCES.put( Set.class, SET );
INSTANCES.put( SortedSet.class, SET );
INSTANCES.put( List.class, LIST );
INSTANCES.put( Map.class, MAP );
}
public static CollectionType collectionTypeForClass(Class clazz) {
return (CollectionType)INSTANCES.get( clazz );
}
}
/**
* Second pass class for grails relationships. This is required as all
* persistent classes need to be loaded in the first pass and then relationships
* established in the second pass compile
*
* @author Graeme
*
*/
static class GrailsCollectionSecondPass implements SecondPass {
protected static final long serialVersionUID = -5540526942092611348L;
protected GrailsDomainClassProperty property;
protected Mappings mappings;
protected Collection collection;
public GrailsCollectionSecondPass(GrailsDomainClassProperty property, Mappings mappings, Collection coll) {
this.property = property;
this.mappings = mappings;
this.collection = coll;
}
public void doSecondPass(Map persistentClasses, Map inheritedMetas) throws MappingException {
bindCollectionSecondPass( this.property, mappings, persistentClasses, collection,inheritedMetas );
createCollectionKeys();
}
private void createCollectionKeys() {
collection.createAllKeys();
if ( LOG.isDebugEnabled() ) {
String msg = "Mapped collection key: " + columns( collection.getKey() );
if ( collection.isIndexed() )
msg += ", index: " + columns( ( (IndexedCollection) collection ).getIndex() );
if ( collection.isOneToMany() ) {
msg += ", one-to-many: "
+ ( (OneToMany) collection.getElement() ).getReferencedEntityName();
}
else {
msg += ", element: " + columns( collection.getElement() );
}
LOG.debug( msg );
}
}
private static String columns(Value val) {
StringBuffer columns = new StringBuffer();
Iterator iter = val.getColumnIterator();
while ( iter.hasNext() ) {
columns.append( ( (Selectable) iter.next() ).getText() );
if ( iter.hasNext() ) columns.append( ", " );
}
return columns.toString();
}
public void doSecondPass(Map persistentClasses) throws MappingException {
bindCollectionSecondPass( this.property, mappings, persistentClasses, collection,Collections.EMPTY_MAP );
createCollectionKeys();
}
}
static class ListSecondPass extends GrailsCollectionSecondPass {
public ListSecondPass(GrailsDomainClassProperty property, Mappings mappings, Collection coll) {
super(property, mappings, coll);
}
public void doSecondPass(Map persistentClasses, Map inheritedMetas) throws MappingException {
bindListSecondPass(this.property, mappings, persistentClasses, (org.hibernate.mapping.List)collection, inheritedMetas);
}
public void doSecondPass(Map persistentClasses) throws MappingException {
bindListSecondPass(this.property, mappings, persistentClasses, (org.hibernate.mapping.List)collection, Collections.EMPTY_MAP);
}
}
static class MapSecondPass extends GrailsCollectionSecondPass {
public MapSecondPass(GrailsDomainClassProperty property, Mappings mappings, Collection coll) {
super(property, mappings, coll);
}
public void doSecondPass(Map persistentClasses, Map inheritedMetas) throws MappingException {
bindMapSecondPass( this.property, mappings, persistentClasses, (org.hibernate.mapping.Map)collection, inheritedMetas);
}
public void doSecondPass(Map persistentClasses) throws MappingException {
bindMapSecondPass( this.property, mappings, persistentClasses, (org.hibernate.mapping.Map)collection, Collections.EMPTY_MAP);
}
}
private static void bindMapSecondPass(GrailsDomainClassProperty property, Mappings mappings, Map persistentClasses, org.hibernate.mapping.Map map, Map inheritedMetas) {
bindCollectionSecondPass(property, mappings, persistentClasses, map, inheritedMetas);
String columnName = getColumnNameForPropertyAndPath(property, "");
SimpleValue value = new SimpleValue( map.getCollectionTable() );
bindSimpleValue(STRING_TYPE, value, true, columnName + UNDERSCORE + IndexedCollection.DEFAULT_INDEX_COLUMN_NAME,mappings);
if ( !value.isTypeSpecified() ) {
throw new MappingException( "map index element must specify a type: "
+ map.getRole() );
}
map.setIndex( value );
if(!property.isOneToMany()) {
SimpleValue elt = new SimpleValue( map.getCollectionTable() );
map.setElement( elt );
bindSimpleValue(STRING_TYPE, elt, false, columnName + UNDERSCORE + IndexedCollection.DEFAULT_ELEMENT_COLUMN_NAME,mappings);
elt.setTypeName(STRING_TYPE);
map.setInverse(false);
}
else {
if(property.isBidirectional())
map.setInverse(true);
else
map.setInverse(false);
}
}
private static void bindListSecondPass(GrailsDomainClassProperty property, Mappings mappings, Map persistentClasses, org.hibernate.mapping.List list, Map inheritedMetas) {
bindCollectionSecondPass( property, mappings, persistentClasses, list,inheritedMetas );
- String columnName = namingStrategy.propertyToColumnName(property.getName()+ UNDERSCORE +IndexedCollection.DEFAULT_INDEX_COLUMN_NAME);
+ String columnName = getColumnNameForPropertyAndPath(property, "")+ UNDERSCORE +IndexedCollection.DEFAULT_INDEX_COLUMN_NAME;
SimpleValue iv = new SimpleValue( list.getCollectionTable() );
bindSimpleValue("integer", iv, true,columnName, mappings);
iv.setTypeName( "integer" );
list.setIndex( iv );
list.setInverse(false);
if(property.isBidirectional()) {
String entityName;
Value element = list.getElement();
if(element instanceof ManyToOne) {
ManyToOne manyToOne = (ManyToOne) element;
entityName = manyToOne.getReferencedEntityName();
}
else {
entityName = ( (OneToMany) element).getReferencedEntityName();
}
PersistentClass referenced = mappings.getClass( entityName );
IndexBackref ib = new IndexBackref();
ib.setName( UNDERSCORE + property.getName() + "IndexBackref" );
ib.setUpdateable( false );
ib.setSelectable( false );
ib.setCollectionRole( list.getRole() );
ib.setEntityName( list.getOwner().getEntityName() );
ib.setValue( list.getIndex() );
referenced.addProperty( ib );
}
}
private static void bindCollectionSecondPass(GrailsDomainClassProperty property, Mappings mappings, Map persistentClasses, Collection collection, Map inheritedMetas) {
PersistentClass associatedClass = null;
if(LOG.isDebugEnabled())
LOG.debug( "Mapping collection: "
+ collection.getRole()
+ " -> "
+ collection.getCollectionTable().getName() );
ColumnConfig cc = getColumnConfig(property);
// Configure one-to-many
if(collection.isOneToMany() ) {
GrailsDomainClass referenced = property.getReferencedDomainClass();
if(referenced != null && !referenced.isRoot()) {
// NOTE: Work around for http://opensource.atlassian.com/projects/hibernate/browse/HHH-2855
collection.setWhere(RootClass.DEFAULT_DISCRIMINATOR_COLUMN_NAME + " = '"+referenced.getFullName()+"'");
}
OneToMany oneToMany = (OneToMany)collection.getElement();
String associatedClassName = oneToMany.getReferencedEntityName();
associatedClass = (PersistentClass)persistentClasses.get(associatedClassName);
// if there is no persistent class for the association throw
// exception
if(associatedClass == null) {
throw new MappingException( "Association references unmapped class: " + oneToMany.getReferencedEntityName() );
}
oneToMany.setAssociatedClass( associatedClass );
if(shouldBindCollectionWithForeignKey(property)) {
collection.setCollectionTable( associatedClass.getTable() );
}
bindCollectionForColumnConfig(collection, cc);
}
if(isSorted(property)) {
collection.setSorted(true);
}
// setup the primary key references
DependantValue key = createPrimaryKeyValue(property, collection,persistentClasses);
// link a bidirectional relationship
if(property.isBidirectional()) {
GrailsDomainClassProperty otherSide = property.getOtherSide();
if(otherSide.isManyToOne()) {
linkBidirectionalOneToMany(collection, associatedClass, key, otherSide);
}
else if(property.isManyToMany() /*&& property.isOwningSide()*/) {
bindDependentKeyValue(property,key,mappings);
}
}
else {
if(cc != null && cc.getJoinTable() != null && cc.getJoinTable().getKey() != null) {
bindSimpleValue("long", key,false, cc.getJoinTable().getKey(), mappings);
}
else {
bindDependentKeyValue(property,key,mappings);
}
}
collection.setKey( key );
// get cache config
if(cc != null) {
CacheConfig cacheConfig = cc.getCache();
if(cacheConfig != null) {
collection.setCacheConcurrencyStrategy(cacheConfig.getUsage());
}
}
// if we have a many-to-many
if(property.isManyToMany() ) {
GrailsDomainClassProperty otherSide = property.getOtherSide();
if(property.isBidirectional()) {
if(LOG.isDebugEnabled())
LOG.debug("[GrailsDomainBinder] Mapping other side "+otherSide.getDomainClass().getName()+"."+otherSide.getName()+" -> "+collection.getCollectionTable().getName()+" as ManyToOne");
ManyToOne element = new ManyToOne( collection.getCollectionTable() );
bindManyToMany(otherSide, element, mappings);
collection.setElement(element);
bindCollectionForColumnConfig(collection, cc);
}
else {
// TODO support unidirectional many-to-many
}
} else if (shouldCollectionBindWithJoinColumn(property)) {
bindCollectionWithJoinTable(property, mappings, collection, cc);
}
else if(isUnidirectionalOneToMany(property)) {
// for non-inverse one-to-many, with a not-null fk, add a backref!
// there are problems with list and map mappings and join columns relating to duplicate key constraints
// TODO change this when HHH-1268 is resolved
bindUnidirectionalOneToMany(property, mappings, collection);
}
}
private static void bindCollectionWithJoinTable(GrailsDomainClassProperty property, Mappings mappings, Collection collection, ColumnConfig cc) {
// for a normal unidirectional one-to-many we use a join column
ManyToOne element = new ManyToOne( collection.getCollectionTable() );
bindUnidirectionalOneToManyInverseValues(property, element);
collection.setInverse(false);
String columnName;
JoinTable jt = cc != null ? cc.getJoinTable() : null;
if(jt != null && jt.getKey()!=null) {
columnName = jt.getColumn();
}
else {
columnName = namingStrategy.propertyToColumnName(property.getReferencedDomainClass().getPropertyName()) + FOREIGN_KEY_SUFFIX;
}
bindSimpleValue("long", element,true, columnName, mappings);
collection.setElement(element);
bindCollectionForColumnConfig(collection, cc);
}
private static boolean shouldCollectionBindWithJoinColumn(GrailsDomainClassProperty property) {
return isUnidirectionalOneToMany(property);
}
/**
* @param property
* @param manyToOne
*/
private static void bindUnidirectionalOneToManyInverseValues(GrailsDomainClassProperty property, ManyToOne manyToOne) {
ColumnConfig cc = getColumnConfig(property);
if(cc != null) {
manyToOne.setLazy(cc.getLazy());
}
else {
manyToOne.setLazy(true);
}
// set referenced entity
manyToOne.setReferencedEntityName( property.getReferencedPropertyType().getName() );
manyToOne.setIgnoreNotFound(true);
}
private static void bindCollectionForColumnConfig(Collection collection, ColumnConfig cc) {
if(cc!=null) {
collection.setLazy(cc.getLazy());
}
else {
collection.setLazy(true);
}
}
private static ColumnConfig getColumnConfig(GrailsDomainClassProperty property) {
Mapping m = getMapping(property.getDomainClass().getFullName());
ColumnConfig cc = m != null ? m.getColumn(property.getName()) : null;
return cc;
}
/**
* Checks whether a property is a unidirectional non-circular one-to-many
* @param property The property to check
* @return True if it is unidirectional and a one-to-many
*/
private static boolean isUnidirectionalOneToMany(GrailsDomainClassProperty property) {
return property.isOneToMany() && !property.isBidirectional();
}
/**
* Binds the primary key value column
*
* @param property The property
* @param key The key
* @param mappings The mappings
*/
private static void bindDependentKeyValue(GrailsDomainClassProperty property, DependantValue key, Mappings mappings) {
if(LOG.isDebugEnabled())
LOG.debug("[GrailsDomainBinder] binding ["+property.getName()+"] with dependant key");
bindSimpleValue(property, key, EMPTY_PATH, mappings);
}
/**
* Creates the DependentValue object that forms a primary key reference for the collection
*
* @param property The grails property
* @param collection The collection object
* @param persistentClasses
* @return The DependantValue (key)
*/
private static DependantValue createPrimaryKeyValue(GrailsDomainClassProperty property, Collection collection, Map persistentClasses) {
KeyValue keyValue;
DependantValue key;
String propertyRef = collection.getReferencedPropertyName();
// this is to support mapping by a property
if(propertyRef == null) {
keyValue = collection.getOwner().getIdentifier();
}
else {
keyValue = (KeyValue)collection.getOwner().getProperty( propertyRef ).getValue();
}
if(LOG.isDebugEnabled())
LOG.debug( "[GrailsDomainBinder] creating dependant key value to table ["+keyValue.getTable().getName()+"]");
key = new DependantValue(collection.getCollectionTable(), keyValue);
key.setTypeName(null);
// make nullable and non-updateable
key.setNullable(true);
key.setUpdateable(false);
return key;
}
/**
* Binds a unidirectional one-to-many creating a psuedo back reference property in the process.
*
* @param property
* @param mappings
* @param collection
*/
private static void bindUnidirectionalOneToMany(GrailsDomainClassProperty property, Mappings mappings, Collection collection) {
Value v = collection.getElement();
v.createForeignKey();
String entityName;
if(v instanceof ManyToOne) {
ManyToOne manyToOne = (ManyToOne) v;
entityName = manyToOne.getReferencedEntityName();
}
else {
entityName = ((OneToMany)v).getReferencedEntityName();
}
collection.setInverse(false);
PersistentClass referenced = mappings.getClass( entityName );
Backref prop = new Backref();
prop.setEntityName(property.getDomainClass().getFullName());
prop.setName(UNDERSCORE + property.getDomainClass().getShortName() + UNDERSCORE + property.getName() + "Backref" );
prop.setUpdateable( false );
prop.setInsertable( true );
prop.setCollectionRole( collection.getRole() );
prop.setValue( collection.getKey() );
prop.setOptional( true );
referenced.addProperty( prop );
}
private static Property getProperty(PersistentClass associatedClass,
String propertyName)
throws MappingException {
try {
return associatedClass.getProperty(propertyName);
} catch (MappingException e) {
//maybe it's squirreled away in a composite primary key
if (associatedClass.getKey() instanceof Component) {
return ((Component)associatedClass.getKey()).getProperty(propertyName);
} else {
throw e;
}
}
}
/**
* Links a bidirectional one-to-many, configuring the inverse side and using a column copy to perform the link
*
* @param collection The collection one-to-many
* @param associatedClass The associated class
* @param key The key
* @param otherSide The other side of the relationship
*/
private static void linkBidirectionalOneToMany(Collection collection, PersistentClass associatedClass, DependantValue key, GrailsDomainClassProperty otherSide) {
collection.setInverse(true);
// Iterator mappedByColumns = associatedClass.getProperty( otherSide.getName() ).getValue().getColumnIterator();
Iterator mappedByColumns = getProperty(associatedClass, otherSide.getName())
.getValue().getColumnIterator();
while(mappedByColumns.hasNext()) {
Column column = (Column)mappedByColumns.next();
linkValueUsingAColumnCopy(otherSide,column,key);
}
}
/**
* Establish whether a collection property is sorted
* @param property The property
* @return True if sorted
*/
private static boolean isSorted(GrailsDomainClassProperty property) {
return SortedSet.class.isAssignableFrom(property.getType());
}
/**
* Binds a many-to-many relationship. A many-to-many consists of
* - a key (a DependentValue)
* - an element
*
* The element is a ManyToOne from the association table to the target entity
*
* @param property The grails property
* @param element The ManyToOne element
* @param mappings The mappings
*/
private static void bindManyToMany(GrailsDomainClassProperty property, ManyToOne element, Mappings mappings) {
bindManyToOne(property,element, EMPTY_PATH, mappings);
element.setReferencedEntityName(property.getDomainClass().getFullName());
}
private static void linkValueUsingAColumnCopy(GrailsDomainClassProperty prop, Column column, DependantValue key) {
Column mappingColumn = new Column();
mappingColumn.setName(column.getName());
mappingColumn.setLength(column.getLength());
mappingColumn.setNullable(prop.isOptional());
mappingColumn.setSqlType(column.getSqlType());
mappingColumn.setValue(key);
key.addColumn( mappingColumn );
key.getTable().addColumn( mappingColumn );
}
/**
* First pass to bind collection to Hibernate metamodel, sets up second pass
*
* @param property The GrailsDomainClassProperty instance
* @param collection The collection
* @param owner The owning persistent class
* @param mappings The Hibernate mappings instance
* @param path
*/
private static void bindCollection(GrailsDomainClassProperty property, Collection collection, PersistentClass owner, Mappings mappings, String path) {
// set role
String propertyName = getNameForPropertyAndPath(property, path);
collection.setRole( StringHelper.qualify( property.getDomainClass().getFullName() , propertyName ) );
// configure eager fetching
if(property.getFetchMode() == GrailsDomainClassProperty.FETCH_EAGER) {
collection.setFetchMode(FetchMode.JOIN);
}
else {
collection.setFetchMode( FetchMode.DEFAULT );
}
// if its a one-to-many mapping
if(shouldBindCollectionWithForeignKey(property)) {
OneToMany oneToMany = new OneToMany( collection.getOwner() );
collection.setElement( oneToMany );
bindOneToMany( property, oneToMany, mappings );
}
else {
bindCollectionTable(property, mappings, collection);
if(!property.isOwningSide()) {
collection.setInverse(true);
}
}
// setup second pass
if(collection instanceof org.hibernate.mapping.Set)
mappings.addSecondPass( new GrailsCollectionSecondPass(property, mappings, collection) );
else if(collection instanceof org.hibernate.mapping.List) {
mappings.addSecondPass( new ListSecondPass(property, mappings, collection) );
}
else if(collection instanceof org.hibernate.mapping.Map) {
mappings.addSecondPass( new MapSecondPass(property, mappings, collection));
}
}
/*
* We bind collections with foreign keys if specified in the mapping and only if it is a unidirectional one-to-many
* that is
*/
private static boolean shouldBindCollectionWithForeignKey(GrailsDomainClassProperty property) {
return (property.isOneToMany() && property.isBidirectional() ||
!shouldCollectionBindWithJoinColumn(property)) && !Map.class.isAssignableFrom(property.getType()) && !property.isManyToMany();
}
private static boolean isListOrMapCollection(GrailsDomainClassProperty property) {
return Map.class.isAssignableFrom(property.getType()) || List.class.isAssignableFrom(property.getType());
}
private static String getNameForPropertyAndPath(GrailsDomainClassProperty property, String path) {
String propertyName;
if(StringHelper.isNotEmpty(path)) {
propertyName = StringHelper.qualify(path, property.getName());
}
else {
propertyName = property.getName();
}
return propertyName;
}
private static void bindCollectionTable(GrailsDomainClassProperty property, Mappings mappings, Collection collection) {
String tableName = calculateTableForMany(property);
Table t = mappings.addTable(
mappings.getSchemaName(),
mappings.getCatalogName(),
tableName,
null,
false
);
collection.setCollectionTable(t);
}
/**
* This method will calculate the mapping table for a many-to-many. One side of
* the relationship has to "own" the relationship so that there is not a situation
* where you have two mapping tables for left_right and right_left
*/
private static String calculateTableForMany(GrailsDomainClassProperty property) {
if(Map.class.isAssignableFrom(property.getType())) {
String tablePrefix = getTableName(property.getDomainClass());
return tablePrefix + "_" + namingStrategy.propertyToColumnName(property.getName());
}
else {
ColumnConfig cc = getColumnConfig(property);
JoinTable jt = cc != null ? cc.getJoinTable() : null;
if(property.isManyToMany() && jt != null && jt.getName()!=null) {
return jt.getName();
}
else {
String left = getTableName(property.getDomainClass());
String right = getTableName(property.getReferencedDomainClass());
if(property.isOwningSide()) {
return left+ UNDERSCORE +right;
}
else if(shouldCollectionBindWithJoinColumn(property)) {
if(jt != null && jt.getName() != null) {
return jt.getName();
}
left = trimBackTigs(left);
right = trimBackTigs(right);
return left+ UNDERSCORE +right;
}
else {
return right+ UNDERSCORE +left;
}
}
}
}
private static String trimBackTigs(String tableName) {
if(tableName.startsWith(BACKTICK)) return tableName.substring(1, tableName.length()-1);
return tableName;
}
/**
* Evaluates the table name for the given property
*
* @param domainClass The domain class to evaluate
* @return The table name
*/
private static String getTableName(GrailsDomainClass domainClass) {
Mapping m = getMapping(domainClass.getFullName());
String tableName = null;
if(m != null && m.getTableName() != null) {
tableName = m.getTableName();
}
if(tableName == null) {
tableName = namingStrategy.classToTableName(domainClass.getShortName());
}
return tableName;
}
/**
* Binds a Grails domain class to the Hibernate runtime meta model
* @param domainClass The domain class to bind
* @param mappings The existing mappings
* @throws MappingException Thrown if the domain class uses inheritance which is not supported
*/
public static void bindClass(GrailsDomainClass domainClass, Mappings mappings)
throws MappingException {
//if(domainClass.getClazz().getSuperclass() == java.lang.Object.class) {
if(domainClass.isRoot()) {
evaluateMapping(domainClass);
bindRoot(domainClass, mappings);
}
//}
//else {
// throw new MappingException("Grails domain classes do not support inheritance");
//}
}
/**
* Evaluates a Mapping object from the domain class if it has a mapping closure
*
* @param domainClass The domain class
*/
private static void evaluateMapping(GrailsDomainClass domainClass) {
Object o = domainClass.getPropertyValue(GrailsDomainClassProperty.MAPPING);
if(o instanceof Closure) {
HibernateMappingBuilder builder = new HibernateMappingBuilder(domainClass.getFullName());
Mapping m = builder.evaluate((Closure)o);
MAPPING_CACHE.put(domainClass.getFullName(), m);
}
}
/**
* Obtains a mapping object for the given domain class nam
* @param domainClassName The domain class name in question
* @return A Mapping object or null
*/
public static Mapping getMapping(String domainClassName) {
return (Mapping)MAPPING_CACHE.get(domainClassName);
}
/**
* Binds the specified persistant class to the runtime model based on the
* properties defined in the domain class
* @param domainClass The Grails domain class
* @param persistentClass The persistant class
* @param mappings Existing mappings
*/
private static void bindClass(GrailsDomainClass domainClass, PersistentClass persistentClass, Mappings mappings) {
// set lazy loading for now
persistentClass.setLazy(true);
persistentClass.setEntityName(domainClass.getFullName());
persistentClass.setProxyInterfaceName( domainClass.getFullName() );
persistentClass.setClassName(domainClass.getFullName());
// set dynamic insert to false
persistentClass.setDynamicInsert(false);
// set dynamic update to false
persistentClass.setDynamicUpdate(false);
// set select before update to false
persistentClass.setSelectBeforeUpdate(false);
// add import to mappings
if ( mappings.isAutoImport() && persistentClass.getEntityName().indexOf( '.' ) > 0 ) {
mappings.addImport( persistentClass.getEntityName(), StringHelper.unqualify( persistentClass
.getEntityName() ) );
}
}
/**
* Binds a root class (one with no super classes) to the runtime meta model
* based on the supplied Grails domain class
*
* @param domainClass The Grails domain class
* @param mappings The Hibernate Mappings object
*/
public static void bindRoot(GrailsDomainClass domainClass, Mappings mappings) {
if(mappings.getClass(domainClass.getFullName()) == null) {
RootClass root = new RootClass();
bindClass(domainClass, root, mappings);
Mapping m = getMapping(domainClass.getName());
if(m!=null) {
CacheConfig cc = m.getCache();
if(cc != null && cc.getEnabled()) {
root.setCacheConcurrencyStrategy(cc.getUsage());
root.setLazyPropertiesCacheable(!"non-lazy".equals(cc.getInclude()));
}
}
bindRootPersistentClassCommonValues(domainClass, root, mappings);
if(!domainClass.getSubClasses().isEmpty()) {
boolean tablePerHierarchy = m == null || m.getTablePerHierarchy();
if(tablePerHierarchy) {
// if the root class has children create a discriminator property
bindDiscriminatorProperty(root.getTable(), root, mappings);
}
// bind the sub classes
bindSubClasses(domainClass,root,mappings);
}
mappings.addClass(root);
}
else {
LOG.info("[GrailsDomainBinder] Class ["+domainClass.getFullName()+"] is already mapped, skipping.. ");
}
}
/**
* Binds the sub classes of a root class using table-per-heirarchy inheritance mapping
*
* @param domainClass The root domain class to bind
* @param parent The parent class instance
* @param mappings The mappings instance
*/
private static void bindSubClasses(GrailsDomainClass domainClass, PersistentClass parent, Mappings mappings) {
Set subClasses = domainClass.getSubClasses();
for (Iterator i = subClasses.iterator(); i.hasNext();) {
GrailsDomainClass sub = (GrailsDomainClass) i.next();
Set subSubs = sub.getSubClasses();
if(sub.getClazz().getSuperclass().equals(domainClass.getClazz())) {
bindSubClass(sub,parent,mappings);
}
}
}
/**
* Binds a sub class
*
* @param sub The sub domain class instance
* @param parent The parent persistent class instance
* @param mappings The mappings instance
*/
private static void bindSubClass(GrailsDomainClass sub, PersistentClass parent, Mappings mappings) {
Mapping m = getMapping(parent.getClassName());
Subclass subClass;
boolean tablePerSubclass = m != null && !m.getTablePerHierarchy();
if(tablePerSubclass) {
subClass = new JoinedSubclass(parent);
}
else {
subClass = new SingleTableSubclass(parent);
// set the descriminator value as the name of the class. This is the
// value used by Hibernate to decide what the type of the class is
// to perform polymorphic queries
subClass.setDiscriminatorValue(sub.getFullName());
}
subClass.setEntityName(sub.getFullName());
parent.addSubclass( subClass );
mappings.addClass( subClass );
if(tablePerSubclass)
bindJoinedSubClass(sub, (JoinedSubclass)subClass, mappings, m);
else
bindSubClass(sub,subClass,mappings);
if(!sub.getSubClasses().isEmpty()) {
// bind the sub classes
bindSubClasses(sub,subClass,mappings);
}
}
/**
* Binds a joined sub-class mapping using table-per-subclass
* @param sub The Grails sub class
* @param joinedSubclass The Hibernate Subclass object
* @param mappings The mappings Object
* @param gormMapping The GORM mapping object
*/
private static void bindJoinedSubClass(GrailsDomainClass sub, JoinedSubclass joinedSubclass, Mappings mappings, Mapping gormMapping) {
bindClass( sub, joinedSubclass, mappings );
if ( joinedSubclass.getEntityPersisterClass() == null ) {
joinedSubclass.getRootClass()
.setEntityPersisterClass( JoinedSubclassEntityPersister.class );
}
Table mytable = mappings.addTable(
mappings.getSchemaName(),
mappings.getCatalogName(),
getJoinedSubClassTableName( sub,joinedSubclass, null, mappings ),
null,
false
);
joinedSubclass.setTable( mytable );
LOG.info(
"Mapping joined-subclass: " + joinedSubclass.getEntityName() +
" -> " + joinedSubclass.getTable().getName()
);
SimpleValue key = new DependantValue( mytable, joinedSubclass.getIdentifier() );
joinedSubclass.setKey( key );
String columnName = namingStrategy.propertyToColumnName(sub.getIdentifier().getName());
bindSimpleValue( sub.getIdentifier().getType().getName(), key, false, columnName, mappings );
joinedSubclass.createPrimaryKey();
// properties
createClassProperties( sub, joinedSubclass, mappings);
}
private static String getJoinedSubClassTableName(
GrailsDomainClass sub, PersistentClass model, Table denormalizedSuperTable,
Mappings mappings
) {
String logicalTableName = StringHelper.unqualify( model.getEntityName() );
String physicalTableName = getTableName(sub);
mappings.addTableBinding( mappings.getSchemaName(), mappings.getCatalogName(), logicalTableName, physicalTableName, denormalizedSuperTable );
return physicalTableName;
}
/**
* Binds a sub-class using table-per-heirarchy in heritance mapping
*
* @param sub The Grails domain class instance representing the sub-class
* @param subClass The Hibernate SubClass instance
* @param mappings The mappings instance
*/
private static void bindSubClass(GrailsDomainClass sub, Subclass subClass, Mappings mappings) {
bindClass( sub, subClass, mappings );
if ( subClass.getEntityPersisterClass() == null ) {
subClass.getRootClass()
.setEntityPersisterClass( SingleTableEntityPersister.class );
}
if(LOG.isDebugEnabled())
LOG.debug(
"Mapping subclass: " + subClass.getEntityName() +
" -> " + subClass.getTable().getName()
);
// properties
createClassProperties( sub, subClass, mappings);
}
/**
* Creates and binds the discriminator property used in table-per-heirarchy inheritance to
* discriminate between sub class instances
*
* @param table The table to bind onto
* @param entity The root class entity
* @param mappings The mappings instance
*/
private static void bindDiscriminatorProperty(Table table, RootClass entity, Mappings mappings) {
SimpleValue d = new SimpleValue( table );
entity.setDiscriminator( d );
entity.setDiscriminatorValue(entity.getClassName());
bindSimpleValue(
STRING_TYPE,
d,
false,
RootClass.DEFAULT_DISCRIMINATOR_COLUMN_NAME,
mappings
);
entity.setPolymorphic( true );
}
/**
* Binds a persistent classes to the table representation and binds the class properties
*
* @param domainClass
* @param root
* @param mappings
*/
private static void bindRootPersistentClassCommonValues(GrailsDomainClass domainClass, RootClass root, Mappings mappings) {
// get the schema and catalog names from the configuration
String schema = mappings.getSchemaName();
String catalog = mappings.getCatalogName();
// create the table
Table table = mappings.addTable(
schema,
catalog,
getTableName(domainClass),
null,
false
);
root.setTable(table);
if(LOG.isDebugEnabled())
LOG.debug( "[GrailsDomainBinder] Mapping Grails domain class: " + domainClass.getFullName() + " -> " + root.getTable().getName() );
Mapping m = getMapping(domainClass.getFullName());
bindIdentity(domainClass, root, mappings, m);
if(m != null) {
if(m.getVersioned()) {
bindVersion( domainClass.getVersion(), root, mappings );
}
}
else
bindVersion( domainClass.getVersion(), root, mappings );
root.createPrimaryKey();
createClassProperties(domainClass,root,mappings);
}
private static void bindIdentity(GrailsDomainClass domainClass, RootClass root, Mappings mappings, Mapping gormMapping) {
if(gormMapping != null) {
Object id = gormMapping.getIdentity();
if(id instanceof CompositeIdentity){
bindCompositeId(domainClass, root, (CompositeIdentity)id, gormMapping, mappings);
}
else {
bindSimpleId( domainClass.getIdentifier(), root, mappings, (Identity)id );
}
}
else {
bindSimpleId( domainClass.getIdentifier(), root, mappings, null);
}
}
private static void bindCompositeId(GrailsDomainClass domainClass, RootClass root, CompositeIdentity compositeIdentity, Mapping gormMapping, Mappings mappings) {
Component id = new Component(root);
root.setIdentifier(id);
root.setEmbeddedIdentifier(true);
id.setComponentClassName( domainClass.getFullName() );
id.setKey(true);
id.setEmbedded(true);
String path = StringHelper.qualify(
root.getEntityName(),
"id");
id.setRoleName(path);
String[] props = compositeIdentity.getPropertyNames();
for (int i = 0; i < props.length; i++) {
String propName = props[i];
GrailsDomainClassProperty property = domainClass.getPropertyByName(propName);
if(property == null) throw new MappingException("Property ["+propName+"] referenced in composite-id mapping of class ["+domainClass.getFullName()+"] is not a valid property!");
bindComponentProperty(id, property, root, "", root.getTable(), mappings);
}
}
/**
* Creates and binds the properties for the specified Grails domain class and PersistantClass
* and binds them to the Hibernate runtime meta model
*
* @param domainClass The Grails domain class
* @param persistentClass The Hibernate PersistentClass instance
* @param mappings The Hibernate Mappings instance
*/
protected static void createClassProperties(GrailsDomainClass domainClass, PersistentClass persistentClass, Mappings mappings) {
GrailsDomainClassProperty[] persistentProperties = domainClass.getPersistentProperties();
Table table = persistentClass.getTable();
Mapping gormMapping = getMapping(domainClass.getFullName());
for(int i = 0; i < persistentProperties.length;i++) {
GrailsDomainClassProperty currentGrailsProp = persistentProperties[i];
// if its inherited skip
if(currentGrailsProp.isInherited() && !isBidirectionalManyToOne(currentGrailsProp))
continue;
if (isCompositeIdProperty(gormMapping, currentGrailsProp)) continue;
if(LOG.isDebugEnabled())
LOG.debug("[GrailsDomainBinder] Binding persistent property [" + currentGrailsProp.getName() + "]");
Value value;
// see if its a collection type
CollectionType collectionType = CollectionType.collectionTypeForClass( currentGrailsProp.getType() );
if(collectionType != null) {
// create collection
Collection collection = collectionType.create(
currentGrailsProp,
persistentClass,
EMPTY_PATH, mappings
);
mappings.addCollection(collection);
value = collection;
}
// work out what type of relationship it is and bind value
else if ( currentGrailsProp.isManyToOne() ) {
if(LOG.isDebugEnabled())
LOG.debug("[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName() + "] as ManyToOne");
value = new ManyToOne( table );
bindManyToOne( currentGrailsProp, (ManyToOne) value, EMPTY_PATH, mappings );
}
else if ( currentGrailsProp.isOneToOne() && !UserType.class.isAssignableFrom(currentGrailsProp.getType())) {
if(LOG.isDebugEnabled())
LOG.debug("[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName() + "] as OneToOne");
//value = new OneToOne( table, persistentClass );
//bindOneToOne( currentGrailsProp, (OneToOne)value, mappings );
value = new ManyToOne( table );
bindManyToOne( currentGrailsProp, (ManyToOne) value, EMPTY_PATH, mappings );
}
else if ( currentGrailsProp.isEmbedded() ) {
value = new Component( persistentClass );
bindComponent((Component)value, currentGrailsProp, true, mappings);
}
else {
if(LOG.isDebugEnabled())
LOG.debug("[GrailsDomainBinder] Binding property [" + currentGrailsProp.getName() + "] as SimpleValue");
value = new SimpleValue( table );
bindSimpleValue( persistentProperties[i], (SimpleValue) value, EMPTY_PATH, mappings );
}
if(value != null) {
Property property = createProperty( value, persistentClass, persistentProperties[i], mappings );
persistentClass.addProperty( property );
}
}
}
private static boolean isCompositeIdProperty(Mapping gormMapping, GrailsDomainClassProperty currentGrailsProp) {
if(gormMapping != null && gormMapping.getIdentity() != null) {
Object id = gormMapping.getIdentity();
if(id instanceof CompositeIdentity) {
CompositeIdentity cid = (CompositeIdentity)id;
if(ArrayUtils.contains(cid.getPropertyNames(), currentGrailsProp.getName()))
return true;
}
}
return false;
}
private static boolean isBidirectionalManyToOne(GrailsDomainClassProperty currentGrailsProp) {
return (currentGrailsProp.isBidirectional() && currentGrailsProp.isManyToOne());
}
/**
* Binds a Hibernate component type using the given GrailsDomainClassProperty instance
*
* @param component The component to bind
* @param property The property
* @param isNullable Whether it is nullable or not
* @param mappings The Hibernate Mappings object
*/
private static void bindComponent(Component component, GrailsDomainClassProperty property, boolean isNullable, Mappings mappings) {
component.setEmbedded(true);
Class type = property.getType();
String role = StringHelper.qualify(type.getName(), property.getName());
component.setRoleName(role);
component.setComponentClassName(type.getName());
GrailsDomainClass domainClass = property.getReferencedDomainClass() != null ? property.getReferencedDomainClass() : new ComponentDomainClass(type);
GrailsDomainClassProperty[] properties = domainClass.getPersistentProperties();
Table table = component.getOwner().getTable();
PersistentClass persistentClass = component.getOwner();
String path = property.getName();
Class propertyType = property.getDomainClass().getClazz();
for (int i = 0; i < properties.length; i++) {
GrailsDomainClassProperty currentGrailsProp = properties[i];
if(currentGrailsProp.isIdentity()) continue;
if(currentGrailsProp.getName().equals(GrailsDomainClassProperty.VERSION)) continue;
if(currentGrailsProp.getType().equals(propertyType)) {
component.setParentProperty(currentGrailsProp.getName());
continue;
}
bindComponentProperty(component, currentGrailsProp, persistentClass, path, table, mappings);
}
}
private static GrailsDomainClassProperty[] createDomainClassProperties(ComponentDomainClass type, PropertyDescriptor[] descriptors) {
List properties = new ArrayList();
for (int i = 0; i < descriptors.length; i++) {
PropertyDescriptor descriptor = descriptors[i];
if(GrailsDomainConfigurationUtil.isNotConfigurational(descriptor)) {
properties.add(new DefaultGrailsDomainClassProperty(type,descriptor));
}
}
return (GrailsDomainClassProperty[])properties.toArray(new GrailsDomainClassProperty[properties.size()]);
}
private static void bindComponentProperty(Component component, GrailsDomainClassProperty property, PersistentClass persistentClass, String path, Table table, Mappings mappings) {
Value value = null;
// see if its a collection type
CollectionType collectionType = CollectionType.collectionTypeForClass( property.getType() );
if(collectionType != null) {
// create collection
Collection collection = collectionType.create(
property,
persistentClass,
path,
mappings
);
mappings.addCollection(collection);
value = collection;
}
// work out what type of relationship it is and bind value
else if ( property.isManyToOne() ) {
if(LOG.isDebugEnabled())
LOG.debug("[GrailsDomainBinder] Binding property [" + property.getName() + "] as ManyToOne");
value = new ManyToOne( table );
bindManyToOne(property, (ManyToOne) value, path, mappings );
}
else if ( property.isOneToOne()) {
if(LOG.isDebugEnabled())
LOG.debug("[GrailsDomainBinder] Binding property [" + property.getName() + "] as OneToOne");
//value = new OneToOne( table, persistentClass );
//bindOneToOne( currentGrailsProp, (OneToOne)value, mappings );
value = new ManyToOne( table );
bindManyToOne(property, (ManyToOne) value, path, mappings );
}
/*
else if ( currentGrailsProp.isEmbedded() ) {
value = new Component( persistentClass );
bindComponent((Component)value, currentGrailsProp, true, mappings);
}
*/
else {
if(LOG.isDebugEnabled())
LOG.debug("[GrailsDomainBinder] Binding property [" + property.getName() + "] as SimpleValue");
value = new SimpleValue( table );
bindSimpleValue(property, (SimpleValue) value, path, mappings );
}
if(value != null) {
Property persistentProperty = createProperty( value, persistentClass, property, mappings );
component.addProperty( persistentProperty );
}
}
/**
* Creates a persistant class property based on the GrailDomainClassProperty instance
*
* @param value
* @param persistentClass
* @param mappings
*/
private static Property createProperty(Value value, PersistentClass persistentClass, GrailsDomainClassProperty grailsProperty, Mappings mappings) {
// set type
value.setTypeUsingReflection( persistentClass.getClassName(), grailsProperty.getName() );
// if it is a ManyToOne or OneToOne relationship
if ( value instanceof ToOne ) {
ToOne toOne = (ToOne) value;
String propertyRef = toOne.getReferencedPropertyName();
if ( propertyRef != null ) {
// TODO: Hmm this method has package visibility. Why?
//mappings.addUniquePropertyReference( toOne.getReferencedEntityName(), propertyRef );
}
}
else if( value instanceof Collection ) {
//Collection collection = (Collection)value;
//String propertyRef = collection.getReferencedPropertyName();
}
if(value.getTable() != null)
value.createForeignKey();
Property prop = new Property();
prop.setValue( value );
bindProperty( grailsProperty, prop, mappings );
return prop;
}
/**
* @param property
* @param oneToOne
* @param mappings
*/
/* private static void bindOneToOne(GrailsDomainClassProperty property, OneToOne oneToOne, Mappings mappings) {
// bind value
bindSimpleValue(property, oneToOne, mappings );
// set foreign key type
oneToOne.setForeignKeyType( ForeignKeyDirection.FOREIGN_KEY_TO_PARENT );
oneToOne.setForeignKeyName( property.getFieldName() + FOREIGN_KEY_SUFFIX );
// TODO configure fetch settings
oneToOne.setFetchMode( FetchMode.DEFAULT );
// TODO configure lazy loading
oneToOne.setLazy(true);
oneToOne.setPropertyName( property.getTagName() );
oneToOne.setReferencedEntityName( property.getType().getTagName() );
}*/
/**
* @param currentGrailsProp
* @param one
* @param mappings
*/
private static void bindOneToMany(GrailsDomainClassProperty currentGrailsProp, OneToMany one, Mappings mappings) {
one.setReferencedEntityName( currentGrailsProp.getReferencedPropertyType().getName() );
}
/**
* Binds a many-to-one relationship to the
* @param property
* @param manyToOne
* @param path
* @param mappings
*/
private static void bindManyToOne(GrailsDomainClassProperty property, ManyToOne manyToOne, String path, Mappings mappings) {
bindManyToOneValues(property, manyToOne);
// bind column
bindSimpleValue(property,manyToOne, path, mappings);
}
/**
* @param property
* @param manyToOne
*/
private static void bindManyToOneValues(GrailsDomainClassProperty property, ManyToOne manyToOne) {
// TODO configure fetching
manyToOne.setFetchMode(FetchMode.DEFAULT);
// TODO configure lazy loading
ColumnConfig cc = getColumnConfig(property);
if(cc != null) {
manyToOne.setLazy(cc.getLazy());
}
else {
manyToOne.setLazy(true);
}
// set referenced entity
manyToOne.setReferencedEntityName( property.getReferencedPropertyType().getName() );
manyToOne.setIgnoreNotFound(true);
}
/**
* @param version
* @param mappings
*/
private static void bindVersion(GrailsDomainClassProperty version, RootClass entity, Mappings mappings) {
SimpleValue val = new SimpleValue( entity.getTable() );
bindSimpleValue( version, val, EMPTY_PATH, mappings);
if ( !val.isTypeSpecified() ) {
val.setTypeName( "version".equals( version.getName() ) ? "integer" : "timestamp" );
}
Property prop = new Property();
prop.setValue( val );
bindProperty( version, prop, mappings );
val.setNullValue( "undefined" );
entity.setVersion( prop );
entity.addProperty( prop );
}
/**
* @param identifier
* @param entity
* @param mappings
* @param mappedId
*/
private static void bindSimpleId(GrailsDomainClassProperty identifier, RootClass entity, Mappings mappings, Identity mappedId) {
// create the id value
SimpleValue id = new SimpleValue(entity.getTable());
// set identifier on entity
Properties params = new Properties();
entity.setIdentifier( id );
if(mappedId != null) {
id.setIdentifierGeneratorStrategy(mappedId.getGenerator());
params.putAll(mappedId.getParams());
}
else {
// configure generator strategy
id.setIdentifierGeneratorStrategy( "native" );
}
if ( mappings.getSchemaName() != null ) {
params.setProperty( PersistentIdentifierGenerator.SCHEMA, mappings.getSchemaName() );
}
if ( mappings.getCatalogName() != null ) {
params.setProperty( PersistentIdentifierGenerator.CATALOG, mappings.getCatalogName() );
}
id.setIdentifierGeneratorProperties(params);
// bind value
bindSimpleValue(identifier, id, EMPTY_PATH, mappings );
// create property
Property prop = new Property();
prop.setValue(id);
// bind property
bindProperty( identifier, prop, mappings );
// set identifier property
entity.setIdentifierProperty( prop );
id.getTable().setIdentifierValue( id );
}
/**
* Binds a property to Hibernate runtime meta model. Deals with cascade strategy based on the Grails domain model
*
* @param grailsProperty The grails property instance
* @param prop The Hibernate property
* @param mappings The Hibernate mappings
*/
private static void bindProperty(GrailsDomainClassProperty grailsProperty, Property prop, Mappings mappings) {
// set the property name
prop.setName( grailsProperty.getName() );
prop.setInsertable(true);
prop.setUpdateable(true);
prop.setPropertyAccessorName( mappings.getDefaultAccess() );
prop.setOptional( grailsProperty.isOptional() );
setCascadeBehaviour(grailsProperty, prop);
// lazy to true
prop.setLazy(true);
}
private static void setCascadeBehaviour(GrailsDomainClassProperty grailsProperty, Property prop) {
String cascadeStrategy = "none";
// set to cascade all for the moment
GrailsDomainClass domainClass = grailsProperty.getDomainClass();
ColumnConfig cc = getColumnConfig(grailsProperty);
GrailsDomainClass referenced = grailsProperty.getReferencedDomainClass();
if(cc!=null && cc.getCascade() != null) {
cascadeStrategy = cc.getCascade();
}
else if(grailsProperty.isAssociation()) {
if(grailsProperty.isOneToOne()) {
if(referenced!=null&&referenced.isOwningClass(domainClass.getClazz()))
cascadeStrategy = CASCADE_ALL;
}
else if(grailsProperty.isOneToMany()) {
if(referenced!=null&&referenced.isOwningClass(domainClass.getClazz()))
cascadeStrategy = CASCADE_ALL;
else
cascadeStrategy = CASCADE_SAVE_UPDATE;
}
else if(grailsProperty.isManyToMany()) {
if(referenced!=null&&referenced.isOwningClass(domainClass.getClazz()))
cascadeStrategy = CASCADE_SAVE_UPDATE;
}
else if(grailsProperty.isManyToOne()) {
if(referenced!=null&&referenced.isOwningClass(domainClass.getClazz()))
cascadeStrategy = CASCADE_ALL;
else
cascadeStrategy = CASCADE_MERGE;
}
}
else if( Map.class.isAssignableFrom(grailsProperty.getType())) {
referenced = grailsProperty.getReferencedDomainClass();
if(referenced!=null&&referenced.isOwningClass(grailsProperty.getDomainClass().getClazz())) {
cascadeStrategy = CASCADE_ALL;
}
else {
cascadeStrategy = CASCADE_SAVE_UPDATE;
}
}
logCascadeMapping(grailsProperty, cascadeStrategy, referenced);
prop.setCascade(cascadeStrategy);
}
private static void logCascadeMapping(GrailsDomainClassProperty grailsProperty, String cascadeStrategy, GrailsDomainClass referenced) {
if(LOG.isDebugEnabled() && grailsProperty.isAssociation()) {
String assType = getAssociationDescription(grailsProperty);
LOG.debug("Mapping cascade strategy for "+assType+" property "+grailsProperty.getDomainClass().getFullName()+"." + grailsProperty.getName() + " referencing type ["+referenced.getClazz()+"] -> [CASCADE: "+cascadeStrategy+"]");
}
}
private static String getAssociationDescription(GrailsDomainClassProperty grailsProperty) {
String assType = "unknown";
if(grailsProperty.isManyToMany()) {
assType = "many-to-many";
}
else if(grailsProperty.isOneToMany()) {
assType = "one-to-many";
}
else if(grailsProperty.isOneToOne()) {
assType = "one-to-one";
}
else if(grailsProperty.isManyToOne()) {
assType = "many-to-one";
}
else if(grailsProperty.isEmbedded()) {
assType = "embedded";
}
return assType;
}
/**
w * Binds a simple value to the Hibernate metamodel. A simple value is
* any type within the Hibernate type system
*
* @param grailsProp The grails domain class property
* @param simpleValue The simple value to bind
* @param path
* @param mappings The Hibernate mappings instance
*/
private static void bindSimpleValue(GrailsDomainClassProperty grailsProp, SimpleValue simpleValue, String path, Mappings mappings) {
// set type
ColumnConfig cc = getColumnConfig(grailsProp);
setTypeForColumnConfig(grailsProp, simpleValue, cc);
Table table = simpleValue.getTable();
Column column = new Column();
// Check for explicitly mapped column name.
if (cc != null && cc.getColumn() != null) {
column.setName(cc.getColumn());
}
column.setValue(simpleValue);
bindColumn(grailsProp, column, path, table);
if(table != null) table.addColumn(column);
simpleValue.addColumn(column);
}
private static void setTypeForColumnConfig(GrailsDomainClassProperty grailsProp, SimpleValue simpleValue, ColumnConfig cc) {
if(cc != null && cc.getType() != null) {
Object type = cc.getType();
simpleValue.setTypeName(type.toString());
}
else {
simpleValue.setTypeName(grailsProp.getType().getName());
}
}
/**
* Binds a value for the specified parameters to the meta model.
*
* @param type The type of the property
* @param simpleValue The simple value instance
* @param nullable Whether it is nullable
* @param columnName The property name
* @param mappings The mappings
*/
private static void bindSimpleValue(String type,SimpleValue simpleValue, boolean nullable, String columnName, Mappings mappings) {
simpleValue.setTypeName(type);
Table t = simpleValue.getTable();
Column column = new Column();
column.setNullable(nullable);
column.setValue(simpleValue);
column.setName(columnName);
if(t!=null)t.addColumn(column);
simpleValue.addColumn(column);
}
/**
* Binds a Column instance to the Hibernate meta model
* @param grailsProp The Grails domain class property
* @param column The column to bind
* @param path
* @param table The table name
*/
private static void bindColumn(GrailsDomainClassProperty grailsProp, Column column, String path, Table table) {
if(grailsProp.isAssociation()) {
// Only use conventional naming when the column has not been explicitly mapped.
if (column.getName() == null) {
String columnName = getColumnNameForPropertyAndPath(grailsProp, path);
if(!grailsProp.isBidirectional() && grailsProp.isOneToMany()) {
String prefix = namingStrategy.classToTableName(grailsProp.getDomainClass().getName());
column.setName(prefix+ UNDERSCORE +columnName + FOREIGN_KEY_SUFFIX);
} else {
if(grailsProp.isInherited() && isBidirectionalManyToOne(grailsProp)) {
column.setName( namingStrategy.propertyToColumnName(grailsProp.getDomainClass().getName()) + '_'+ columnName + FOREIGN_KEY_SUFFIX );
}
else {
column.setName( columnName + FOREIGN_KEY_SUFFIX );
}
}
}
column.setNullable(true);
} else {
String columnName = getColumnNameForPropertyAndPath(grailsProp, path);
column.setName(columnName);
column.setNullable(grailsProp.isOptional());
// Use the constraints for this property to more accurately define
// the column's length, precision, and scale
ConstrainedProperty constrainedProperty = getConstrainedProperty(grailsProp);
if (constrainedProperty != null) {
if (String.class.isAssignableFrom(grailsProp.getType()) || byte[].class.isAssignableFrom(grailsProp.getType())) {
bindStringColumnConstraints(column, constrainedProperty);
}
if (Number.class.isAssignableFrom(grailsProp.getType())) {
bindNumericColumnConstraints(column, constrainedProperty);
}
}
}
bindIndex(grailsProp, column, table);
if(!grailsProp.getDomainClass().isRoot()) {
if(LOG.isDebugEnabled())
LOG.debug("[GrailsDomainBinder] Sub class property [" + grailsProp.getName() + "] for column name ["+column.getName()+"] in table ["+table.getName()+"] set to nullable");
column.setNullable(true);
}
if(LOG.isDebugEnabled())
LOG.debug("[GrailsDomainBinder] bound property [" + grailsProp.getName() + "] to column name ["+column.getName()+"] in table ["+table.getName()+"]");
}
private static void bindIndex(GrailsDomainClassProperty grailsProp, Column column, Table table) {
ColumnConfig cc = getColumnConfig(grailsProp);
if(cc!=null) {
String indexDefinition = cc.getIndex();
if(indexDefinition != null) {
String[] tokens = indexDefinition.split(",");
for (int i = 0; i < tokens.length; i++) {
String index = tokens[i];
table.getOrCreateIndex(index).addColumn(column);
}
}
}
}
private static String getColumnNameForPropertyAndPath(GrailsDomainClassProperty grailsProp, String path) {
GrailsDomainClass domainClass = grailsProp.getDomainClass();
String columnName = null;
Mapping m = getMapping(domainClass.getFullName());
if(m != null) {
ColumnConfig c = m.getColumn(grailsProp.getName());
if(c != null && c.getColumn() != null) {
columnName = c.getColumn();
}
}
if(columnName == null) {
if(StringHelper.isNotEmpty(path)) {
columnName = namingStrategy.propertyToColumnName(path) + UNDERSCORE + namingStrategy.propertyToColumnName(grailsProp.getName());
}
else {
columnName = namingStrategy.propertyToColumnName(grailsProp.getName());
}
}
return columnName;
}
/**
* Returns the constraints applied to the specified domain class property.
*
* @param grailsProp the property whose constraints will be returned
* @return the <code>ConstrainedProperty</code> object representing the property's constraints
*/
private static ConstrainedProperty getConstrainedProperty(GrailsDomainClassProperty grailsProp) {
ConstrainedProperty constrainedProperty = null;
Map constraints = grailsProp.getDomainClass().getConstrainedProperties();
for (Iterator constrainedPropertyIter = constraints.values().iterator(); constrainedPropertyIter.hasNext() && (constrainedProperty == null);) {
ConstrainedProperty tmpConstrainedProperty = (ConstrainedProperty)constrainedPropertyIter.next();
if (tmpConstrainedProperty.getPropertyName().equals(grailsProp.getName())) {
constrainedProperty = tmpConstrainedProperty;
}
}
return constrainedProperty;
}
/**
* Interrogates the specified constraints looking for any constraints that would limit the
* length of the property's value. If such constraints exist, this method adjusts the length
* of the column accordingly.
*
* @param column the column that corresponds to the property
* @param constrainedProperty the property's constraints
*/
protected static void bindStringColumnConstraints(Column column, ConstrainedProperty constrainedProperty) {
Integer columnLength = constrainedProperty.getMaxSize();
List inListValues = constrainedProperty.getInList();
if (columnLength != null) {
column.setLength(columnLength.intValue());
}
else if (inListValues != null) {
column.setLength(getMaxSize(inListValues));
}
}
/**
* Interrogates the specified constraints looking for any constraints that would limit the
* precision and/or scale of the property's value. If such constraints exist, this method adjusts
* the precision and/or scale of the column accordingly.
*
* @param column the column that corresponds to the property
* @param constrainedProperty the property's constraints
*/
protected static void bindNumericColumnConstraints(Column column, ConstrainedProperty constrainedProperty) {
int scale = Column.DEFAULT_SCALE;
int precision = Column.DEFAULT_PRECISION;
if (constrainedProperty.getScale() != null) {
scale = constrainedProperty.getScale().intValue();
column.setScale(scale);
}
Comparable minConstraintValue = constrainedProperty.getMin();
Comparable maxConstraintValue = constrainedProperty.getMax();
int minConstraintValueLength = 0;
if ((minConstraintValue != null) && (minConstraintValue instanceof Number)) {
minConstraintValueLength = Math.max(
countDigits((Number) minConstraintValue),
countDigits(new Long(((Number) minConstraintValue).longValue())) + scale
);
}
int maxConstraintValueLength = 0;
if ((maxConstraintValue != null) && (maxConstraintValue instanceof Number)) {
maxConstraintValueLength = Math.max(
countDigits((Number) maxConstraintValue),
countDigits(new Long(((Number) maxConstraintValue).longValue())) + scale
);
}
if (minConstraintValueLength > 0 && maxConstraintValueLength > 0) {
// If both of min and max constraints are setted we could use
// maximum digits number in it as precision
precision = NumberUtils.max(new int[] { minConstraintValueLength, maxConstraintValueLength });
} else {
// Overwise we should also use default precision
precision = NumberUtils.max(new int[] { precision, minConstraintValueLength, maxConstraintValueLength });
}
column.setPrecision(precision);
}
/**
* @return a count of the digits in the specified number
*/
private static int countDigits(Number number) {
int numDigits = 0;
if (number != null) {
// Remove everything that's not a digit (e.g., decimal points or signs)
String digitsOnly = number.toString().replaceAll("\\D", EMPTY_PATH);
numDigits = digitsOnly.length();
}
return numDigits;
}
/**
* @return the maximum length of the strings in the specified list
*/
private static int getMaxSize(List inListValues) {
int maxSize = 0;
for (Iterator iter = inListValues.iterator(); iter.hasNext();) {
String value = (String)iter.next();
maxSize = Math.max(value.length(), maxSize);
}
return maxSize;
}
private static class ComponentDomainClass extends AbstractGrailsClass implements GrailsDomainClass {
private GrailsDomainClassProperty[] properties;
public ComponentDomainClass(Class type) {
super(type, "");
PropertyDescriptor[] descriptors;
try {
descriptors = java.beans.Introspector.getBeanInfo(type).getPropertyDescriptors();
} catch (IntrospectionException e) {
throw new MappingException("Failed to use class ["+type+"] as a component. Cannot introspect! " + e.getMessage());
}
this.properties = createDomainClassProperties(this,descriptors);
}
public boolean isOwningClass(Class domainClass) {
return false;
}
public GrailsDomainClassProperty[] getProperties() {
return properties;
}
public GrailsDomainClassProperty[] getPersistantProperties() {
return properties;
}
public GrailsDomainClassProperty[] getPersistentProperties() {
return properties;
}
public GrailsDomainClassProperty getIdentifier() {
return null; // no identifier for embedded component
}
public GrailsDomainClassProperty getVersion() {
return null; // no version for embedded component
}
public Map getAssociationMap() {
return Collections.EMPTY_MAP;
}
public GrailsDomainClassProperty getPropertyByName(String name) {
for (int i = 0; i < properties.length; i++) {
GrailsDomainClassProperty property = properties[i];
if(property.getName().equals(name)) return property;
}
return null;
}
public String getFieldName(String propertyName) {
return null;
}
public boolean isOneToMany(String propertyName) {
return false;
}
public boolean isManyToOne(String propertyName) {
return false;
}
public boolean isBidirectional(String propertyName) {
return false;
}
public Class getRelatedClassType(String propertyName) {
return getPropertyByName(propertyName).getReferencedPropertyType();
}
public Map getConstrainedProperties() {
return Collections.EMPTY_MAP;
}
public Validator getValidator() {
return null;
}
public void setValidator(Validator validator) {
}
public String getMappingStrategy() {
return GrailsDomainClass.GORM;
}
public boolean isRoot() {
return true;
}
public Set getSubClasses() {
return Collections.EMPTY_SET;
}
public void refreshConstraints() {
// do nothing
}
public boolean hasSubClasses() {
return false;
}
public Map getMappedBy() {
return Collections.EMPTY_MAP;
}
}
}
| true | false | null | null |
diff --git a/amibe/src/org/jcae/mesh/amibe/algos3d/JunctionConverter.java b/amibe/src/org/jcae/mesh/amibe/algos3d/JunctionConverter.java
index 883208e7..d2fb3040 100644
--- a/amibe/src/org/jcae/mesh/amibe/algos3d/JunctionConverter.java
+++ b/amibe/src/org/jcae/mesh/amibe/algos3d/JunctionConverter.java
@@ -1,85 +1,97 @@
/*
- * This source code is the property of EADS France. No part of it shall
- * be reproduced or transmitted without the express prior written
- * authorization of EADS France, and its contents shall not be disclosed.
- * Copyright EADS France.
+ * Project Info: http://jcae.sourceforge.net
+ *
+ * This program 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 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; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
+ *
+ * (C) Copyright 2012, by EADS France
*/
-
package org.jcae.mesh.amibe.algos3d;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import org.jcae.mesh.amibe.ds.AbstractHalfEdge;
import org.jcae.mesh.amibe.ds.Mesh;
import org.jcae.mesh.amibe.ds.Vertex;
/**
* Convert junctions between beams and triangles to group of node
* @author Jerome Robert
*/
public class JunctionConverter {
private transient int groupID = 1;
private final Collection<String> groupNames = new HashSet<String>();
private final Mesh mesh;
public JunctionConverter(Mesh mesh)
{
this.mesh = mesh;
for(int i = 0; i < mesh.getNumberOfGroups(); i++)
groupNames.add(mesh.getGroupName(i));
}
public void compute()
{
List<Vertex> beams = mesh.getBeams();
int n = beams.size();
for(int i = 0; i < n; i++)
{
Vertex v = beams.get(i);
if(v.getLink() != null)
processVertex(i, v, mesh);
}
}
private String groupName()
{
String r;
do
{
r = groupName(groupID++);
}
while(groupNames.contains(r));
return r;
}
protected String groupName(int i)
{
return "J_"+i;
}
private void processVertex(int i, Vertex v, Mesh mesh) {
Iterator<AbstractHalfEdge> it = v.getNeighbourIteratorAbstractHalfEdge();
double min = Double.MAX_VALUE;
Vertex bestOther = null;
while(it.hasNext())
{
AbstractHalfEdge edge = it.next();
Vertex other = edge.destination();
double d2 = other.sqrDistance3D(v);
if(d2 < min)
{
min = d2;
bestOther = other;
}
}
String group = groupName();
Vertex newV = mesh.createVertex(v.getUV());
newV.setMutable(false);
mesh.add(newV);
mesh.setBeam(i, newV);
mesh.setVertexGroup(v, group);
mesh.setVertexGroup(newV, group);
mesh.setVertexGroup(bestOther, group);
}
}
| false | false | null | null |
diff --git a/rxjava-core/src/test/java/rx/operators/OperationParallelMergeTest.java b/rxjava-core/src/test/java/rx/operators/OperationParallelMergeTest.java
index 907993ef1..7872ae59d 100644
--- a/rxjava-core/src/test/java/rx/operators/OperationParallelMergeTest.java
+++ b/rxjava-core/src/test/java/rx/operators/OperationParallelMergeTest.java
@@ -1,135 +1,119 @@
/**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package rx.operators;
import static org.junit.Assert.*;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import rx.Observable;
import rx.schedulers.Schedulers;
import rx.subjects.PublishSubject;
import rx.util.functions.Action1;
import rx.util.functions.Func1;
public class OperationParallelMergeTest {
@Test
public void testParallelMerge() {
PublishSubject<String> p1 = PublishSubject.<String> create();
PublishSubject<String> p2 = PublishSubject.<String> create();
PublishSubject<String> p3 = PublishSubject.<String> create();
PublishSubject<String> p4 = PublishSubject.<String> create();
Observable<Observable<String>> fourStreams = Observable.<Observable<String>> from(p1, p2, p3, p4);
Observable<Observable<String>> twoStreams = OperationParallelMerge.parallelMerge(fourStreams, 2);
Observable<Observable<String>> threeStreams = OperationParallelMerge.parallelMerge(fourStreams, 3);
List<? super Observable<String>> fourList = fourStreams.toList().toBlockingObservable().last();
List<? super Observable<String>> threeList = threeStreams.toList().toBlockingObservable().last();
List<? super Observable<String>> twoList = twoStreams.toList().toBlockingObservable().last();
System.out.println("two list: " + twoList);
System.out.println("three list: " + threeList);
System.out.println("four list: " + fourList);
assertEquals(4, fourList.size());
assertEquals(3, threeList.size());
assertEquals(2, twoList.size());
}
@Test
public void testNumberOfThreads() {
- final ConcurrentHashMap<String, String> threads = new ConcurrentHashMap<String, String>();
- Observable.merge(getStreams())
- .toBlockingObservable().forEach(new Action1<String>() {
-
- @Override
- public void call(String o) {
- System.out.println("o: " + o + " Thread: " + Thread.currentThread());
- threads.put(Thread.currentThread().getName(), Thread.currentThread().getName());
- }
- });
-
- // without injecting anything, the getStream() method uses Interval which runs on a default scheduler
- assertEquals(Runtime.getRuntime().availableProcessors(), threads.keySet().size());
-
- // clear
- threads.clear();
-
- // now we parallelMerge into 3 streams and observeOn for each
+ final ConcurrentHashMap<Long, Long> threads = new ConcurrentHashMap<Long, Long>();
+ // parallelMerge into 3 streams and observeOn for each
// we expect 3 threads in the output
OperationParallelMerge.parallelMerge(getStreams(), 3)
.flatMap(new Func1<Observable<String>, Observable<String>>() {
@Override
public Observable<String> call(Observable<String> o) {
// for each of the parallel
return o.observeOn(Schedulers.newThread());
}
})
.toBlockingObservable().forEach(new Action1<String>() {
@Override
public void call(String o) {
- System.out.println("o: " + o + " Thread: " + Thread.currentThread());
- threads.put(Thread.currentThread().getName(), Thread.currentThread().getName());
+ System.out.println("o: " + o + " Thread: " + Thread.currentThread().getId());
+ threads.put(Thread.currentThread().getId(), Thread.currentThread().getId());
}
});
assertEquals(3, threads.keySet().size());
}
@Test
public void testNumberOfThreadsOnScheduledMerge() {
- final ConcurrentHashMap<String, String> threads = new ConcurrentHashMap<String, String>();
+ final ConcurrentHashMap<Long, Long> threads = new ConcurrentHashMap<Long, Long>();
// now we parallelMerge into 3 streams and observeOn for each
// we expect 3 threads in the output
Observable.merge(OperationParallelMerge.parallelMerge(getStreams(), 3, Schedulers.newThread()))
.toBlockingObservable().forEach(new Action1<String>() {
@Override
public void call(String o) {
- System.out.println("o: " + o + " Thread: " + Thread.currentThread());
- threads.put(Thread.currentThread().getName(), Thread.currentThread().getName());
+ System.out.println("o: " + o + " Thread: " + Thread.currentThread().getId());
+ threads.put(Thread.currentThread().getId(), Thread.currentThread().getId());
}
});
assertEquals(3, threads.keySet().size());
}
private static Observable<Observable<String>> getStreams() {
return Observable.range(0, 10).map(new Func1<Integer, Observable<String>>() {
@Override
public Observable<String> call(final Integer i) {
return Observable.interval(10, TimeUnit.MILLISECONDS).map(new Func1<Long, String>() {
@Override
public String call(Long l) {
return "Stream " + i + " Value: " + l;
}
}).take(5);
}
});
}
}
| false | false | null | null |
diff --git a/src/main/java/component/controller/ProjectController.java b/src/main/java/component/controller/ProjectController.java
index 1da9ac9..6cde6fd 100755
--- a/src/main/java/component/controller/ProjectController.java
+++ b/src/main/java/component/controller/ProjectController.java
@@ -1,408 +1,408 @@
package component.controller;
import component.service.FurnitureService;
import component.service.ProjectService;
import component.service.UserService;
import entity.FurnitureItem;
import entity.ProjectDataEntity;
import entity.UserEntity;
import entity.WallItem;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.security.Principal;
import java.sql.Timestamp;
import java.util.*;
@Controller
@RequestMapping("/project")
public class ProjectController {
@Autowired
public ProjectService projectService;
@Autowired
public UserService userService;
@Autowired
public FurnitureService furnitureService;
@RequestMapping(method = RequestMethod.GET, produces="text/html")
public String showProjectList(Map<String, Object> model, Principal principal) {
List<ProjectDataEntity> projectList = projectService.getAllProjects();
if(projectList!=null) {
model.put("projectList", projectList);
if(principal!=null) {
String userName = principal.getName();
model.put("principal", userName);
}
model.put("pageHeading", "Katalog projektów");
model.put("pageLead", "Lista projektów wszystkich użytkowników");
return "projectList";
}
else {
model.put("error", "Brak projektów w bazie.");
return "projectErrorPage";
}
}
@RequestMapping(value = {"/{id}"}, method = RequestMethod.GET, produces="text/html")
public String showProject(@PathVariable int id, Map<String, Object> model) throws IOException {
ProjectDataEntity projectData = projectService.getProject(id);
if(projectData!=null) {
ObjectMapper mapper = new ObjectMapper();
List<FurnitureItem> furnitureList = mapper.readValue(projectData.getDataObjects(), mapper.getTypeFactory().constructCollectionType(List.class, FurnitureItem.class));
List<WallItem> wallsList = mapper.readValue(projectData.getDataWalls(), mapper.getTypeFactory().constructCollectionType(List.class, WallItem.class));
String furnitureHtml = "";
for(FurnitureItem p : furnitureList) {
- furnitureHtml += "<div class='furniture' style='position:absolute; width:"
+ furnitureHtml += "<div class='furniture furniture-preview' style='position:absolute; width:"
+ p.getWidth() + "px; height:"
+ p.getHeight() + "px; top:"
+ p.getY() + "px; left:"
+ p.getX() + "px;'>"
+ "<span class='f_id'>" + p.getId() + "</span>"
+ "<span class='f_width'>" + p.getWidth() + " cm</span>"
+ "<span class='f_height'>" + p.getHeight() + " cm</span>"
+ "</div>";
}
String wallsHtml = "";
for(WallItem p : wallsList) {
if(p.getX2()-p.getX1() <= p.getY2()-p.getY1()) {
Integer height = p.getY2() - p.getY1();
wallsHtml += "<div class='wall' style='position:absolute; width: 3px; height: " + height +"px; top:" + p.getY1() + "px; left:" + p.getX1() + "px;'><span class='wall-height'>" + height + " cm</span></div>";
} else {
Integer width = p.getX2() - p.getX1();
wallsHtml += "<div class='wall' style='position:absolute; height: 3px; width: " + width +"px; top:" + p.getY1() + "px; left:" + p.getX1() + "px;'><span class='wall-width'>" + width + " cm</span></div>";
}
}
model.put("projectDataEntity", projectData);
model.put("pageHeading", "Projekt: " + projectData.getTitle());
model.put("pageLead", "Podgląd projektu użytkownika " + projectData.getOwnerId());
model.put("description", projectData.getProjectDescription());
model.put("furnitureHtml", furnitureHtml) ;
model.put("wallsHtml", wallsHtml) ;
return "projectViewer";
}
else {
model.put("error", "Projekt o podanym id nie istnieje.");
return "redirect:/project";
}
}
@PreAuthorize("hasRole('ROLE_USER')")
@RequestMapping(value = {"/edit/{id}"}, method = RequestMethod.GET, produces="text/html")
public String editProject(@PathVariable int id, Map<String, Object> model, Principal principal) throws IOException {
ProjectDataEntity projectData = projectService.getProject(id);
if(projectData!=null) {
if(projectData.getOwnerId().equals(principal.getName())) {
ObjectMapper mapper = new ObjectMapper();
List<FurnitureItem> furnitureList = mapper.readValue(projectData.getDataObjects(), mapper.getTypeFactory().constructCollectionType(List.class, FurnitureItem.class));
List<WallItem> wallsList = mapper.readValue(projectData.getDataWalls(), mapper.getTypeFactory().constructCollectionType(List.class, WallItem.class));
String furnitureHtml = "";
for(FurnitureItem p : furnitureList) {
furnitureHtml += "<div class='furniture movable obstacle' style='position:absolute; width:"
+ p.getWidth() + "px; height:"
+ p.getHeight() + "px; top:"
+ p.getY() + "px; left:"
+ p.getX() + "px;'>"
+ "<span class='f_id'>" + p.getId() + "</span>"
+ "<span class='f_width'>" + p.getWidth() + " cm</span>"
+ "<span class='f_height'>" + p.getHeight() + " cm</span>"
+ "<div class='f_delete'></div>"
+ "<div class='f_rotate'></div>"
+ "</div>";
}
String wallsHtml = "";
for(WallItem p : wallsList) {
if(p.getX2()-p.getX1() <= p.getY2()-p.getY1()) {
Integer height = p.getY2() - p.getY1();
wallsHtml += "<div class='wall editable obstacle' style='position:absolute; width: 3px; height: " + height +"px; top:" + p.getY1() + "px; left:" + p.getX1() + "px;'><span class='wall-height'>" + height + " cm</span></div>";
} else {
Integer width = p.getX2() - p.getX1();
wallsHtml += "<div class='wall editable obstacle' style='position:absolute; height: 3px; width: " + width +"px; top:" + p.getY1() + "px; left:" + p.getX1() + "px;'><span class='wall-width'>" + width + " cm</span></div>";
}
}
model.put("projectDataEntity", projectData);
model.put("pageHeading", "Projekt: " + projectData.getTitle());
model.put("pageLead", "Podgląd projektu użytkownika " + projectData.getOwnerId());
model.put("description", projectData.getProjectDescription());
model.put("furnitureHtml", furnitureHtml) ;
model.put("wallsHtml", wallsHtml) ;
return "projectEditor";
} else {
model.put("error", "Projekt o podanym id nie nalezy do Ciebie.");
return "redirect:/project";
}
} else {
model.put("error", "Projekt o podanym id nie istnieje.");
return "redirect:/project";
}
}
@PreAuthorize("hasRole('ROLE_USER')")
@RequestMapping(value = {"/edit/{id}"}, method = RequestMethod.POST, produces="text/html")
public String processEditedProject(@PathVariable int id, @Valid ProjectDataEntity projectDataEntity, BindingResult bindingResult, Principal principal, HttpServletRequest request) {
if(bindingResult.hasErrors()) {
return "projectEditor";
}
else {
ProjectDataEntity projectData = projectService.getProject(id);
projectData.setTitle(projectDataEntity.getTitle());
projectData.setProjectDescription(projectDataEntity.getProjectDescription());
projectData.setDataWalls(projectDataEntity.getDataWalls());
projectData.setDataObjects(projectDataEntity.getDataObjects());
projectService.updateProject(projectData);
return "redirect:/project/" + id;
}
}
@PreAuthorize("hasRole('ROLE_USER')")
@RequestMapping(value = "/user", method = RequestMethod.GET, produces="text/html")
public String showCurrentUserProjects(Map<String, Object> model, Principal principal) {
if(principal!=null) {
String userName = principal.getName();
System.out.print(userName);
List<ProjectDataEntity> projectList = projectService.getProjectsByUser(userName);
model.put("projectList", projectList);
model.put("principal", userName);
}
model.put("pageHeading", "Twoje projekty");
model.put("pageLead", "Projekty stworzone przez Ciebie w naszym systemie");
return "projectList";
}
@RequestMapping(value = "/user/{id}", method = RequestMethod.GET, produces="text/html")
public String showUserProjects(@PathVariable Integer id, Map<String, Object> model, Principal principal) {
UserEntity user = userService.getById(id);
if(principal!=null) {
String userName = principal.getName();
model.put("principal", userName);
}
model.put("projectList", projectService.getProjectsByUser(user.getEmail()));
return "projectList";
}
@PreAuthorize("hasRole('ROLE_USER')")
@RequestMapping(value = "/create", method = RequestMethod.GET, produces="text/html")
public String createProject(Map<String, Object> model, Principal principal) {
model.put("pageHeading", "Kreator projektu");
model.put("pageLead", "Stwórz projekt swojego mieszkania");
model.put("projectDataEntity", new ProjectDataEntity());
return "projectEditor";
}
@PreAuthorize("hasRole('ROLE_USER')")
@RequestMapping(value = {"/create"}, method = RequestMethod.POST, produces="text/html")
public String processCreateProject(@Valid ProjectDataEntity projectDataEntity, BindingResult bindingResult, Principal principal, HttpServletRequest request) {
if(bindingResult.hasErrors()) {
return "projectEditor";
}
else {
ProjectDataEntity projectData = new ProjectDataEntity();
projectData.setTitle(projectDataEntity.getTitle());
projectData.setProjectDescription(projectDataEntity.getProjectDescription());
projectData.setOwnerId(principal.getName());
System.out.println(projectDataEntity.getDataWalls());
projectData.setDataWalls(projectDataEntity.getDataWalls());
if(projectDataEntity.getDataObjects() == null) {
projectData.setDataObjects("[]");
} else {
projectData.setDataObjects(projectDataEntity.getDataObjects());
}
return "redirect:/project/" + projectService.createProject(projectData);
}
}
@PreAuthorize("hasRole('ROLE_USER')")
@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET, produces="text/html")
public String deleteProject(@PathVariable Integer id, Model model, Principal principal) {
ProjectDataEntity project = projectService.getProject(id);
if(project!=null) {
if(principal.getName().equals(project.getOwnerId())){
projectService.deleteProject(project);
model.addAttribute("info", "Projekt zostal pomyslnie skasowany z bazy danych.");
return "redirect:/project";
}
else {
model.addAttribute("error", "Nie mozesz skasowac projektu, ktory nie nalezy do Ciebie!");
return "redirect:/project";
}
}
else {
model.addAttribute("info", "Projekt nie istnieje.");
return "redirect:/project";
}
}
/*
Api mapping
*/
@RequestMapping(value ="/", method = RequestMethod.GET, produces="application/json;charset=UTF-8")
@ResponseBody
public Object getProjectList(@RequestParam("username") String email, @RequestParam("password") String password) throws IOException {
UserEntity userEntity = userService.getCredentials(email, password);
if(userEntity.getId()!=0) {
return projectService.apiGetProjectListByUser(userEntity.getEmail());
} else {
return "WrongCredentionals";
}
}
@RequestMapping(value ="/{id}", method = RequestMethod.GET, produces="application/json;charset=UTF-8")
@ResponseBody
public Object getProjectData(@PathVariable Integer id, @RequestParam("username") String email, @RequestParam("password") String password) throws IOException {
UserEntity userEntity = userService.getCredentials(email, password);
if(userEntity.getId()!=0) {
ProjectDataEntity projectDataEntity = projectService.getProject(id);
if(projectDataEntity!=null) {
if (projectDataEntity.getOwnerId().equals(userEntity.getEmail())) {
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(projectDataEntity);
} else {
return "NowAnOwner";
}
} else {
return "ProjectDoesntExist";
}
} else {
return "WrongCredentionals";
}
}
@RequestMapping(method = RequestMethod.POST, produces="application/json;charset=UTF-8")
@ResponseBody
public Object apiCreateProject(@RequestParam("title") String title,
@RequestParam("desc") String description,
@RequestParam("walls") Object walls,
@RequestParam("furniture") Object furniture,
@RequestParam("username") String email,
@RequestParam("password") String password) {
UserEntity userEntity = userService.getCredentials(email, password);
if(userEntity!=null) {
List<String> status = null;
if(title.isEmpty()){
status.add("TitleEmpty");
}
if(description.isEmpty()) {
status.add("DescEmpty");
}
if(walls.equals(null)) {
status.add("WallsIsNull");
}
if(furniture.equals(null)) {
status.add("FurnitureIsNull");
}
if(status != null) {
return status.toArray();
} else {
ProjectDataEntity projectData = new ProjectDataEntity();
projectData.setOwnerId(userEntity.getEmail());
projectData.setTitle(title);
projectData.setProjectDescription(description);
projectData.setDataObjects((String)furniture);
projectData.setDataWalls((String)walls);
return "ID=" + projectService.apiCreateProject(projectData);
}
} else {
return "WrongCredentionals";
}
}
@RequestMapping(value ="/{id}", method = RequestMethod.PUT, produces="application/json;charset=UTF-8")
@ResponseBody
public Object apiUpdateProject(@PathVariable("id") Integer id,
@RequestParam(value = "title", required=false) String title,
@RequestParam(value = "desc", required=false) String description,
@RequestParam("walls") String walls,
@RequestParam("furniture") String furniture,
@RequestParam("username") String email,
@RequestParam("password") String password) {
UserEntity userEntity = userService.getCredentials(email, password);
if(userEntity!=null) {
ProjectDataEntity projectData = projectService.getProject(id);
if(projectData!=null) {
if (projectData.getOwnerId().equals(email)) {
if(title!=null){
projectData.setTitle(title);
}
if(description!=null) {
projectData.setProjectDescription(description);
}
projectData.setDataWalls(walls);
projectData.setDataObjects(furniture);
projectService.apiUpdateProject(projectData);
return "ProjectUpdated";
} else {
return "NowAnOwner";
}
} else {
return "ProjectDoesntExist";
}
} else {
return "WrongCredentionals";
}
}
@RequestMapping(value ="/{id}", method = RequestMethod.DELETE, produces="application/json")
@ResponseBody
public Object deleteProjectData(@PathVariable Integer id) {
ProjectDataEntity projectDataEntity = projectService.getProject(id);
if(projectDataEntity!=null) {
projectService.deleteProject(projectDataEntity);
return "Deleted";
} else {
return "ProjectDoesntExist";
}
}
}
\ No newline at end of file
| true | false | null | null |
diff --git a/bundles/binding/org.openhab.binding.exec/src/main/java/org/openhab/binding/exec/internal/ExecBinding.java b/bundles/binding/org.openhab.binding.exec/src/main/java/org/openhab/binding/exec/internal/ExecBinding.java
index e37fa5be..3b3e94e3 100755
--- a/bundles/binding/org.openhab.binding.exec/src/main/java/org/openhab/binding/exec/internal/ExecBinding.java
+++ b/bundles/binding/org.openhab.binding.exec/src/main/java/org/openhab/binding/exec/internal/ExecBinding.java
@@ -1,421 +1,424 @@
/**
* openHAB, the open Home Automation Bus.
* Copyright (C) 2010-2013, openHAB.org <[email protected]>
*
* See the contributors.txt file in the distribution for a
* full listing of individual contributors.
*
* 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>.
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or
* combining it with Eclipse (or a modified version of that library),
* containing parts covered by the terms of the Eclipse Public License
* (EPL), the licensors of this Program grant you additional permission
* to convey the resulting work.
*/
package org.openhab.binding.exec.internal;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import org.apache.commons.exec.CommandLine;
+import org.apache.commons.exec.DefaultExecuteResultHandler;
+import org.apache.commons.exec.DefaultExecutor;
+import org.apache.commons.exec.ExecuteException;
+import org.apache.commons.exec.ExecuteWatchdog;
+import org.apache.commons.exec.Executor;
+import org.apache.commons.exec.PumpStreamHandler;
+import org.apache.commons.lang.StringUtils;
import org.openhab.binding.exec.ExecBindingProvider;
import org.openhab.core.binding.AbstractActiveBinding;
import org.openhab.core.items.Item;
import org.openhab.core.library.items.ContactItem;
import org.openhab.core.library.items.NumberItem;
+import org.openhab.core.library.items.RollershutterItem;
import org.openhab.core.library.items.SwitchItem;
import org.openhab.core.library.types.DecimalType;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.library.types.OpenClosedType;
+import org.openhab.core.library.types.PercentType;
import org.openhab.core.library.types.StringType;
import org.openhab.core.transform.TransformationException;
import org.openhab.core.transform.TransformationHelper;
import org.openhab.core.transform.TransformationService;
import org.openhab.core.types.Command;
import org.openhab.core.types.State;
import org.openhab.core.types.TypeParser;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-
//import sun.tools.jar.CommandLine;
-import org.apache.commons.exec.CommandLine;
-import org.apache.commons.exec.DefaultExecuteResultHandler;
-import org.apache.commons.exec.DefaultExecutor;
-import org.apache.commons.exec.ExecuteException;
-import org.apache.commons.exec.ExecuteWatchdog;
-import org.apache.commons.exec.Executor;
-import org.apache.commons.exec.PumpStreamHandler;
-import org.apache.commons.lang.StringUtils;
/**
* The swiss army knife binding which executes given commands on the commandline.
* It could act as the opposite of WoL and sends the shutdown command to servers.
* Or switches of WLAN connectivity if a scene "sleeping" is activated.
* <p>
* <i>Note</i>: when using 'ssh' you should use private key authorization since
* the password cannot be read from commandline. The given user should have the
* necessary permissions.
*
* @author Thomas.Eichstaedt-Engelen
* @author Pauli Anttila
* @since 0.6.0
*/
public class ExecBinding extends AbstractActiveBinding<ExecBindingProvider> implements ManagedService {
private static final Logger logger = LoggerFactory.getLogger(ExecBinding.class);
protected static final Command WILDCARD_COMMAND_KEY = StringType.valueOf("*");
private static final String CMD_LINE_DELIMITER = "@@";
/** the timeout for executing command (defaults to 60000 milliseconds) */
private int timeout = 60000;
/** the interval to find new refresh candidates (defaults to 1000 milliseconds)*/
private int granularity = 1000;
private Map<String, Long> lastUpdateMap = new HashMap<String, Long>();
/** RegEx to extract a parse a function String <code>'(.*?)\((.*)\)'</code> */
private static final Pattern EXTRACT_FUNCTION_PATTERN = Pattern.compile("(.*?)\\((.*)\\)");
@Override
protected boolean isProperlyConfigured() {
return true;
}
@Override
protected long getRefreshInterval() {
return granularity;
}
@Override
protected String getName() {
return "Exec Refresh Service";
}
public void execute() {
for (ExecBindingProvider provider : providers) {
for (String itemName : provider.getInBindingItemNames()) {
String commandLine = provider.getCommandLine(itemName);
int refreshInterval = provider.getRefreshInterval(itemName);
String transformation = provider.getTransformation(itemName);
Long lastUpdateTimeStamp = lastUpdateMap.get(itemName);
if (lastUpdateTimeStamp == null) {
lastUpdateTimeStamp = 0L;
}
long age = System.currentTimeMillis() - lastUpdateTimeStamp;
boolean needsUpdate = age >= refreshInterval;
if (needsUpdate) {
logger.debug("item '{}' is about to be refreshed now", itemName);
commandLine = String.format(commandLine, Calendar.getInstance().getTime(), "", itemName);
String response = executeCommandAndWaitResponse(commandLine);
if(response==null) {
logger.error("No response received from command '{}'", commandLine);
} else {
String transformedResponse;
try {
String[] parts = splitTransformationConfig(transformation);
String transformationType = parts[0];
String transformationFunction = parts[1];
TransformationService transformationService =
TransformationHelper.getTransformationService(ExecActivator.getContext(), transformationType);
if (transformationService != null) {
transformedResponse = transformationService.transform(transformationFunction, response);
} else {
transformedResponse = response;
logger.warn("couldn't transform response because transformationService of type '{}' is unavailable", transformationType);
}
}
catch (TransformationException te) {
logger.error("transformation throws exception [transformation="
+ transformation + ", response=" + response + "]", te);
// in case of an error we return the response without any
// transformation
transformedResponse = response;
}
logger.debug("transformed response is '{}'", transformedResponse);
Class<? extends Item> itemType = provider.getItemType(itemName);
State state = createState(itemType, transformedResponse);
if (state != null) {
eventPublisher.postUpdate(itemName, state);
}
}
lastUpdateMap.put(itemName, System.currentTimeMillis());
}
}
}
}
/**
* Splits a transformation configuration string into its two parts - the
* transformation type and the function/pattern to apply.
*
* @param transformation the string to split
* @return a string array with exactly two entries for the type and the function
*/
protected String[] splitTransformationConfig(String transformation) {
Matcher matcher = EXTRACT_FUNCTION_PATTERN.matcher(transformation);
if (!matcher.matches()) {
throw new IllegalArgumentException("given transformation function '" + transformation + "' does not follow the expected pattern '<function>(<pattern>)'");
}
matcher.reset();
matcher.find();
String type = matcher.group(1);
String pattern = matcher.group(2);
return new String[] { type, pattern };
}
/**
* Returns a {@link State} which is inherited from the {@link Item}s
* accepted DataTypes. The call is delegated to the {@link TypeParser}. If
* <code>item</code> is <code>null</code> the {@link StringType} is used.
*
* @param itemType
* @param transformedResponse
*
* @return a {@link State} which type is inherited by the {@link TypeParser}
* or a {@link StringType} if <code>item</code> is <code>null</code>
*/
private State createState(Class<? extends Item> itemType, String transformedResponse) {
try {
if (itemType.isAssignableFrom(NumberItem.class)) {
return DecimalType.valueOf(transformedResponse);
} else if (itemType.isAssignableFrom(ContactItem.class)) {
return OpenClosedType.valueOf(transformedResponse);
} else if (itemType.isAssignableFrom(SwitchItem.class)) {
return OnOffType.valueOf(transformedResponse);
+ } else if (itemType.isAssignableFrom(RollershutterItem.class)) {
+ return PercentType.valueOf(transformedResponse);
} else {
return StringType.valueOf(transformedResponse);
}
} catch (Exception e) {
logger.debug("Couldn't create state of type '{}' for value '{}'", itemType, transformedResponse);
return StringType.valueOf(transformedResponse);
}
}
/**
* @{inheritDoc}
*/
@Override
public void internalReceiveCommand(String itemName, Command command) {
ExecBindingProvider provider =
findFirstMatchingBindingProvider(itemName, command);
if (provider == null) {
logger.warn("doesn't find matching binding provider [itemName={}, command={}]", itemName, command);
return;
}
String commandLine = provider.getCommandLine(itemName, command);
// fallback
if (commandLine == null) {
commandLine = provider.getCommandLine(itemName, WILDCARD_COMMAND_KEY);
}
if (commandLine != null && !commandLine.isEmpty()) {
commandLine = String.format(commandLine, Calendar.getInstance().getTime(), command, itemName);
executeCommand(commandLine);
}
}
/**
* Find the first matching {@link ExecBindingProvider} according to
* <code>itemName</code> and <code>command</code>. If no direct match is
* found, a second match is issued with wilcard-command '*'.
*
* @param itemName
* @param command
*
* @return the matching binding provider or <code>null</code> if no binding
* provider could be found
*/
private ExecBindingProvider findFirstMatchingBindingProvider(String itemName, Command command) {
ExecBindingProvider firstMatchingProvider = null;
for (ExecBindingProvider provider : this.providers) {
String commandLine = provider.getCommandLine(itemName, command);
if (commandLine != null) {
firstMatchingProvider = provider;
break;
}
}
// we didn't find an exact match. probably one configured a fallback
// command?
if (firstMatchingProvider == null) {
for (ExecBindingProvider provider : this.providers) {
String commandLine = provider.getCommandLine(itemName, WILDCARD_COMMAND_KEY);
if (commandLine != null) {
firstMatchingProvider = provider;
break;
}
}
}
return firstMatchingProvider;
}
/**
* <p>Executes <code>commandLine</code>. Sometimes (especially observed on
* MacOS) the commandLine isn't executed properly. In that cases another
* exec-method is to be used. To accomplish this please use the special
* delimiter '<code>@@</code>'. If <code>commandLine</code> contains this
* delimiter it is split into a String[] array and the special exec-method
* is used.</p>
* <p>A possible {@link IOException} gets logged but no further processing is
* done.</p>
*
* @param commandLine the command line to execute
* @see http://www.peterfriese.de/running-applescript-from-java/
*/
private void executeCommand(String commandLine) {
try {
if (commandLine.contains(CMD_LINE_DELIMITER)) {
String[] cmdArray = commandLine.split(CMD_LINE_DELIMITER);
Runtime.getRuntime().exec(cmdArray);
logger.info("executed commandLine '{}'", Arrays.asList(cmdArray));
} else {
Runtime.getRuntime().exec(commandLine);
logger.info("executed commandLine '{}'", commandLine);
}
}
catch (IOException e) {
logger.error("couldn't execute commandLine '" + commandLine + "'", e);
}
}
/**
* <p>Executes <code>commandLine</code>. Sometimes (especially observed on
* MacOS) the commandLine isn't executed properly. In that cases another
* exec-method is to be used. To accomplish this please use the special
* delimiter '<code>@@</code>'. If <code>commandLine</code> contains this
* delimiter it is split into a String[] array and the special exec-method
* is used.</p>
* <p>A possible {@link IOException} gets logged but no further processing is
* done.</p>
*
* @param commandLine the command line to execute
* @return response data from executed command line
*/
private String executeCommandAndWaitResponse(String commandLine) {
String retval = null;
CommandLine cmdLine = null;
if (commandLine.contains(CMD_LINE_DELIMITER)) {
String[] cmdArray = commandLine.split(CMD_LINE_DELIMITER);
cmdLine = new CommandLine(cmdArray[0]);
for (int i = 1; i < cmdArray.length; i++) {
cmdLine.addArgument(cmdArray[i], false);
}
} else {
cmdLine = CommandLine.parse(commandLine);
}
DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
Executor executor = new DefaultExecutor();
ByteArrayOutputStream stdout = new ByteArrayOutputStream();
PumpStreamHandler streamHandler = new PumpStreamHandler(stdout);
executor.setExitValue(1);
executor.setStreamHandler(streamHandler);
executor.setWatchdog(watchdog);
try {
executor.execute(cmdLine, resultHandler);
logger.debug("executed commandLine '{}'", commandLine);
} catch (ExecuteException e) {
logger.error("couldn't execute commandLine '" + commandLine + "'", e);
} catch (IOException e) {
logger.error("couldn't execute commandLine '" + commandLine + "'", e);
}
// some time later the result handler callback was invoked so we
// can safely request the exit code
try {
resultHandler.waitFor();
int exitCode = resultHandler.getExitValue();
retval = StringUtils.chomp(stdout.toString());
logger.debug("exit code '{}', result '{}'", exitCode, retval);
} catch (InterruptedException e) {
logger.error("Timeout occured when executing commandLine '" + commandLine + "'", e);
}
return retval;
}
@Override
@SuppressWarnings("rawtypes")
public void updated(Dictionary config) throws ConfigurationException {
if (config != null) {
String timeoutString = (String) config.get("timeout");
if (StringUtils.isNotBlank(timeoutString)) {
timeout = Integer.parseInt(timeoutString);
}
String granularityString = (String) config.get("granularity");
if (StringUtils.isNotBlank(granularityString)) {
granularity = Integer.parseInt(granularityString);
}
}
}
}
diff --git a/bundles/binding/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/HttpBinding.java b/bundles/binding/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/HttpBinding.java
index e31d1c9d..8de6dfae 100644
--- a/bundles/binding/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/HttpBinding.java
+++ b/bundles/binding/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/HttpBinding.java
@@ -1,327 +1,331 @@
/**
* openHAB, the open Home Automation Bus.
* Copyright (C) 2010-2013, openHAB.org <[email protected]>
*
* See the contributors.txt file in the distribution for a
* full listing of individual contributors.
*
* 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>.
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or
* combining it with Eclipse (or a modified version of that library),
* containing parts covered by the terms of the Eclipse Public License
* (EPL), the licensors of this Program grant you additional permission
* to convey the resulting work.
*/
package org.openhab.binding.http.internal;
import static org.apache.commons.lang.StringUtils.isNotBlank;
import static org.openhab.binding.http.internal.HttpGenericBindingProvider.CHANGED_COMMAND_KEY;
import java.util.Calendar;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.openhab.binding.http.HttpBindingProvider;
import org.openhab.core.binding.AbstractActiveBinding;
import org.openhab.core.items.Item;
import org.openhab.core.library.items.ContactItem;
import org.openhab.core.library.items.NumberItem;
+import org.openhab.core.library.items.RollershutterItem;
import org.openhab.core.library.items.SwitchItem;
import org.openhab.core.library.types.DecimalType;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.library.types.OpenClosedType;
+import org.openhab.core.library.types.PercentType;
import org.openhab.core.library.types.StringType;
import org.openhab.core.transform.TransformationException;
import org.openhab.core.transform.TransformationHelper;
import org.openhab.core.transform.TransformationService;
import org.openhab.core.types.Command;
import org.openhab.core.types.State;
import org.openhab.core.types.Type;
import org.openhab.core.types.TypeParser;
import org.openhab.io.net.http.HttpUtil;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An active binding which requests a given URL frequently.
*
* @author Thomas.Eichstaedt-Engelen
* @author Kai Kreuzer
* @since 0.6.0
*/
public class HttpBinding extends AbstractActiveBinding<HttpBindingProvider> implements ManagedService {
static final Logger logger = LoggerFactory.getLogger(HttpBinding.class);
/** the timeout to use for connecting to a given host (defaults to 5000 milliseconds) */
private int timeout = 5000;
/** the interval to find new refresh candidates (defaults to 1000 milliseconds)*/
private int granularity = 1000;
private Map<String, Long> lastUpdateMap = new HashMap<String, Long>();
/** RegEx to extract a parse a function String <code>'(.*?)\((.*)\)'</code> */
private static final Pattern EXTRACT_FUNCTION_PATTERN = Pattern.compile("(.*?)\\((.*)\\)");
public HttpBinding() {
}
/**
* @{inheritDoc}
*/
@Override
protected long getRefreshInterval() {
return granularity;
}
@Override
protected String getName() {
return "HTTP Refresh Service";
}
/**
* @{inheritDoc}
*/
@Override
protected void internalReceiveUpdate(String itemName, State newState) {
formatAndExecute(itemName, CHANGED_COMMAND_KEY, newState);
}
/**
* @{inheritDoc}
*/
@Override
public void internalReceiveCommand(String itemName, Command command) {
formatAndExecute(itemName, command, command);
}
/**
* @{inheritDoc}
*/
@Override
public boolean isProperlyConfigured() {
return true;
}
/**
* @{inheritDoc}
*/
@Override
public void execute() {
for (HttpBindingProvider provider : providers) {
for (String itemName : provider.getInBindingItemNames()) {
String url = provider.getUrl(itemName);
url = String.format(url, Calendar.getInstance().getTime());
Properties headers = provider.getHttpHeaders(itemName);
int refreshInterval = provider.getRefreshInterval(itemName);
String transformation = provider.getTransformation(itemName);
Long lastUpdateTimeStamp = lastUpdateMap.get(itemName);
if (lastUpdateTimeStamp == null) {
lastUpdateTimeStamp = 0L;
}
long age = System.currentTimeMillis() - lastUpdateTimeStamp;
boolean needsUpdate = age >= refreshInterval;
if (needsUpdate) {
logger.debug("item '{}' is about to be refreshed now", itemName);
String response = HttpUtil.executeUrl("GET", url, headers, null, null, timeout);
if(response==null) {
logger.error("No response received from '{}'", url);
} else {
String transformedResponse;
try {
String[] parts = splitTransformationConfig(transformation);
String transformationType = parts[0];
String transformationFunction = parts[1];
TransformationService transformationService =
TransformationHelper.getTransformationService(HttpActivator.getContext(), transformationType);
if (transformationService != null) {
transformedResponse = transformationService.transform(transformationFunction, response);
} else {
transformedResponse = response;
logger.warn("couldn't transform response because transformationService of type '{}' is unavailable", transformationType);
}
}
catch (TransformationException te) {
logger.error("transformation throws exception [transformation="
+ transformation + ", response=" + response + "]", te);
// in case of an error we return the response without any
// transformation
transformedResponse = response;
}
logger.debug("transformed response is '{}'", transformedResponse);
Class<? extends Item> itemType = provider.getItemType(itemName);
State state = createState(itemType, transformedResponse);
if (state != null) {
eventPublisher.postUpdate(itemName, state);
}
}
lastUpdateMap.put(itemName, System.currentTimeMillis());
}
}
}
}
/**
* Splits a transformation configuration string into its two parts - the
* transformation type and the function/pattern to apply.
*
* @param transformation the string to split
* @return a string array with exactly two entries for the type and the function
*/
protected String[] splitTransformationConfig(String transformation) {
Matcher matcher = EXTRACT_FUNCTION_PATTERN.matcher(transformation);
if (!matcher.matches()) {
throw new IllegalArgumentException("given transformation function '" + transformation + "' does not follow the expected pattern '<function>(<pattern>)'");
}
matcher.reset();
matcher.find();
String type = matcher.group(1);
String pattern = matcher.group(2);
return new String[] { type, pattern };
}
/**
* Returns a {@link State} which is inherited from the {@link Item}s
* accepted DataTypes. The call is delegated to the {@link TypeParser}. If
* <code>item</code> is <code>null</code> the {@link StringType} is used.
*
* @param itemType
* @param transformedResponse
*
* @return a {@link State} which type is inherited by the {@link TypeParser}
* or a {@link StringType} if <code>item</code> is <code>null</code>
*/
private State createState(Class<? extends Item> itemType, String transformedResponse) {
try {
if (itemType.isAssignableFrom(NumberItem.class)) {
return DecimalType.valueOf(transformedResponse);
} else if (itemType.isAssignableFrom(ContactItem.class)) {
return OpenClosedType.valueOf(transformedResponse);
} else if (itemType.isAssignableFrom(SwitchItem.class)) {
return OnOffType.valueOf(transformedResponse);
+ } else if (itemType.isAssignableFrom(RollershutterItem.class)) {
+ return PercentType.valueOf(transformedResponse);
} else {
return StringType.valueOf(transformedResponse);
}
} catch (Exception e) {
logger.debug("Couldn't create state of type '{}' for value '{}'", itemType, transformedResponse);
return StringType.valueOf(transformedResponse);
}
}
/**
* Finds the corresponding binding provider, replaces formatting markers
* in the url (@see java.util.Formatter for further information) and executes
* the formatted url.
*
* @param itemName the item context
* @param command the executed command or one of the virtual commands
* (see {@link HttpGenericBindingProvider})
* @param value the value to be used by the String.format method
*/
private void formatAndExecute(String itemName, Command command, Type value) {
HttpBindingProvider provider =
findFirstMatchingBindingProvider(itemName, command);
if (provider == null) {
logger.trace("doesn't find matching binding provider [itemName={}, command={}]", itemName, command);
return;
}
String httpMethod = provider.getHttpMethod(itemName, command);
String url = provider.getUrl(itemName, command);
url = String.format(url, Calendar.getInstance().getTime(), value);
if (isNotBlank(httpMethod) && isNotBlank(url)) {
HttpUtil.executeUrl(httpMethod, url, provider.getHttpHeaders(itemName, command), null, null, timeout);
}
}
/**
* Find the first matching {@link HttpBindingProvider} according to
* <code>itemName</code> and <code>command</code>.
*
* @param itemName
* @param command
*
* @return the matching binding provider or <code>null</code> if no binding
* provider could be found
*/
private HttpBindingProvider findFirstMatchingBindingProvider(String itemName, Command command) {
HttpBindingProvider firstMatchingProvider = null;
for (HttpBindingProvider provider : this.providers) {
String url = provider.getUrl(itemName, command);
if (url != null) {
firstMatchingProvider = provider;
break;
}
}
return firstMatchingProvider;
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("rawtypes")
public void updated(Dictionary config) throws ConfigurationException {
if (config != null) {
String timeoutString = (String) config.get("timeout");
if (StringUtils.isNotBlank(timeoutString)) {
timeout = Integer.parseInt(timeoutString);
}
String granularityString = (String) config.get("granularity");
if (StringUtils.isNotBlank(granularityString)) {
granularity = Integer.parseInt(granularityString);
}
}
}
}
| false | false | null | null |
diff --git a/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc17/SVNCommitter17.java b/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc17/SVNCommitter17.java
index 6df75eb75..6abcc2b0f 100644
--- a/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc17/SVNCommitter17.java
+++ b/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc17/SVNCommitter17.java
@@ -1,401 +1,401 @@
/*
* ====================================================================
* Copyright (c) 2004-2011 TMate Software Ltd. All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://svnkit.com/license.html.
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
* ====================================================================
*/
package org.tmatesoft.svn.core.internal.wc17;
import java.io.File;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import org.tmatesoft.svn.core.SVNCommitInfo;
import org.tmatesoft.svn.core.SVNErrorCode;
import org.tmatesoft.svn.core.SVNErrorMessage;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNNodeKind;
import org.tmatesoft.svn.core.SVNProperties;
import org.tmatesoft.svn.core.SVNProperty;
import org.tmatesoft.svn.core.SVNPropertyValue;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.internal.wc.ISVNCommitPathHandler;
import org.tmatesoft.svn.core.internal.wc.SVNCommitUtil;
import org.tmatesoft.svn.core.internal.wc.SVNErrorManager;
import org.tmatesoft.svn.core.internal.wc.SVNEventFactory;
import org.tmatesoft.svn.core.internal.wc.SVNFileUtil;
import org.tmatesoft.svn.core.internal.wc.admin.SVNChecksumInputStream;
import org.tmatesoft.svn.core.internal.wc.admin.SVNChecksumOutputStream;
import org.tmatesoft.svn.core.internal.wc17.SVNWCContext.PristineContentsInfo;
import org.tmatesoft.svn.core.internal.wc17.SVNWCContext.WritableBaseInfo;
import org.tmatesoft.svn.core.internal.wc17.db.ISVNWCDb.WCDbInfo.InfoField;
import org.tmatesoft.svn.core.io.ISVNEditor;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.diff.SVNDeltaGenerator;
import org.tmatesoft.svn.core.wc.ISVNEventHandler;
import org.tmatesoft.svn.core.wc.SVNEvent;
import org.tmatesoft.svn.core.wc.SVNEventAction;
import org.tmatesoft.svn.core.wc.SVNStatusType;
import org.tmatesoft.svn.core.wc2.SvnChecksum;
import org.tmatesoft.svn.core.wc2.SvnCommitItem;
import org.tmatesoft.svn.util.SVNLogType;
/**
* @version 1.4
* @author TMate Software Ltd.
*/
public class SVNCommitter17 implements ISVNCommitPathHandler {
private SVNWCContext myContext;
private Map<String, SvnCommitItem> myCommittables;
private SVNURL myRepositoryRoot;
private Map<File, SvnChecksum> myMd5Checksums;
private Map<File, SvnChecksum> mySha1Checksums;
private Map<String, SvnCommitItem> myModifiedFiles;
private SVNDeltaGenerator myDeltaGenerator;
private SVNCommitter17(SVNWCContext context, Map<String, SvnCommitItem> committables, SVNURL repositoryRoot, Collection<File> tmpFiles, Map<File, SvnChecksum> md5Checksums,
Map<File, SvnChecksum> sha1Checksums) {
myContext = context;
myCommittables = committables;
myRepositoryRoot = repositoryRoot;
myMd5Checksums = md5Checksums;
mySha1Checksums = sha1Checksums;
myModifiedFiles = new TreeMap<String, SvnCommitItem>();
}
public static SVNCommitInfo commit(SVNWCContext context, Collection<File> tmpFiles, Map<String, SvnCommitItem> committables, SVNURL repositoryRoot, ISVNEditor commitEditor,
Map<File, SvnChecksum> md5Checksums, Map<File, SvnChecksum> sha1Checksums) throws SVNException {
SVNCommitter17 committer = new SVNCommitter17(context, committables, repositoryRoot, tmpFiles, md5Checksums, sha1Checksums);
SVNCommitUtil.driveCommitEditor(committer, committables.keySet(), commitEditor, -1);
committer.sendTextDeltas(commitEditor);
return commitEditor.closeEdit();
}
public boolean handleCommitPath(String commitPath, ISVNEditor commitEditor) throws SVNException {
SvnCommitItem item = myCommittables.get(commitPath);
myContext.checkCancelled();
if (item.hasFlag(SvnCommitItem.COPY)) {
if (item.getCopyFromUrl() == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.BAD_URL, "Commit item ''{0}'' has copy flag but no copyfrom URL", item.getPath());
SVNErrorManager.error(err, SVNLogType.WC);
} else if (item.getCopyFromRevision() < 0) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_BAD_REVISION, "Commit item ''{0}'' has copy flag but an invalid revision", item.getPath());
SVNErrorManager.error(err, SVNLogType.WC);
}
}
boolean closeDir = false;
File localAbspath = null;
if (item.getKind() != SVNNodeKind.NONE && item.getPath() != null) {
localAbspath = item.getPath();
}
long rev = item.getRevision();
SVNEvent event = null;
if (item.hasFlag(SvnCommitItem.ADD) && item.hasFlag(SvnCommitItem.DELETE)) {
event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), null, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_REPLACED, null, null, null);
event.setPreviousRevision(rev);
} else if (item.hasFlag(SvnCommitItem.DELETE)) {
event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), null, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_DELETED, null, null, null);
event.setPreviousRevision(rev);
} else if (item.hasFlag(SvnCommitItem.ADD)) {
String mimeType = null;
if (item.getKind() == SVNNodeKind.FILE && localAbspath != null) {
mimeType = myContext.getProperty(localAbspath, SVNProperty.MIME_TYPE);
}
event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), mimeType, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_ADDED, null, null, null);
event.setPreviousRevision(item.getCopyFromRevision() >= 0 ? item.getCopyFromRevision() : -1);
event.setPreviousURL(item.getCopyFromUrl());
} else if (item.hasFlag(SvnCommitItem.TEXT_MODIFIED) || item.hasFlag(SvnCommitItem.PROPS_MODIFIED)) {
SVNStatusType contentState = SVNStatusType.UNCHANGED;
if (item.hasFlag(SvnCommitItem.TEXT_MODIFIED)) {
contentState = SVNStatusType.CHANGED;
}
SVNStatusType propState = SVNStatusType.UNCHANGED;
if (item.hasFlag(SvnCommitItem.PROPS_MODIFIED) ) {
propState = SVNStatusType.CHANGED;
}
event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), null, SVNRepository.INVALID_REVISION, contentState, propState, null, SVNEventAction.COMMIT_MODIFIED, null, null, null);
event.setPreviousRevision(rev);
}
if (event != null) {
event.setURL(item.getUrl());
if (myContext.getEventHandler() != null) {
myContext.getEventHandler().handleEvent(event, ISVNEventHandler.UNKNOWN);
}
}
if (item.hasFlag(SvnCommitItem.DELETE)) {
try {
commitEditor.deleteEntry(commitPath, rev);
} catch (SVNException e) {
fixError(commitPath, e, SVNNodeKind.FILE);
}
}
long cfRev = item.getCopyFromRevision();
Map<String, SVNPropertyValue> outgoingProperties = item.getOutgoingProperties();
boolean fileOpen = false;
if (item.hasFlag(SvnCommitItem.ADD)) {
String copyFromPath = getCopyFromPath(item.getCopyFromUrl());
if (item.getKind() == SVNNodeKind.FILE) {
commitEditor.addFile(commitPath, copyFromPath, cfRev);
fileOpen = true;
} else {
commitEditor.addDir(commitPath, copyFromPath, cfRev);
closeDir = true;
}
if (outgoingProperties != null) {
for (Iterator<String> propsIter = outgoingProperties.keySet().iterator(); propsIter.hasNext();) {
String propName = propsIter.next();
SVNPropertyValue propValue = outgoingProperties.get(propName);
if (item.getKind() == SVNNodeKind.FILE) {
commitEditor.changeFileProperty(commitPath, propName, propValue);
} else {
commitEditor.changeDirProperty(propName, propValue);
}
}
outgoingProperties = null;
}
}
if (item.hasFlag(SvnCommitItem.PROPS_MODIFIED)) { // || (outgoingProperties != null && !outgoingProperties.isEmpty())) {
if (item.getKind() == SVNNodeKind.FILE) {
if (!fileOpen) {
try {
commitEditor.openFile(commitPath, rev);
} catch (SVNException e) {
fixError(commitPath, e, SVNNodeKind.FILE);
}
}
fileOpen = true;
} else if (!item.hasFlag(SvnCommitItem.ADD)) {
// do not open dir twice.
try {
if ("".equals(commitPath)) {
commitEditor.openRoot(rev);
} else {
commitEditor.openDir(commitPath, rev);
}
} catch (SVNException svne) {
fixError(commitPath, svne, SVNNodeKind.DIR);
}
closeDir = true;
}
if (item.hasFlag(SvnCommitItem.PROPS_MODIFIED)) {
try {
sendPropertiesDelta(localAbspath, commitPath, item, commitEditor);
} catch (SVNException e) {
fixError(commitPath, e, item.getKind());
}
}
if (outgoingProperties != null) {
for (Iterator<String> propsIter = outgoingProperties.keySet().iterator(); propsIter.hasNext();) {
String propName = propsIter.next();
SVNPropertyValue propValue = outgoingProperties.get(propName);
if (item.getKind() == SVNNodeKind.FILE) {
commitEditor.changeFileProperty(commitPath, propName, propValue);
} else {
commitEditor.changeDirProperty(propName, propValue);
}
}
}
}
if (item.hasFlag(SvnCommitItem.TEXT_MODIFIED) && item.getKind() == SVNNodeKind.FILE) {
if (!fileOpen) {
try {
commitEditor.openFile(commitPath, rev);
} catch (SVNException e) {
fixError(commitPath, e, SVNNodeKind.FILE);
}
}
myModifiedFiles.put(commitPath, item);
} else if (fileOpen) {
commitEditor.closeFile(commitPath, null);
}
return closeDir;
}
private void fixError(String path, SVNException e, SVNNodeKind kind) throws SVNException {
SVNErrorMessage err = e.getErrorMessage();
if (err.getErrorCode() == SVNErrorCode.FS_NOT_FOUND || err.getErrorCode() == SVNErrorCode.RA_DAV_PATH_NOT_FOUND) {
err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_UP_TO_DATE, kind == SVNNodeKind.DIR ? "Directory ''{0}'' is out of date" : "File ''{0}'' is out of date", path);
throw new SVNException(err);
}
throw e;
}
private String getCopyFromPath(SVNURL url) {
if (url == null) {
return null;
}
String path = url.getPath();
if (myRepositoryRoot.getPath().equals(path)) {
return "/";
}
return path.substring(myRepositoryRoot.getPath().length());
}
private void sendPropertiesDelta(File localAbspath, String commitPath, SvnCommitItem item, ISVNEditor commitEditor) throws SVNException {
SVNNodeKind kind = myContext.readKind(localAbspath, false);
SVNProperties propMods = myContext.getPropDiffs(localAbspath).propChanges;
for (Object i : propMods.nameSet()) {
String propName = (String) i;
SVNPropertyValue propValue = propMods.getSVNPropertyValue(propName);
if (kind == SVNNodeKind.FILE) {
commitEditor.changeFileProperty(commitPath, propName, propValue);
} else {
commitEditor.changeDirProperty(propName, propValue);
}
}
}
private void sendTextDeltas(ISVNEditor editor) throws SVNException {
for (String path : myModifiedFiles.keySet()) {
SvnCommitItem item = myModifiedFiles.get(path);
myContext.checkCancelled();
File itemAbspath = item.getPath();
if (myContext.getEventHandler() != null) {
SVNEvent event = SVNEventFactory.createSVNEvent(itemAbspath, SVNNodeKind.FILE, null, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_DELTA_SENT, null, null, null);
myContext.getEventHandler().handleEvent(event, ISVNEventHandler.UNKNOWN);
}
boolean fulltext = item.hasFlag(SvnCommitItem.ADD);
TransmittedChecksums transmitTextDeltas = transmitTextDeltas(path, itemAbspath, fulltext, editor);
SvnChecksum newTextBaseMd5Checksum = transmitTextDeltas.md5Checksum;
SvnChecksum newTextBaseSha1Checksum = transmitTextDeltas.sha1Checksum;
if (myMd5Checksums != null) {
myMd5Checksums.put(itemAbspath, newTextBaseMd5Checksum);
}
if (mySha1Checksums != null) {
mySha1Checksums.put(itemAbspath, newTextBaseSha1Checksum);
}
}
}
private static class TransmittedChecksums {
public SvnChecksum md5Checksum;
public SvnChecksum sha1Checksum;
}
private TransmittedChecksums transmitTextDeltas(String path, File localAbspath, boolean fulltext, ISVNEditor editor) throws SVNException {
InputStream localStream = SVNFileUtil.DUMMY_IN;
InputStream baseStream = SVNFileUtil.DUMMY_IN;
SvnChecksum expectedMd5Checksum = null;
SvnChecksum localMd5Checksum = null;
SvnChecksum verifyChecksum = null;
SVNChecksumOutputStream localSha1ChecksumStream = null;
SVNChecksumInputStream verifyChecksumStream = null;
SVNErrorMessage error = null;
File newPristineTmpAbspath = null;
try {
localStream = myContext.getTranslatedStream(localAbspath, localAbspath, true, false);
WritableBaseInfo openWritableBase = myContext.openWritableBase(localAbspath, false, true);
OutputStream newPristineStream = openWritableBase.stream;
newPristineTmpAbspath = openWritableBase.tempBaseAbspath;
localSha1ChecksumStream = openWritableBase.sha1ChecksumStream;
localStream = new CopyingStream(newPristineStream, localStream);
if (!fulltext) {
PristineContentsInfo pristineContents = myContext.getPristineContents(localAbspath, true, true);
File baseFile = pristineContents.path;
baseStream = pristineContents.stream;
if (baseStream == null) {
baseStream = SVNFileUtil.DUMMY_IN;
}
expectedMd5Checksum = myContext.getDb().readInfo(localAbspath, InfoField.checksum).checksum;
if (expectedMd5Checksum != null && expectedMd5Checksum.getKind() != SvnChecksum.Kind.md5) {
expectedMd5Checksum = myContext.getDb().getPristineMD5(localAbspath, expectedMd5Checksum);
}
if (expectedMd5Checksum != null) {
verifyChecksumStream = new SVNChecksumInputStream(baseStream, SVNChecksumInputStream.MD5_ALGORITHM);
baseStream = verifyChecksumStream;
} else {
expectedMd5Checksum = new SvnChecksum(SvnChecksum.Kind.md5, SVNFileUtil.computeChecksum(baseFile));
}
}
editor.applyTextDelta(path, expectedMd5Checksum!=null ? expectedMd5Checksum.getDigest() : null);
if (myDeltaGenerator == null) {
myDeltaGenerator = new SVNDeltaGenerator();
}
localMd5Checksum = new SvnChecksum(SvnChecksum.Kind.md5, myDeltaGenerator.sendDelta(path, baseStream, 0, localStream, editor, true));
if (verifyChecksumStream != null) {
verifyChecksum = new SvnChecksum(SvnChecksum.Kind.md5, verifyChecksumStream.getDigest());
}
} catch (SVNException svne) {
error = svne.getErrorMessage().wrap("While preparing ''{0}'' for commit", localAbspath);
} finally {
SVNFileUtil.closeFile(localStream);
SVNFileUtil.closeFile(baseStream);
}
if (expectedMd5Checksum != null && verifyChecksum != null && !expectedMd5Checksum.equals(verifyChecksum)) {
- SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_CORRUPT_TEXT_BASE, "Checksum mismatch for ''{0}''; expected: ''{1}'', actual: ''{2}''", new Object[] {
+ SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CHECKSUM_MISMATCH, "Checksum mismatch for ''{0}''; expected: ''{1}'', actual: ''{2}''", new Object[] {
localAbspath, expectedMd5Checksum, verifyChecksum
});
SVNErrorManager.error(err, SVNLogType.WC);
}
if (error != null) {
SVNErrorManager.error(error, SVNLogType.WC);
}
editor.closeFile(path, localMd5Checksum!=null ? localMd5Checksum.getDigest() : null);
SvnChecksum localSha1Checksum = new SvnChecksum(SvnChecksum.Kind.sha1, localSha1ChecksumStream.getDigest());
myContext.getDb().installPristine(newPristineTmpAbspath, localSha1Checksum, localMd5Checksum);
TransmittedChecksums result = new TransmittedChecksums();
result.md5Checksum = localMd5Checksum;
result.sha1Checksum = localSha1Checksum;
return result;
}
private class CopyingStream extends FilterInputStream {
private OutputStream myOutput;
public CopyingStream(OutputStream out, InputStream in) {
super(in);
myOutput = out;
}
public int read() throws IOException {
int r = super.read();
if (r != -1) {
myOutput.write(r);
}
return r;
}
public int read(byte[] b) throws IOException {
int r = super.read(b);
if (r != -1) {
myOutput.write(b, 0, r);
}
return r;
}
public int read(byte[] b, int off, int len) throws IOException {
int r = super.read(b, off, len);
if (r != -1) {
myOutput.write(b, off, r);
}
return r;
}
public void close() throws IOException {
try{
myOutput.close();
} finally {
super.close();
}
}
}
}
| true | true | public boolean handleCommitPath(String commitPath, ISVNEditor commitEditor) throws SVNException {
SvnCommitItem item = myCommittables.get(commitPath);
myContext.checkCancelled();
if (item.hasFlag(SvnCommitItem.COPY)) {
if (item.getCopyFromUrl() == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.BAD_URL, "Commit item ''{0}'' has copy flag but no copyfrom URL", item.getPath());
SVNErrorManager.error(err, SVNLogType.WC);
} else if (item.getCopyFromRevision() < 0) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_BAD_REVISION, "Commit item ''{0}'' has copy flag but an invalid revision", item.getPath());
SVNErrorManager.error(err, SVNLogType.WC);
}
}
boolean closeDir = false;
File localAbspath = null;
if (item.getKind() != SVNNodeKind.NONE && item.getPath() != null) {
localAbspath = item.getPath();
}
long rev = item.getRevision();
SVNEvent event = null;
if (item.hasFlag(SvnCommitItem.ADD) && item.hasFlag(SvnCommitItem.DELETE)) {
event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), null, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_REPLACED, null, null, null);
event.setPreviousRevision(rev);
} else if (item.hasFlag(SvnCommitItem.DELETE)) {
event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), null, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_DELETED, null, null, null);
event.setPreviousRevision(rev);
} else if (item.hasFlag(SvnCommitItem.ADD)) {
String mimeType = null;
if (item.getKind() == SVNNodeKind.FILE && localAbspath != null) {
mimeType = myContext.getProperty(localAbspath, SVNProperty.MIME_TYPE);
}
event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), mimeType, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_ADDED, null, null, null);
event.setPreviousRevision(item.getCopyFromRevision() >= 0 ? item.getCopyFromRevision() : -1);
event.setPreviousURL(item.getCopyFromUrl());
} else if (item.hasFlag(SvnCommitItem.TEXT_MODIFIED) || item.hasFlag(SvnCommitItem.PROPS_MODIFIED)) {
SVNStatusType contentState = SVNStatusType.UNCHANGED;
if (item.hasFlag(SvnCommitItem.TEXT_MODIFIED)) {
contentState = SVNStatusType.CHANGED;
}
SVNStatusType propState = SVNStatusType.UNCHANGED;
if (item.hasFlag(SvnCommitItem.PROPS_MODIFIED) ) {
propState = SVNStatusType.CHANGED;
}
event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), null, SVNRepository.INVALID_REVISION, contentState, propState, null, SVNEventAction.COMMIT_MODIFIED, null, null, null);
event.setPreviousRevision(rev);
}
if (event != null) {
event.setURL(item.getUrl());
if (myContext.getEventHandler() != null) {
myContext.getEventHandler().handleEvent(event, ISVNEventHandler.UNKNOWN);
}
}
if (item.hasFlag(SvnCommitItem.DELETE)) {
try {
commitEditor.deleteEntry(commitPath, rev);
} catch (SVNException e) {
fixError(commitPath, e, SVNNodeKind.FILE);
}
}
long cfRev = item.getCopyFromRevision();
Map<String, SVNPropertyValue> outgoingProperties = item.getOutgoingProperties();
boolean fileOpen = false;
if (item.hasFlag(SvnCommitItem.ADD)) {
String copyFromPath = getCopyFromPath(item.getCopyFromUrl());
if (item.getKind() == SVNNodeKind.FILE) {
commitEditor.addFile(commitPath, copyFromPath, cfRev);
fileOpen = true;
} else {
commitEditor.addDir(commitPath, copyFromPath, cfRev);
closeDir = true;
}
if (outgoingProperties != null) {
for (Iterator<String> propsIter = outgoingProperties.keySet().iterator(); propsIter.hasNext();) {
String propName = propsIter.next();
SVNPropertyValue propValue = outgoingProperties.get(propName);
if (item.getKind() == SVNNodeKind.FILE) {
commitEditor.changeFileProperty(commitPath, propName, propValue);
} else {
commitEditor.changeDirProperty(propName, propValue);
}
}
outgoingProperties = null;
}
}
if (item.hasFlag(SvnCommitItem.PROPS_MODIFIED)) { // || (outgoingProperties != null && !outgoingProperties.isEmpty())) {
if (item.getKind() == SVNNodeKind.FILE) {
if (!fileOpen) {
try {
commitEditor.openFile(commitPath, rev);
} catch (SVNException e) {
fixError(commitPath, e, SVNNodeKind.FILE);
}
}
fileOpen = true;
} else if (!item.hasFlag(SvnCommitItem.ADD)) {
// do not open dir twice.
try {
if ("".equals(commitPath)) {
commitEditor.openRoot(rev);
} else {
commitEditor.openDir(commitPath, rev);
}
} catch (SVNException svne) {
fixError(commitPath, svne, SVNNodeKind.DIR);
}
closeDir = true;
}
if (item.hasFlag(SvnCommitItem.PROPS_MODIFIED)) {
try {
sendPropertiesDelta(localAbspath, commitPath, item, commitEditor);
} catch (SVNException e) {
fixError(commitPath, e, item.getKind());
}
}
if (outgoingProperties != null) {
for (Iterator<String> propsIter = outgoingProperties.keySet().iterator(); propsIter.hasNext();) {
String propName = propsIter.next();
SVNPropertyValue propValue = outgoingProperties.get(propName);
if (item.getKind() == SVNNodeKind.FILE) {
commitEditor.changeFileProperty(commitPath, propName, propValue);
} else {
commitEditor.changeDirProperty(propName, propValue);
}
}
}
}
if (item.hasFlag(SvnCommitItem.TEXT_MODIFIED) && item.getKind() == SVNNodeKind.FILE) {
if (!fileOpen) {
try {
commitEditor.openFile(commitPath, rev);
} catch (SVNException e) {
fixError(commitPath, e, SVNNodeKind.FILE);
}
}
myModifiedFiles.put(commitPath, item);
} else if (fileOpen) {
commitEditor.closeFile(commitPath, null);
}
return closeDir;
}
private void fixError(String path, SVNException e, SVNNodeKind kind) throws SVNException {
SVNErrorMessage err = e.getErrorMessage();
if (err.getErrorCode() == SVNErrorCode.FS_NOT_FOUND || err.getErrorCode() == SVNErrorCode.RA_DAV_PATH_NOT_FOUND) {
err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_UP_TO_DATE, kind == SVNNodeKind.DIR ? "Directory ''{0}'' is out of date" : "File ''{0}'' is out of date", path);
throw new SVNException(err);
}
throw e;
}
private String getCopyFromPath(SVNURL url) {
if (url == null) {
return null;
}
String path = url.getPath();
if (myRepositoryRoot.getPath().equals(path)) {
return "/";
}
return path.substring(myRepositoryRoot.getPath().length());
}
private void sendPropertiesDelta(File localAbspath, String commitPath, SvnCommitItem item, ISVNEditor commitEditor) throws SVNException {
SVNNodeKind kind = myContext.readKind(localAbspath, false);
SVNProperties propMods = myContext.getPropDiffs(localAbspath).propChanges;
for (Object i : propMods.nameSet()) {
String propName = (String) i;
SVNPropertyValue propValue = propMods.getSVNPropertyValue(propName);
if (kind == SVNNodeKind.FILE) {
commitEditor.changeFileProperty(commitPath, propName, propValue);
} else {
commitEditor.changeDirProperty(propName, propValue);
}
}
}
private void sendTextDeltas(ISVNEditor editor) throws SVNException {
for (String path : myModifiedFiles.keySet()) {
SvnCommitItem item = myModifiedFiles.get(path);
myContext.checkCancelled();
File itemAbspath = item.getPath();
if (myContext.getEventHandler() != null) {
SVNEvent event = SVNEventFactory.createSVNEvent(itemAbspath, SVNNodeKind.FILE, null, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_DELTA_SENT, null, null, null);
myContext.getEventHandler().handleEvent(event, ISVNEventHandler.UNKNOWN);
}
boolean fulltext = item.hasFlag(SvnCommitItem.ADD);
TransmittedChecksums transmitTextDeltas = transmitTextDeltas(path, itemAbspath, fulltext, editor);
SvnChecksum newTextBaseMd5Checksum = transmitTextDeltas.md5Checksum;
SvnChecksum newTextBaseSha1Checksum = transmitTextDeltas.sha1Checksum;
if (myMd5Checksums != null) {
myMd5Checksums.put(itemAbspath, newTextBaseMd5Checksum);
}
if (mySha1Checksums != null) {
mySha1Checksums.put(itemAbspath, newTextBaseSha1Checksum);
}
}
}
private static class TransmittedChecksums {
public SvnChecksum md5Checksum;
public SvnChecksum sha1Checksum;
}
private TransmittedChecksums transmitTextDeltas(String path, File localAbspath, boolean fulltext, ISVNEditor editor) throws SVNException {
InputStream localStream = SVNFileUtil.DUMMY_IN;
InputStream baseStream = SVNFileUtil.DUMMY_IN;
SvnChecksum expectedMd5Checksum = null;
SvnChecksum localMd5Checksum = null;
SvnChecksum verifyChecksum = null;
SVNChecksumOutputStream localSha1ChecksumStream = null;
SVNChecksumInputStream verifyChecksumStream = null;
SVNErrorMessage error = null;
File newPristineTmpAbspath = null;
try {
localStream = myContext.getTranslatedStream(localAbspath, localAbspath, true, false);
WritableBaseInfo openWritableBase = myContext.openWritableBase(localAbspath, false, true);
OutputStream newPristineStream = openWritableBase.stream;
newPristineTmpAbspath = openWritableBase.tempBaseAbspath;
localSha1ChecksumStream = openWritableBase.sha1ChecksumStream;
localStream = new CopyingStream(newPristineStream, localStream);
if (!fulltext) {
PristineContentsInfo pristineContents = myContext.getPristineContents(localAbspath, true, true);
File baseFile = pristineContents.path;
baseStream = pristineContents.stream;
if (baseStream == null) {
baseStream = SVNFileUtil.DUMMY_IN;
}
expectedMd5Checksum = myContext.getDb().readInfo(localAbspath, InfoField.checksum).checksum;
if (expectedMd5Checksum != null && expectedMd5Checksum.getKind() != SvnChecksum.Kind.md5) {
expectedMd5Checksum = myContext.getDb().getPristineMD5(localAbspath, expectedMd5Checksum);
}
if (expectedMd5Checksum != null) {
verifyChecksumStream = new SVNChecksumInputStream(baseStream, SVNChecksumInputStream.MD5_ALGORITHM);
baseStream = verifyChecksumStream;
} else {
expectedMd5Checksum = new SvnChecksum(SvnChecksum.Kind.md5, SVNFileUtil.computeChecksum(baseFile));
}
}
editor.applyTextDelta(path, expectedMd5Checksum!=null ? expectedMd5Checksum.getDigest() : null);
if (myDeltaGenerator == null) {
myDeltaGenerator = new SVNDeltaGenerator();
}
localMd5Checksum = new SvnChecksum(SvnChecksum.Kind.md5, myDeltaGenerator.sendDelta(path, baseStream, 0, localStream, editor, true));
if (verifyChecksumStream != null) {
verifyChecksum = new SvnChecksum(SvnChecksum.Kind.md5, verifyChecksumStream.getDigest());
}
} catch (SVNException svne) {
error = svne.getErrorMessage().wrap("While preparing ''{0}'' for commit", localAbspath);
} finally {
SVNFileUtil.closeFile(localStream);
SVNFileUtil.closeFile(baseStream);
}
if (expectedMd5Checksum != null && verifyChecksum != null && !expectedMd5Checksum.equals(verifyChecksum)) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_CORRUPT_TEXT_BASE, "Checksum mismatch for ''{0}''; expected: ''{1}'', actual: ''{2}''", new Object[] {
localAbspath, expectedMd5Checksum, verifyChecksum
});
SVNErrorManager.error(err, SVNLogType.WC);
}
if (error != null) {
SVNErrorManager.error(error, SVNLogType.WC);
}
editor.closeFile(path, localMd5Checksum!=null ? localMd5Checksum.getDigest() : null);
SvnChecksum localSha1Checksum = new SvnChecksum(SvnChecksum.Kind.sha1, localSha1ChecksumStream.getDigest());
myContext.getDb().installPristine(newPristineTmpAbspath, localSha1Checksum, localMd5Checksum);
TransmittedChecksums result = new TransmittedChecksums();
result.md5Checksum = localMd5Checksum;
result.sha1Checksum = localSha1Checksum;
return result;
}
private class CopyingStream extends FilterInputStream {
private OutputStream myOutput;
public CopyingStream(OutputStream out, InputStream in) {
super(in);
myOutput = out;
}
public int read() throws IOException {
int r = super.read();
if (r != -1) {
myOutput.write(r);
}
return r;
}
public int read(byte[] b) throws IOException {
int r = super.read(b);
if (r != -1) {
myOutput.write(b, 0, r);
}
return r;
}
public int read(byte[] b, int off, int len) throws IOException {
int r = super.read(b, off, len);
if (r != -1) {
myOutput.write(b, off, r);
}
return r;
}
public void close() throws IOException {
try{
myOutput.close();
} finally {
super.close();
}
}
}
}
| public boolean handleCommitPath(String commitPath, ISVNEditor commitEditor) throws SVNException {
SvnCommitItem item = myCommittables.get(commitPath);
myContext.checkCancelled();
if (item.hasFlag(SvnCommitItem.COPY)) {
if (item.getCopyFromUrl() == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.BAD_URL, "Commit item ''{0}'' has copy flag but no copyfrom URL", item.getPath());
SVNErrorManager.error(err, SVNLogType.WC);
} else if (item.getCopyFromRevision() < 0) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_BAD_REVISION, "Commit item ''{0}'' has copy flag but an invalid revision", item.getPath());
SVNErrorManager.error(err, SVNLogType.WC);
}
}
boolean closeDir = false;
File localAbspath = null;
if (item.getKind() != SVNNodeKind.NONE && item.getPath() != null) {
localAbspath = item.getPath();
}
long rev = item.getRevision();
SVNEvent event = null;
if (item.hasFlag(SvnCommitItem.ADD) && item.hasFlag(SvnCommitItem.DELETE)) {
event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), null, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_REPLACED, null, null, null);
event.setPreviousRevision(rev);
} else if (item.hasFlag(SvnCommitItem.DELETE)) {
event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), null, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_DELETED, null, null, null);
event.setPreviousRevision(rev);
} else if (item.hasFlag(SvnCommitItem.ADD)) {
String mimeType = null;
if (item.getKind() == SVNNodeKind.FILE && localAbspath != null) {
mimeType = myContext.getProperty(localAbspath, SVNProperty.MIME_TYPE);
}
event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), mimeType, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_ADDED, null, null, null);
event.setPreviousRevision(item.getCopyFromRevision() >= 0 ? item.getCopyFromRevision() : -1);
event.setPreviousURL(item.getCopyFromUrl());
} else if (item.hasFlag(SvnCommitItem.TEXT_MODIFIED) || item.hasFlag(SvnCommitItem.PROPS_MODIFIED)) {
SVNStatusType contentState = SVNStatusType.UNCHANGED;
if (item.hasFlag(SvnCommitItem.TEXT_MODIFIED)) {
contentState = SVNStatusType.CHANGED;
}
SVNStatusType propState = SVNStatusType.UNCHANGED;
if (item.hasFlag(SvnCommitItem.PROPS_MODIFIED) ) {
propState = SVNStatusType.CHANGED;
}
event = SVNEventFactory.createSVNEvent(localAbspath, item.getKind(), null, SVNRepository.INVALID_REVISION, contentState, propState, null, SVNEventAction.COMMIT_MODIFIED, null, null, null);
event.setPreviousRevision(rev);
}
if (event != null) {
event.setURL(item.getUrl());
if (myContext.getEventHandler() != null) {
myContext.getEventHandler().handleEvent(event, ISVNEventHandler.UNKNOWN);
}
}
if (item.hasFlag(SvnCommitItem.DELETE)) {
try {
commitEditor.deleteEntry(commitPath, rev);
} catch (SVNException e) {
fixError(commitPath, e, SVNNodeKind.FILE);
}
}
long cfRev = item.getCopyFromRevision();
Map<String, SVNPropertyValue> outgoingProperties = item.getOutgoingProperties();
boolean fileOpen = false;
if (item.hasFlag(SvnCommitItem.ADD)) {
String copyFromPath = getCopyFromPath(item.getCopyFromUrl());
if (item.getKind() == SVNNodeKind.FILE) {
commitEditor.addFile(commitPath, copyFromPath, cfRev);
fileOpen = true;
} else {
commitEditor.addDir(commitPath, copyFromPath, cfRev);
closeDir = true;
}
if (outgoingProperties != null) {
for (Iterator<String> propsIter = outgoingProperties.keySet().iterator(); propsIter.hasNext();) {
String propName = propsIter.next();
SVNPropertyValue propValue = outgoingProperties.get(propName);
if (item.getKind() == SVNNodeKind.FILE) {
commitEditor.changeFileProperty(commitPath, propName, propValue);
} else {
commitEditor.changeDirProperty(propName, propValue);
}
}
outgoingProperties = null;
}
}
if (item.hasFlag(SvnCommitItem.PROPS_MODIFIED)) { // || (outgoingProperties != null && !outgoingProperties.isEmpty())) {
if (item.getKind() == SVNNodeKind.FILE) {
if (!fileOpen) {
try {
commitEditor.openFile(commitPath, rev);
} catch (SVNException e) {
fixError(commitPath, e, SVNNodeKind.FILE);
}
}
fileOpen = true;
} else if (!item.hasFlag(SvnCommitItem.ADD)) {
// do not open dir twice.
try {
if ("".equals(commitPath)) {
commitEditor.openRoot(rev);
} else {
commitEditor.openDir(commitPath, rev);
}
} catch (SVNException svne) {
fixError(commitPath, svne, SVNNodeKind.DIR);
}
closeDir = true;
}
if (item.hasFlag(SvnCommitItem.PROPS_MODIFIED)) {
try {
sendPropertiesDelta(localAbspath, commitPath, item, commitEditor);
} catch (SVNException e) {
fixError(commitPath, e, item.getKind());
}
}
if (outgoingProperties != null) {
for (Iterator<String> propsIter = outgoingProperties.keySet().iterator(); propsIter.hasNext();) {
String propName = propsIter.next();
SVNPropertyValue propValue = outgoingProperties.get(propName);
if (item.getKind() == SVNNodeKind.FILE) {
commitEditor.changeFileProperty(commitPath, propName, propValue);
} else {
commitEditor.changeDirProperty(propName, propValue);
}
}
}
}
if (item.hasFlag(SvnCommitItem.TEXT_MODIFIED) && item.getKind() == SVNNodeKind.FILE) {
if (!fileOpen) {
try {
commitEditor.openFile(commitPath, rev);
} catch (SVNException e) {
fixError(commitPath, e, SVNNodeKind.FILE);
}
}
myModifiedFiles.put(commitPath, item);
} else if (fileOpen) {
commitEditor.closeFile(commitPath, null);
}
return closeDir;
}
private void fixError(String path, SVNException e, SVNNodeKind kind) throws SVNException {
SVNErrorMessage err = e.getErrorMessage();
if (err.getErrorCode() == SVNErrorCode.FS_NOT_FOUND || err.getErrorCode() == SVNErrorCode.RA_DAV_PATH_NOT_FOUND) {
err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_UP_TO_DATE, kind == SVNNodeKind.DIR ? "Directory ''{0}'' is out of date" : "File ''{0}'' is out of date", path);
throw new SVNException(err);
}
throw e;
}
private String getCopyFromPath(SVNURL url) {
if (url == null) {
return null;
}
String path = url.getPath();
if (myRepositoryRoot.getPath().equals(path)) {
return "/";
}
return path.substring(myRepositoryRoot.getPath().length());
}
private void sendPropertiesDelta(File localAbspath, String commitPath, SvnCommitItem item, ISVNEditor commitEditor) throws SVNException {
SVNNodeKind kind = myContext.readKind(localAbspath, false);
SVNProperties propMods = myContext.getPropDiffs(localAbspath).propChanges;
for (Object i : propMods.nameSet()) {
String propName = (String) i;
SVNPropertyValue propValue = propMods.getSVNPropertyValue(propName);
if (kind == SVNNodeKind.FILE) {
commitEditor.changeFileProperty(commitPath, propName, propValue);
} else {
commitEditor.changeDirProperty(propName, propValue);
}
}
}
private void sendTextDeltas(ISVNEditor editor) throws SVNException {
for (String path : myModifiedFiles.keySet()) {
SvnCommitItem item = myModifiedFiles.get(path);
myContext.checkCancelled();
File itemAbspath = item.getPath();
if (myContext.getEventHandler() != null) {
SVNEvent event = SVNEventFactory.createSVNEvent(itemAbspath, SVNNodeKind.FILE, null, SVNRepository.INVALID_REVISION, SVNEventAction.COMMIT_DELTA_SENT, null, null, null);
myContext.getEventHandler().handleEvent(event, ISVNEventHandler.UNKNOWN);
}
boolean fulltext = item.hasFlag(SvnCommitItem.ADD);
TransmittedChecksums transmitTextDeltas = transmitTextDeltas(path, itemAbspath, fulltext, editor);
SvnChecksum newTextBaseMd5Checksum = transmitTextDeltas.md5Checksum;
SvnChecksum newTextBaseSha1Checksum = transmitTextDeltas.sha1Checksum;
if (myMd5Checksums != null) {
myMd5Checksums.put(itemAbspath, newTextBaseMd5Checksum);
}
if (mySha1Checksums != null) {
mySha1Checksums.put(itemAbspath, newTextBaseSha1Checksum);
}
}
}
private static class TransmittedChecksums {
public SvnChecksum md5Checksum;
public SvnChecksum sha1Checksum;
}
private TransmittedChecksums transmitTextDeltas(String path, File localAbspath, boolean fulltext, ISVNEditor editor) throws SVNException {
InputStream localStream = SVNFileUtil.DUMMY_IN;
InputStream baseStream = SVNFileUtil.DUMMY_IN;
SvnChecksum expectedMd5Checksum = null;
SvnChecksum localMd5Checksum = null;
SvnChecksum verifyChecksum = null;
SVNChecksumOutputStream localSha1ChecksumStream = null;
SVNChecksumInputStream verifyChecksumStream = null;
SVNErrorMessage error = null;
File newPristineTmpAbspath = null;
try {
localStream = myContext.getTranslatedStream(localAbspath, localAbspath, true, false);
WritableBaseInfo openWritableBase = myContext.openWritableBase(localAbspath, false, true);
OutputStream newPristineStream = openWritableBase.stream;
newPristineTmpAbspath = openWritableBase.tempBaseAbspath;
localSha1ChecksumStream = openWritableBase.sha1ChecksumStream;
localStream = new CopyingStream(newPristineStream, localStream);
if (!fulltext) {
PristineContentsInfo pristineContents = myContext.getPristineContents(localAbspath, true, true);
File baseFile = pristineContents.path;
baseStream = pristineContents.stream;
if (baseStream == null) {
baseStream = SVNFileUtil.DUMMY_IN;
}
expectedMd5Checksum = myContext.getDb().readInfo(localAbspath, InfoField.checksum).checksum;
if (expectedMd5Checksum != null && expectedMd5Checksum.getKind() != SvnChecksum.Kind.md5) {
expectedMd5Checksum = myContext.getDb().getPristineMD5(localAbspath, expectedMd5Checksum);
}
if (expectedMd5Checksum != null) {
verifyChecksumStream = new SVNChecksumInputStream(baseStream, SVNChecksumInputStream.MD5_ALGORITHM);
baseStream = verifyChecksumStream;
} else {
expectedMd5Checksum = new SvnChecksum(SvnChecksum.Kind.md5, SVNFileUtil.computeChecksum(baseFile));
}
}
editor.applyTextDelta(path, expectedMd5Checksum!=null ? expectedMd5Checksum.getDigest() : null);
if (myDeltaGenerator == null) {
myDeltaGenerator = new SVNDeltaGenerator();
}
localMd5Checksum = new SvnChecksum(SvnChecksum.Kind.md5, myDeltaGenerator.sendDelta(path, baseStream, 0, localStream, editor, true));
if (verifyChecksumStream != null) {
verifyChecksum = new SvnChecksum(SvnChecksum.Kind.md5, verifyChecksumStream.getDigest());
}
} catch (SVNException svne) {
error = svne.getErrorMessage().wrap("While preparing ''{0}'' for commit", localAbspath);
} finally {
SVNFileUtil.closeFile(localStream);
SVNFileUtil.closeFile(baseStream);
}
if (expectedMd5Checksum != null && verifyChecksum != null && !expectedMd5Checksum.equals(verifyChecksum)) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CHECKSUM_MISMATCH, "Checksum mismatch for ''{0}''; expected: ''{1}'', actual: ''{2}''", new Object[] {
localAbspath, expectedMd5Checksum, verifyChecksum
});
SVNErrorManager.error(err, SVNLogType.WC);
}
if (error != null) {
SVNErrorManager.error(error, SVNLogType.WC);
}
editor.closeFile(path, localMd5Checksum!=null ? localMd5Checksum.getDigest() : null);
SvnChecksum localSha1Checksum = new SvnChecksum(SvnChecksum.Kind.sha1, localSha1ChecksumStream.getDigest());
myContext.getDb().installPristine(newPristineTmpAbspath, localSha1Checksum, localMd5Checksum);
TransmittedChecksums result = new TransmittedChecksums();
result.md5Checksum = localMd5Checksum;
result.sha1Checksum = localSha1Checksum;
return result;
}
private class CopyingStream extends FilterInputStream {
private OutputStream myOutput;
public CopyingStream(OutputStream out, InputStream in) {
super(in);
myOutput = out;
}
public int read() throws IOException {
int r = super.read();
if (r != -1) {
myOutput.write(r);
}
return r;
}
public int read(byte[] b) throws IOException {
int r = super.read(b);
if (r != -1) {
myOutput.write(b, 0, r);
}
return r;
}
public int read(byte[] b, int off, int len) throws IOException {
int r = super.read(b, off, len);
if (r != -1) {
myOutput.write(b, off, r);
}
return r;
}
public void close() throws IOException {
try{
myOutput.close();
} finally {
super.close();
}
}
}
}
|
diff --git a/activiti-engine/src/test/java/com/camunda/fox/deployer/test/TestFoxDeployer.java b/activiti-engine/src/test/java/com/camunda/fox/deployer/test/TestFoxDeployer.java
index 0797e5762..fae2c8bc2 100755
--- a/activiti-engine/src/test/java/com/camunda/fox/deployer/test/TestFoxDeployer.java
+++ b/activiti-engine/src/test/java/com/camunda/fox/deployer/test/TestFoxDeployer.java
@@ -1,366 +1,372 @@
/**
* Copyright (C) 2011, 2012 camunda services GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.camunda.fox.deployer.test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.List;
import org.activiti.engine.impl.util.IoUtil;
import org.activiti.engine.repository.Deployment;
/**
*
* @author Daniel Meyer
- *
+//
*/
public class TestFoxDeployer extends FoxDeployerTestcase {
public void testDeployEmptyArchive() {
try {
deployer.deploy("processArchive", new HashMap<String, byte[]>(), getClass().getClassLoader());
fail("exception expected");
}catch (Exception e) {
if(!e.getCause().getMessage().contains("Deployment must contain at least one resource")) {
fail("wrong exception");
}
// expected
}
}
public void testDeployNoNameArchive() {
try {
deployer.deploy(null, new HashMap<String, byte[]>(), getClass().getClassLoader());
fail("exception expected");
}catch (Exception e) {
// expected
}
}
public void testDeployUndeployDeleteTrue() {
ClassLoader cl = getClass().getClassLoader();
String name = "processArchive";
String process = IoUtil.readFileAsString("oneTaskProcess.bpmn20.xml");
HashMap<String, byte[]> resources = new HashMap<String, byte[]>();
resources.put("oneTaskProcess.bpmn20.xml", process.getBytes());
deployer.deploy(name, resources, cl);
assertNotNull(repositoryService.createDeploymentQuery().deploymentName(name).singleResult());
assertNotNull(repositoryService.createProcessDefinitionQuery().singleResult());
assertNotNull(repositoryService.createProcessDefinitionQuery().active().singleResult());
deployer.unDeploy(name, true);
assertNull(repositoryService.createDeploymentQuery().deploymentName(name).singleResult());
assertNull(repositoryService.createProcessDefinitionQuery().singleResult());
}
public void testDeployUndeployDeleteFalse() {
ClassLoader cl = getClass().getClassLoader();
String name = "processArchive";
String process = IoUtil.readFileAsString("oneTaskProcess.bpmn20.xml");
HashMap<String, byte[]> resources = new HashMap<String, byte[]>();
resources.put("oneTaskProcess.bpmn20.xml", process.getBytes());
deployer.deploy(name, resources, cl);
assertNotNull(repositoryService.createDeploymentQuery().deploymentName(name).singleResult());
assertNotNull(repositoryService.createProcessDefinitionQuery().singleResult());
assertNotNull(repositoryService.createProcessDefinitionQuery().active().singleResult());
deployer.unDeploy(name, false);
assertNotNull(repositoryService.createDeploymentQuery().deploymentName(name).singleResult());
assertNotNull(repositoryService.createProcessDefinitionQuery().singleResult());
assertNull(repositoryService.createProcessDefinitionQuery().active().singleResult()); // process definition is suspended
assertNotNull(repositoryService.createProcessDefinitionQuery().suspended().singleResult());
// cleanup
deployer.unDeploy(name, true);
}
public void testDeploySameKeyFails() {
ClassLoader cl = getClass().getClassLoader();
String name = "processArchive";
String process = IoUtil.readFileAsString("oneTaskProcess.bpmn20.xml");
HashMap<String, byte[]> resources = new HashMap<String, byte[]>();
resources.put("oneTaskProcess.bpmn20.xml", process.getBytes());
deployer.deploy(name, resources, cl);
try {
deployer.deploy("differentName", resources, cl);
fail("exception expected");
}catch (Exception e) {
assertTrue(e.getMessage().contains("Could not deploy 'differentName': Cannot deploy process with id/key='oneTaskProcess', a process with the same key is already deployed"));
}
// cleanup
deployer.unDeploy(name, true);
}
public void testScenarioRedeployDifferentName() {
ClassLoader cl = getClass().getClassLoader();
String name = "processArchive";
String process = IoUtil.readFileAsString("oneTaskProcess.bpmn20.xml");
HashMap<String, byte[]> resources = new HashMap<String, byte[]>();
resources.put("oneTaskProcess.bpmn20.xml", process.getBytes());
deployer.deploy(name, resources, cl);
deployer.unDeploy(name, false);
assertEquals(1, repositoryService.createDeploymentQuery().deploymentName(name).count());
assertEquals(1, repositoryService.createProcessDefinitionQuery().count());
assertEquals(1, repositoryService.createProcessDefinitionQuery().suspended().count());
// re-deploy same version, differnet name of the process archive
deployer.deploy("newName", resources, cl);
assertEquals(2, repositoryService.createDeploymentQuery().count());
assertEquals(2, repositoryService.createProcessDefinitionQuery().count());
// old processes are activated
assertEquals(2, repositoryService.createProcessDefinitionQuery().active().count());
// clean db:
deployer.unDeploy(name, true);
deployer.unDeploy("newName", true);
}
public void testScenarioRedeployNoChangesInProcess() {
ClassLoader cl = getClass().getClassLoader();
String name = "processArchive";
String process = IoUtil.readFileAsString("oneTaskProcess.bpmn20.xml");
HashMap<String, byte[]> resources = new HashMap<String, byte[]>();
resources.put("oneTaskProcess.bpmn20.xml", process.getBytes());
deployer.deploy(name, resources, cl);
deployer.unDeploy(name, false);
assertEquals(1, repositoryService.createDeploymentQuery().deploymentName(name).count());
assertEquals(1, repositoryService.createProcessDefinitionQuery().count());
assertEquals(1, repositoryService.createProcessDefinitionQuery().suspended().count());
// re-deploy same version
deployer.deploy(name, resources, cl);
assertEquals(1, repositoryService.createDeploymentQuery().deploymentName(name).count());
assertEquals(1, repositoryService.createProcessDefinitionQuery().count());
assertEquals(1, repositoryService.createProcessDefinitionQuery().active().count());
// clean db:
deployer.unDeploy(name, true);
}
public void testScenarioRedeployNoChangesInProcessForUTF8() {
ClassLoader cl = getClass().getClassLoader();
String name = "processArchive";
String process = IoUtil.readFileAsString("fox-invoice.bpmn");
HashMap<String, byte[]> resources = new HashMap<String, byte[]>();
resources.put("fox-invoice.bpmn", process.getBytes());
String deploymentId = deployer.deploy(name, resources, cl);
assertNotNull(deploymentId);
deployer.unDeploy(name, false);
assertEquals(1, repositoryService.createDeploymentQuery().deploymentName(name).count());
assertEquals(1, repositoryService.createProcessDefinitionQuery().count());
assertEquals(1, repositoryService.createProcessDefinitionQuery().suspended().count());
// re-deploy same version
String noChangesProcess = IoUtil.readFileAsString("fox-invoice.bpmn");
resources = new HashMap<String, byte[]>();
resources.put("fox-invoice.bpmn", noChangesProcess.getBytes());
deployer.deploy(name, resources, cl);
assertEquals(1, repositoryService.createDeploymentQuery().deploymentName(name).count());
assertEquals(1, repositoryService.createProcessDefinitionQuery().count());
assertEquals(1, repositoryService.createProcessDefinitionQuery().active().count());
// clean db:
deployer.unDeploy(name, true);
}
public void testScenarioReDeployAdonisProcess() {
ClassLoader cl = getClass().getClassLoader();
String name = "processArchive";
deployer.unDeploy(name, true);
String process = IoUtil.readFileAsString("adonis-invoice.bpmn");
HashMap<String, byte[]> resources = new HashMap<String, byte[]>();
resources.put("adonis-invoice.bpmn", process.getBytes());
String deploymentId = deployer.deploy(name, resources, cl);
assertNotNull(deploymentId);
deployer.unDeploy(name, false);
assertEquals(1, repositoryService.createDeploymentQuery().deploymentName(name).count());
assertEquals(1, repositoryService.createProcessDefinitionQuery().count());
assertEquals(1, repositoryService.createProcessDefinitionQuery().suspended().count());
// re-deploy same version
String noChangesProcess = IoUtil.readFileAsString("adonis-invoice.bpmn");
resources = new HashMap<String, byte[]>();
resources.put("adonis-invoice.bpmn", noChangesProcess.getBytes());
deployer.deploy(name, resources, cl);
assertEquals(1, repositoryService.createDeploymentQuery().deploymentName(name).count());
assertEquals(1, repositoryService.createProcessDefinitionQuery().count());
assertEquals(1, repositoryService.createProcessDefinitionQuery().active().count());
// clean db:
deployer.unDeploy(name, true);
}
public void testScenarioUpgrade() {
ClassLoader cl = getClass().getClassLoader();
String name = "processArchive";
String process = IoUtil.readFileAsString("oneTaskProcess.bpmn20.xml");
HashMap<String, byte[]> resources = new HashMap<String, byte[]>();
resources.put("oneTaskProcess.bpmn20.xml", process.getBytes());
String processUpgrade = IoUtil.readFileAsString("oneTaskProcessUpgrade.bpmn20.xml");
HashMap<String, byte[]> resourcesUpgrade = new HashMap<String, byte[]>();
resourcesUpgrade.put("oneTaskProcess.bpmn20.xml", processUpgrade.getBytes());
deployer.deploy(name, resources, cl);
deployer.unDeploy(name, false);
assertEquals(1, repositoryService.createDeploymentQuery().deploymentName(name).count());
assertEquals(1, repositoryService.createProcessDefinitionQuery().count());
assertEquals(1, repositoryService.createProcessDefinitionQuery().suspended().count());
// deploy a new version:
deployer.deploy(name, resourcesUpgrade, cl);
assertEquals(2, repositoryService.createDeploymentQuery().deploymentName(name).count());
assertEquals(2, repositoryService.createProcessDefinitionQuery().count());
// deploying the new version activates previous versions
assertEquals(2, repositoryService.createProcessDefinitionQuery().active().count());
// clean db:
List<Deployment> deployments = repositoryService.createDeploymentQuery().list();
for (Deployment deployment : deployments) {
repositoryService.deleteDeployment(deployment.getId(), true);
}
}
public void testDeployNonBpmnFile() {
ClassLoader cl = getClass().getClassLoader();
String name = "processArchive";
System.err.println();
String process = IoUtil.readFileAsString("invoice.png");
HashMap<String, byte[]> resources = new HashMap<String, byte[]>();
resources.put("invoice.png", process.getBytes());
// capture messages in System.err from the XML parser in DeployIfChangedCmd#getExistingProcessDefinition(String, byte[])
ByteArrayOutputStream errContent = new ByteArrayOutputStream();
+
+ PrintStream systemErr = System.err;
System.setErr(new PrintStream(errContent));
deployer.deploy(name, resources, cl);
assertEquals("System.err is not empty.", "", errContent.toString());
- System.setErr(null); // reset System.err
+ System.setErr(systemErr); // reset System.err
assertNotNull(repositoryService.createDeploymentQuery().deploymentName(name).singleResult());
assertNull(repositoryService.createProcessDefinitionQuery().singleResult());
assertNull(repositoryService.createProcessDefinitionQuery().active().singleResult());
deployer.unDeploy(name, true);
assertNull(repositoryService.createDeploymentQuery().deploymentName(name).singleResult());
assertNull(repositoryService.createProcessDefinitionQuery().singleResult());
}
public void testDeployOnlyIsExecutableFlaggedProcesses() {
ClassLoader cl = getClass().getClassLoader();
String name = "processArchive";
String process = IoUtil.readFileAsString("collaboration_with_non_executable_process.bpmn");
HashMap<String, byte[]> resources = new HashMap<String, byte[]>();
resources.put("collaboration_with_non_executable_process.bpmn", process.getBytes());
ByteArrayOutputStream errContent = new ByteArrayOutputStream();
+
+ PrintStream systemErr = System.err;
System.setErr(new PrintStream(errContent));
String deploymentId = deployer.deploy(name, resources, cl);
assertEquals("System.err is not empty.", "", errContent.toString());
- System.setErr(null); // reset System.err
+ System.setErr(systemErr); // reset System.err
assertNotNull(deploymentId);
assertEquals(1, repositoryService.createDeploymentQuery().deploymentName(name).count());
assertEquals(2, repositoryService.createProcessDefinitionQuery().count());
deployer.unDeploy(name, true);
assertNull(repositoryService.createDeploymentQuery().deploymentName(name).singleResult());
assertNull(repositoryService.createProcessDefinitionQuery().singleResult());
}
public void testDontDeployIsExecutableFalseFlaggedProcesses() {
ClassLoader cl = getClass().getClassLoader();
String name = "processArchive";
String process = IoUtil.readFileAsString("collaboration_with_non_executable_processes.bpmn");
HashMap<String, byte[]> resources = new HashMap<String, byte[]>();
resources.put("collaboration_with_non_executable_processes.bpmn", process.getBytes());
ByteArrayOutputStream errContent = new ByteArrayOutputStream();
+
+ PrintStream systemErr = System.err;
System.setErr(new PrintStream(errContent));
String deploymentId = deployer.deploy(name, resources, cl);
assertEquals("System.err is not empty.", "", errContent.toString());
- System.setErr(null); // reset System.err
+ System.setErr(systemErr); // reset System.err
assertNotNull(deploymentId);
assertEquals(1, repositoryService.createDeploymentQuery().deploymentName(name).count());
assertEquals(0, repositoryService.createProcessDefinitionQuery().count());
deployer.unDeploy(name, true);
assertNull(repositoryService.createDeploymentQuery().deploymentName(name).singleResult());
assertNull(repositoryService.createProcessDefinitionQuery().singleResult());
}
}
| false | false | null | null |
diff --git a/src/test/java/org/freehep/util/io/test/ASCII85OutputStreamTest.java b/src/test/java/org/freehep/util/io/test/ASCII85OutputStreamTest.java
index c39cfc7..8fb2b61 100644
--- a/src/test/java/org/freehep/util/io/test/ASCII85OutputStreamTest.java
+++ b/src/test/java/org/freehep/util/io/test/ASCII85OutputStreamTest.java
@@ -1,42 +1,42 @@
// Copyright 2001-2005, FreeHEP.
package org.freehep.util.io.test;
-import java.io.BufferedReader;
import java.io.File;
+import java.io.FileInputStream;
import java.io.FileOutputStream;
-import java.io.FileReader;
-import java.io.PrintWriter;
+import java.io.InputStream;
import org.freehep.util.Assert;
import org.freehep.util.io.ASCII85OutputStream;
/**
* Test for ASCII85 Output Stream
*
* @author Mark Donszelmann
- * @version $Id: src/test/java/org/freehep/util/io/test/ASCII85OutputStreamTest.java c5cb38309f84 2005/12/02 20:35:09 duns $
+ * @version $Id: src/test/java/org/freehep/util/io/test/ASCII85OutputStreamTest.java d1e969e11aba 2005/12/10 00:18:28 duns $
*/
public class ASCII85OutputStreamTest extends AbstractStreamTest {
/**
* Test method for 'org.freehep.util.io.ASCII85OutputStream.write()'
* @throws Exception if ref file cannot be found
*/
public void testWrite() throws Exception {
+ // this XML file needs to be fixed: eol-style=CRLF
File testFile = new File(testDir, "TestFile.xml");
File outFile = new File(outDir, "TestFile.a85");
File refFile = new File(refDir, "TestFile.a85");
ASCII85OutputStream out = new ASCII85OutputStream(new FileOutputStream(outFile));
- PrintWriter writer = new PrintWriter(out);
- BufferedReader reader = new BufferedReader(new FileReader(testFile));
- String line;
- while ((line = reader.readLine()) != null) {
- writer.println(line);
+ // NOTE: read byte by byte, so the test will work on all platforms
+ InputStream in = new FileInputStream(testFile);
+ int b;
+ while ((b = in.read()) >= 0) {
+ out.write(b);
}
- reader.close();
- writer.close();
+ in.close();
+ out.close();
Assert.assertEquals(refFile, outFile, false);
}
}
| false | false | null | null |
diff --git a/jamwiki-web/src/main/java/org/jamwiki/authentication/JAMWikiPostAuthenticationFilter.java b/jamwiki-web/src/main/java/org/jamwiki/authentication/JAMWikiPostAuthenticationFilter.java
index ee1a6021..dfbeb4fe 100644
--- a/jamwiki-web/src/main/java/org/jamwiki/authentication/JAMWikiPostAuthenticationFilter.java
+++ b/jamwiki-web/src/main/java/org/jamwiki/authentication/JAMWikiPostAuthenticationFilter.java
@@ -1,188 +1,201 @@
/**
* 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.authentication;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.jamwiki.WikiBase;
import org.jamwiki.model.WikiUser;
import org.jamwiki.utils.WikiLogger;
import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.anonymous.AnonymousAuthenticationToken;
import org.springframework.security.userdetails.UserDetails;
/**
* Provide processing of a successfully authenticated user. This filter will examine
* the authentication credentails for systems using LDAP or other external
* authentication systems, and verify that the authenticated user has valid records in
* the jam_wiki_user and similar tables; if no such records exist they will be created to
* allow tracking of edit history and user contributions. Additionally, this filter
* provides capabilities for adding anonymous group permissions to anonymous users.
*/
public class JAMWikiPostAuthenticationFilter implements Filter {
/** Standard logger. */
private static final WikiLogger logger = WikiLogger.getLogger(JAMWikiPostAuthenticationFilter.class.getName());
private String key;
private boolean useJAMWikiAnonymousRoles;
/**
*
*/
private GrantedAuthority[] combineAuthorities(GrantedAuthority[] list1, GrantedAuthority[] list2) {
if (list1 == null || list2 == null) {
return null;
}
// add these roles to a single array of authorities
int authoritySize = list1.length + list2.length;
GrantedAuthority[] combinedAuthorities = new GrantedAuthority[authoritySize];
for (int i = 0; i < list1.length; i++) {
combinedAuthorities[i] = list1[i];
}
for (int i = 0; i < list2.length; i++) {
combinedAuthorities[i + list1.length] = list2[i];
}
return combinedAuthorities;
}
/**
*
*/
public void destroy() {
}
/**
*
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (!(request instanceof HttpServletRequest)) {
throw new ServletException("HttpServletRequest required");
}
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth instanceof AnonymousAuthenticationToken) {
// anonymous user
this.handleAnonymousUser(auth);
} else if (auth != null && auth.isAuthenticated()) {
// registered user
this.handleRegisteredUser(auth);
}
chain.doFilter(request, response);
}
/**
*
*/
private void handleAnonymousUser(Authentication auth) {
if (!this.getUseJAMWikiAnonymousRoles()) {
// the configuration file indicates that JAMWiki anonymous roles should not be
// used, so assume that an external system is providing this information.
return;
}
// get arrays of existing Spring Security roles and JAMWiki anonymous user roles
GrantedAuthority[] springSecurityAnonymousAuthorities = auth.getAuthorities();
GrantedAuthority[] jamwikiAnonymousAuthorities = JAMWikiAuthenticationConfiguration.getJamwikiAnonymousAuthorities();
GrantedAuthority[] anonymousAuthorities = combineAuthorities(springSecurityAnonymousAuthorities, jamwikiAnonymousAuthorities);
if (anonymousAuthorities == null) {
return;
}
// replace the existing anonymous authentication object with the new authentication array
AnonymousAuthenticationToken jamwikiAuth = new AnonymousAuthenticationToken(this.getKey(), auth.getPrincipal(), anonymousAuthorities);
jamwikiAuth.setDetails(auth.getDetails());
jamwikiAuth.setAuthenticated(auth.isAuthenticated());
SecurityContextHolder.getContext().setAuthentication(jamwikiAuth);
}
/**
*
*/
private void handleRegisteredUser(Authentication auth) throws ServletException {
Object principal = auth.getPrincipal();
- if (!(principal instanceof UserDetails)) {
- logger.warning("Unknown principal type: " + principal);
- return;
- }
+ // Check if Authentication returns a known principal
if (principal instanceof WikiUserDetails) {
// user has gone through the normal authentication path, no need to process further
return;
}
- String username = ((UserDetails)principal).getUsername();
+
+ // find out authenticated username
+ logger.info("'" + principal + "' logged in");
+ String username;
+ if (principal instanceof UserDetails) {
+ // using custom authentication with Spring Security UserDetail service
+ username = ((UserDetails)principal).getUsername();
+ } else if (principal instanceof String) {
+ // external authentication returns only username
+ username = String.valueOf(principal);
+ } else {
+ // no known principal was found
+ logger.warning("Unknown principal type: " + principal);
+ username = null;
+ return;
+ }
+
if (StringUtils.isBlank(username)) {
logger.warning("Null or empty username found for authenticated principal");
return;
}
// for LDAP and other authentication methods, verify that JAMWiki database records exist
- try {
+ try {
if (WikiBase.getDataHandler().lookupWikiUser(username) == null) {
// if there is a valid security credential & no JAMWiki record for the user, create one
WikiUser user = new WikiUser(username);
// default the password empty so that the user cannot login directly
String encryptedPassword = "";
WikiBase.getDataHandler().writeWikiUser(user, username, encryptedPassword);
}
} catch (Exception e) {
logger.severe("Failure while processing user credentials for " + username, e);
throw new ServletException(e);
}
}
/**
*
*/
public void init(FilterConfig filterConfig) throws ServletException {
}
/**
* Standard get method to return the anonymous authentication token key configured
* for anonymous users. This value is set from the configuration file and MUST match
* the value used when creating anonymous authentication credentials.
*/
public String getKey() {
return key;
}
/**
*
*/
public void setKey(String key) {
this.key = key;
}
/**
* Provide a flag to disable the addition of JAMWiki GROUP_ANONYMOUS permissions to
* all anonymous users.
*/
public boolean getUseJAMWikiAnonymousRoles() {
return useJAMWikiAnonymousRoles;
}
/**
* Provide a flag to disable the addition of JAMWiki GROUP_ANONYMOUS permissions to
* all anonymous users.
*/
public void setUseJAMWikiAnonymousRoles(boolean useJAMWikiAnonymousRoles) {
this.useJAMWikiAnonymousRoles = useJAMWikiAnonymousRoles;
}
}
| false | false | null | null |
diff --git a/amibe/src/org/jcae/mesh/amibe/ds/OTriangle.java b/amibe/src/org/jcae/mesh/amibe/ds/OTriangle.java
index 4db7c1ec..08fb145e 100644
--- a/amibe/src/org/jcae/mesh/amibe/ds/OTriangle.java
+++ b/amibe/src/org/jcae/mesh/amibe/ds/OTriangle.java
@@ -1,1290 +1,1284 @@
/* jCAE stand for Java Computer Aided Engineering. Features are : Small CAD
modeler, Finit element mesher, Plugin architecture.
Copyright (C) 2004,2005
Jerome Robert <[email protected]>
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 */
package org.jcae.mesh.amibe.ds;
import java.util.Random;
import java.util.HashSet;
import org.jcae.mesh.amibe.metrics.Metric3D;
import org.apache.log4j.Logger;
/*
* This class is derived from Jonathan R. Shewchuk's work
* on Triangle, see
* http://www.cs.cmu.edu/~quake/triangle.html
* His data structure is very compact, and similar ideas were
* developed here, but due to Java constraints, this version is a
* little bit less efficient than its C counterpart.
*
* Geometrical primitives and basic routines have been written from
* scratch, but are in many cases very similar to those defined by
* Shewchuk since data structures are almost equivalent and there
* are few ways to achieve the same operations.
*
* Other ideas come from Bamg, written by Frederic Hecht
* http://www-rocq1.inria.fr/gamma/cdrom/www/bamg/eng.htm
*/
/**
* A handle to {@link Triangle} objects.
*
* <p>
* Jonathan Richard Shewchuk
* <a href="http://www.cs.cmu.edu/~quake/triangle.html">explains</a>
* why triangle-based data structures are more efficient than their
* edge-based counterparts. But mesh operations make heavy use of edges,
* and informations about adges are not stored in this data structure in
* order to be compact.
* </p>
*
* <p>
* A triangle is composed of three edges, so a triangle and a number
* between 0 and 2 can represent an edge. This <code>OTriangle</code>
* class plays this role, it defines an <em>oriented triangle</em>, or
* in other words an oriented edge. Instances of this class are tied to
* their underlying {@link Triangle} instances, so modifications are not
* local to this class!
* </p>
*
* <p>
* The main goal of this class is to ease mesh traversal.
* Consider the <code>ot</code> {@link OTriangle} with a null orientation of
* {@link Triangle} <code>t</code>below.
* </p>
* <pre>
* V2
* V5 _________________,________________, V3
* \ <---- / \ <---- /
* \ 1 / \ 1 /
* \ t3 -.// /\\\ t0 _,/
* \ 0 ///1 0\\\2 0 // t.vertex = { V0, V1, V2 }
* \ //V t \\V // t0.vertex = { V2, V1, V3 }
* \ / \ / t2.vertex = { V0, V4, V1 }
* \ / 2 \ / t3.vertex = { V5, V0, V2 }
* \ / ----> \ /
* V0 +-----------------+ V1
* \ <---- /
* \ 1 /
* \ t2 _,/
* \ 0//
* </pre>
* The following methods can be applied to <code>ot</code>:
* <pre>
* ot.nextOTri(); // Moves (t,0) to (t,1)
* ot.prevOTri(); // Moves (t,0) to (t,2)
* ot.symOTri(); // Moves (t,0) to (t0,2)
* ot.nextOTriOrigin(); // Moves (t,0) to (t2,1)
* ot.prevOTriOrigin(); // Moves (t,0) to (t0,0)
* ot.nextOTriDest(); // Moves (t,0) to (t0,1)
* ot.prevOTriDest(); // Moves (t,0) to (t3,0)
* ot.nextOTriApex(); // Moves (t,0) to (t3,1)
* ot.prevOTriApex(); // Moves (t,0) to (t2,0)
* </pre>
*/
public class OTriangle
{
private static Logger logger = Logger.getLogger(OTriangle.class);
private static final int [] next3 = { 1, 2, 0 };
private static final int [] prev3 = { 2, 0, 1 };
private double [] tempD = new double[3];
private double [] tempD1 = new double[3];
private double [] tempD2 = new double[3];
/**
* Numeric constants for edge attributes. Set if edge is on
* boundary.
* @see #setAttributes
* @see #hasAttributes
*/
public static final int BOUNDARY = 1 << 0;
/**
* Numeric constants for edge attributes. Set if edge is outer.
* (Ie. one of its end point is {@link Vertex#outer})
* @see #setAttributes
* @see #hasAttributes
*/
public static final int OUTER = 1 << 1;
/**
* Numeric constants for edge attributes. Set if edge had been
* swapped.
* @see #setAttributes
* @see #hasAttributes
*/
public static final int SWAPPED = 1 << 2;
/**
* Numeric constants for edge attributes. Set if edge had been
* marked (for any operation).
* @see #setAttributes
* @see #hasAttributes
*/
public static final int MARKED = 1 << 3;
/**
* Numeric constants for edge attributes. Set if edge is the inner
* edge of a quadrangle.
* @see #setAttributes
* @see #hasAttributes
*/
public static final int QUAD = 1 << 4;
// Complex algorithms require several OTriangle, they are
// allocated here to prevent allocation/deallocation overhead.
private static OTriangle [] work = new OTriangle[4];
static {
for (int i = 0; i < 4; i++)
work[i] = new OTriangle();
}
private static final Random rand = new Random(139L);
private static final Triangle dummy = new Triangle();
/*
* Vertices can be accessed through
* origin = tri.vertex[next3[orientation]]
* destination = tri.vertex[prev3[orientation]]
* apex = tri.vertex[orientation]
* Adjacent triangle is tri.adj[orientation].tri and its orientation
* is ((tri.adjPos >> (2*orientation)) & 3)
*/
protected Triangle tri;
protected int orientation;
protected int attributes;
/**
* Sole constructor.
*/
public OTriangle()
{
tri = null;
orientation = 0;
attributes = 0;
}
/**
* Create an object to handle data about a triangle.
*
* @param t geometrical triangle.
* @param o a number between 0 and 2 determining an edge.
*/
public OTriangle(Triangle t, int o)
{
tri = t;
orientation = o;
attributes = (tri.adjPos >> (8*(1+orientation))) & 0xff;
}
/**
* Return the triangle tied to this object.
*
* @return the triangle tied to this object.
*/
public final Triangle getTri()
{
return tri;
}
/**
* Set the triangle tied to this object, and resets orientation.
*
* @param t the triangle tied to this object.
*/
public final void bind(Triangle t)
{
tri = t;
orientation = 0;
attributes = (tri.adjPos >> 8) & 0xff;
}
/**
* Check if some attributes of this oriented triangle are set.
*
* @param attr the attributes to check
* @return <code>true</code> if this OTriangle has all these
* attributes set, <code>false</code> otherwise.
*/
public final boolean hasAttributes(int attr)
{
return (attributes & attr) == attr;
}
/**
* Set attributes of this oriented triangle.
*
* @param attr the attribute of this oriented triangle.
*/
public final void setAttributes(int attr)
{
attributes |= attr;
pushAttributes();
}
/**
* Reset attributes of this oriented triangle.
*
* @param attr the attributes of this oriented triangle to clear out.
*/
public final void clearAttributes(int attr)
{
attributes &= ~attr;
pushAttributes();
}
// Adjust tri.adjPos after attributes is modified.
public final void pushAttributes()
{
tri.adjPos &= ~(0xff << (8*(1+orientation)));
tri.adjPos |= ((attributes & 0xff) << (8*(1+orientation)));
}
// Adjust attributes after tri.adjPos is modified.
public final void pullAttributes()
{
attributes = (tri.adjPos >> (8*(1+orientation))) & 0xff;
}
/**
* Copy an <code>OTriangle</code> into another <code>OTriangle</code>.
*
* @param src <code>OTriangle</code> being duplicated
* @param dest already allocated <code>OTriangle</code> where data are
* copied
*/
public static final void copyOTri(OTriangle src, OTriangle dest)
{
dest.tri = src.tri;
dest.orientation = src.orientation;
dest.attributes = src.attributes;
}
// These geometrical primitives have 2 signatures:
// fct(this, that) applies fct to 'this' and stores result
// in an already allocated object 'that'.
// fct() transforms current object.
// This is definitely not an OO approach, but it is much more
// efficient by preventing useless memory allocations.
// They do not return any value to make clear that calling
// these routines requires extra care.
/**
* Copy an <code>OTriangle</code> and move to its symmetric edge.
*
* @param o source <code>OTriangle</code>
* @param that already allocated <code>OTriangle</code> where data are
* copied
*/
public static final void symOTri(OTriangle o, OTriangle that)
{
that.tri = o.tri.adj[o.orientation];
that.orientation = ((o.tri.adjPos >> (2*o.orientation)) & 3);
that.attributes = (that.tri.adjPos >> (8*(1+that.orientation))) & 0xff;
}
/**
* Move to the symmetric edge.
*/
public final void symOTri()
{
int neworient = ((tri.adjPos >> (2*orientation)) & 3);
tri = tri.adj[orientation];
orientation = neworient;
attributes = (tri.adjPos >> (8*(1+orientation))) & 0xff;
}
/**
* Copy an <code>OTriangle</code> and move it to the counterclockwaise
* following edge.
*
* @param o source <code>OTriangle</code>
* @param that already allocated <code>OTriangle</code> where data are
* copied
*/
public static final void nextOTri(OTriangle o, OTriangle that)
{
that.tri = o.tri;
that.orientation = next3[o.orientation];
that.attributes = (that.tri.adjPos >> (8*(1+that.orientation))) & 0xff;
}
/**
* Move to the counterclockwaise following edge.
*/
public final void nextOTri()
{
orientation = next3[orientation];
attributes = (tri.adjPos >> (8*(1+orientation))) & 0xff;
}
/**
* Copy an <code>OTriangle</code> and move it to the counterclockwaise
* previous edge.
*
* @param o source <code>OTriangle</code>
* @param that already allocated <code>OTriangle</code> where data are
* copied
*/
public static final void prevOTri(OTriangle o, OTriangle that)
{
that.tri = o.tri;
that.orientation = prev3[o.orientation];
that.attributes = (that.tri.adjPos >> (8*(1+that.orientation))) & 0xff;
}
/**
* Move to the counterclockwaise previous edge.
*/
public final void prevOTri()
{
orientation = prev3[orientation];
attributes = (tri.adjPos >> (8*(1+orientation))) & 0xff;
}
/**
* Copy an <code>OTriangle</code> and move it to the counterclockwaise
* following edge which has the same origin.
*
* @param o source <code>OTriangle</code>
* @param that already allocated <code>OTriangle</code> where data are
* copied
*/
public static final void nextOTriOrigin(OTriangle o, OTriangle that)
{
prevOTri(o, that);
that.symOTri();
}
/**
* Move counterclockwaise to the following edge with the same origin.
*/
public final void nextOTriOrigin()
{
prevOTri();
symOTri();
}
/**
* Copy an <code>OTriangle</code> and move it to the counterclockwaise
* previous edge which has the same origin.
*
* @param o source <code>OTriangle</code>
* @param that already allocated <code>OTriangle</code> where data are
* copied
*/
public static final void prevOTriOrigin(OTriangle o, OTriangle that)
{
symOTri(o, that);
that.nextOTri();
}
/**
* Move counterclockwaise to the previous edge with the same origin.
*/
public final void prevOTriOrigin()
{
symOTri();
nextOTri();
}
/**
* Copy an <code>OTriangle</code> and move it to the counterclockwaise
* following edge which has the same destination.
*
* @param o source <code>OTriangle</code>
* @param that already allocated <code>OTriangle</code> where data are
* copied
*/
public static final void nextOTriDest(OTriangle o, OTriangle that)
{
symOTri(o, that);
that.prevOTri();
}
/**
* Move counterclockwaise to the following edge with the same
* destination.
*/
public final void nextOTriDest()
{
symOTri();
prevOTri();
}
/**
* Copy an <code>OTriangle</code> and move it to the counterclockwaise
* previous edge which has the same destination.
*
* @param o source <code>OTriangle</code>
* @param that already allocated <code>OTriangle</code> where data are
* copied
*/
public static final void prevOTriDest(OTriangle o, OTriangle that)
{
nextOTri(o, that);
that.symOTri();
}
/**
* Move counterclockwaise to the previous edge with the same
* destination.
*/
public final void prevOTriDest()
{
nextOTri();
symOTri();
}
/**
* Copy an <code>OTriangle</code> and move it to the counterclockwaise
* following edge which has the same apex.
*
* @param o source <code>OTriangle</code>
* @param that already allocated <code>OTriangle</code> where data are
* copied
*/
public static final void nextOTriApex(OTriangle o, OTriangle that)
{
nextOTri(o, that);
that.symOTri();
that.nextOTri();
}
/**
* Move counterclockwaise to the following edge with the same apex.
*/
public final void nextOTriApex()
{
nextOTri();
symOTri();
nextOTri();
}
/**
* Copy an <code>OTriangle</code> and move it to the counterclockwaise
* previous edge which has the same apex.
*
* @param o source <code>OTriangle</code>
* @param that already allocated <code>OTriangle</code> where data are
* copied
*/
public static final void prevOTriApex(OTriangle o, OTriangle that)
{
prevOTri(o, that);
that.symOTri();
that.prevOTri();
}
/**
* Move counterclockwaise to the previous edge with the same apex.
*/
public final void prevOTriApex()
{
prevOTri();
symOTri();
prevOTri();
}
/**
* Returns the start vertex of this edge.
*
* @return the start vertex of this edge.
*/
public final Vertex origin()
{
return tri.vertex[next3[orientation]];
}
/**
* Returns the end vertex of this edge.
*
* @return the end vertex of this edge.
*/
public final Vertex destination()
{
return tri.vertex[prev3[orientation]];
}
/**
* Returns the apex of this edge.
*
* @return the apex of this edge.
*/
public final Vertex apex()
{
return tri.vertex[orientation];
}
// The following 3 methods change the underlying triangle.
// So they also modify all OTriangle bound to this one.
/**
* Sets the start vertex of this edge.
*
* @param v the start vertex of this edge.
*/
public final void setOrigin(Vertex v)
{
tri.vertex[next3[orientation]] = v;
}
/**
* Sets the end vertex of this edge.
*
* @param v the end vertex of this edge.
*/
public final void setDestination(Vertex v)
{
tri.vertex[prev3[orientation]] = v;
}
/**
* Sets the apex of this edge.
*
* @param v the apex of this edge.
*/
public final void setApex(Vertex v)
{
tri.vertex[orientation] = v;
}
/**
* Sets adjacency relations between two triangles.
*
* @param sym the triangle bond to this one.
*/
public final void glue(OTriangle sym)
{
tri.adj[orientation] = sym.tri;
sym.tri.adj[sym.orientation] = tri;
// Clear previous adjacent position ...
tri.adjPos &= ~(3 << (2*orientation));
sym.tri.adjPos &= ~(3 << (2*sym.orientation));
// ... and set it right
tri.adjPos |= (sym.orientation << (2*orientation));
sym.tri.adjPos |= (orientation << (2*sym.orientation));
}
/**
* Collapse an edge and update adjacency relations.
* Its start and end points must have the same location.
*/
public final void collapse()
{
Vertex o = origin();
Vertex d = destination();
assert o.getRef() != 0 && d.getRef() != 0 && o.getRef() == d.getRef();
// Replace o by d in all triangles
copyOTri(this, work[0]);
work[0].nextOTriOrigin();
for ( ; work[0].destination() != d; work[0].nextOTriOrigin())
{
for (int i = 0; i < 3; i++)
{
if (work[0].tri.vertex[i] == o)
{
work[0].tri.vertex[i] = d;
break;
}
}
}
o.removeFromQuadTree();
// Glue triangles
nextOTri(this, work[0]);
work[0].symOTri();
prevOTri(this, work[1]);
work[1].symOTri();
work[0].glue(work[1]);
// Glue symmetric triangles
symOTri(this, work[0]);
work[0].nextOTri();
work[0].symOTri();
symOTri(this, work[1]);
work[1].prevOTri();
work[1].symOTri();
work[0].glue(work[1]);
}
/*
* a
* ,
* /|\
* / | \
* oldLeft / | \ oldRight
* / v+ \
* / / \ \
* / / \ \
* / / \ \
* o '---------------` d
* (this)
*/
/**
* Splits a triangle into three new triangles by inserting a vertex.
*
* Two new triangles have to be created, the last one is
* updated. For efficiency reasons, no checks are performed to
* ensure that the vertex being inserted is contained by this
* triangle. Once triangles are created, edges are swapped if
* they are not Delaunay.
*
* If edges are not swapped after vertex is inserted, the quality of
* newly created triangles has decreased, and the vertex is eventually
* not inserted unless the <code>force</code> argument is set to
* <code>true</code>.
*
* Origin and destination points must not be at infinite, which
* is the case when current triangle is returned by
* getSurroundingTriangle(). If apex is Vertex.outer, then
* getSurroundingTriangle() ensures that v.onLeft(o,d) > 0.
*
* @param v the vertex being inserted.
* @param force if <code>false</code>, the vertex is inserted only if some edges were swapped after its insertion. If <code>true</code>, the vertex is unconditionnally inserted.
* @return <code>true</code> if vertex was successfully added, <code>false</code> otherwise.
*/
public final boolean split3(Vertex v, boolean force)
{
// Aliases
OTriangle oldLeft = work[0];
OTriangle oldRight = work[1];
OTriangle oldSymLeft = work[2];
OTriangle oldSymRight = work[3];
prevOTri(this, oldLeft); // = (aod)
nextOTri(this, oldRight); // = (dao)
symOTri(oldLeft, oldSymLeft); // = (oa*)
symOTri(oldRight, oldSymRight); // = (ad*)
// Set vertices of newly created and current triangles
Vertex o = origin();
assert o != Vertex.outer;
Vertex d = destination();
assert d != Vertex.outer;
Vertex a = apex();
OTriangle newLeft = new OTriangle(new Triangle(a, o, v), 2);
OTriangle newRight = new OTriangle(new Triangle(d, a, v), 2);
if (oldLeft.attributes != 0)
{
newLeft.attributes = oldLeft.attributes;
newLeft.pushAttributes();
oldLeft.attributes = 0;
oldLeft.pushAttributes();
}
if (oldRight.attributes != 0)
{
newRight.attributes = oldRight.attributes;
newRight.pushAttributes();
oldRight.attributes = 0;
oldRight.pushAttributes();
}
Triangle iniTri = tri;
v.tri = tri;
a.tri = newLeft.tri;
// Move apex of current OTriangle. As a consequence,
// oldLeft is now (vod) and oldRight is changed to (dvo).
setApex(v);
newLeft.glue(oldSymLeft);
newRight.glue(oldSymRight);
// Creates 3 inner links
newLeft.nextOTri(); // = (ova)
newLeft.glue(oldLeft);
newRight.prevOTri(); // = (vda)
newRight.glue(oldRight);
newLeft.nextOTri(); // = (vao)
newRight.prevOTri(); // = (avd)
newLeft.glue(newRight);
// Data structures have been created, search now for non-Delaunay
// edges. Re-use newLeft to walk through new vertex ring.
newLeft.nextOTri(); // = (aov)
Triangle newTri1 = newLeft.tri;
Triangle newTri2 = newRight.tri;
if (force)
CheckAndSwap(newLeft, oldRight, false);
else if (0 == CheckAndSwap(newLeft, oldRight, false))
{
// v has been inserted and no edges are swapped,
// thus global quality has been decreased.
// Remove v in such cases.
o.tri = iniTri;
d.tri = iniTri;
a.tri = iniTri;
setApex(a);
nextOTri(this, oldLeft); // = (oad)
oldLeft.glue(oldSymRight);
oldLeft.nextOTri(); // = (ado)
oldLeft.glue(oldSymLeft);
return false;
}
newTri1.addToMesh();
newTri2.addToMesh();
return true;
}
// Called from BasicMesh to improve initial mesh
public int checkSmallerAndSwap()
{
// As CheckAndSwap modifies its arguments, 'this'
// must be protected.
OTriangle ot1 = new OTriangle();
OTriangle ot2 = new OTriangle();
copyOTri(this, ot1);
return CheckAndSwap(ot1, ot2, true);
}
private int CheckAndSwap(OTriangle newLeft, OTriangle newRight, boolean smallerDiag)
{
int nrSwap = 0;
int totNrSwap = 0;
Vertex v = newLeft.apex();
assert v != Vertex.outer;
Vertex firstVertex = newLeft.origin();
while (firstVertex == Vertex.outer)
{
newLeft.nextOTriApex();
firstVertex = newLeft.origin();
}
// Loops around v
Vertex a, o, d;
while (true)
{
boolean swap = false;
symOTri(newLeft, newRight);
o = newLeft.origin();
d = newLeft.destination();
a = newRight.apex();
if (o == Vertex.outer)
swap = (v.onLeft(d, a) < 0L);
else if (d == Vertex.outer)
swap = (v.onLeft(a, o) < 0L);
else if (a == Vertex.outer)
swap = (v.onLeft(o, d) == 0L);
else if (newLeft.isMutable())
{
if (!smallerDiag)
swap = !newLeft.isDelaunay(a);
else
swap = !a.isSmallerDiagonale(newLeft);
}
if (swap)
{
newLeft.swapOTriangle(v, a);
nrSwap++;
totNrSwap++;
}
else
{
newLeft.nextOTriApex();
if (newLeft.origin() == firstVertex)
{
if (nrSwap == 0)
break;
nrSwap = 0;
}
}
}
return totNrSwap;
}
/**
* Checks whether an edge can be swapped.
*
* @return <code>false</code> if edge is a boundary or outside the mesh,
* <code>true</code> otherwise.
*/
public final boolean isMutable()
{
return !(hasAttributes(BOUNDARY) || hasAttributes(OUTER));
}
/**
* Checks whether an edge is Delaunay.
*
* As apical vertices are already computed by calling routines,
* they are passed as parameters for efficiency reasons.
*
* @param apex2 apex of the symmetric edge
* @return <code>true</code> if edge is Delaunay, <code>false</code>
* otherwise.
*/
public final boolean isDelaunay(Vertex apex2)
{
if (apex2.isPseudoIsotropic())
return isDelaunay_isotropic(apex2);
return isDelaunay_anisotropic(apex2);
}
private final boolean isDelaunay_isotropic(Vertex apex2)
{
assert Vertex.outer != origin();
assert Vertex.outer != destination();
assert Vertex.outer != apex();
Vertex vA = origin();
Vertex vB = destination();
Vertex v1 = apex();
long tp1 = vA.onLeft(vB, v1);
long tp2 = vB.onLeft(vA, apex2);
long tp3 = apex2.onLeft(vB, v1);
long tp4 = v1.onLeft(vA, apex2);
if (Math.abs(tp3) + Math.abs(tp4) < Math.abs(tp1)+Math.abs(tp2) )
return true;
if (tp1 > 0L && tp2 > 0L)
{
if (tp3 <= 0L || tp4 <= 0L)
return true;
}
return !apex2.inCircleTest2(this);
}
private final boolean isDelaunay_anisotropic(Vertex apex2)
{
assert Vertex.outer != origin();
assert Vertex.outer != destination();
assert Vertex.outer != apex();
if (apex2 == Vertex.outer)
return true;
return !apex2.inCircleTest3(this);
}
/**
* Swaps an edge.
*
* This routine swaps an edge (od) to (na), updates
* adjacency relations and backward links between vertices and
* triangles. Current object is transformed from (oda) to (ona)
* and not (nao), because this helps turning around o, e.g.
* at the end of {@link #split3}.
*
* @param a apex of the current edge
* @param n apex of the symmetric edge
* @return a handle to (ona) oriented triangle.
* otherwise.
*/
public final OTriangle swapOTriangle(Vertex a, Vertex n)
{
Vertex o = origin();
Vertex d = destination();
/*
* d d
* . .
* /|\ / \
* a1 / | \ a4 a1 / \ a4
* / | \ / \
* a + | + n a +-------+ n
* \ | / \ /
* a2 \ | / a3 a2 \ / a3
* \|/ \ /
* ' '
* o o
* .
* | /|\
* | |
* \|/ |
* '
* d n
* . .
* /|\ / \
* a2 / | \ a1 a1 / \ a4
* / | \ / \
* a + | + n is d +-------+ o
* \ | / \ /
* a3 \ | / a4 a2 \ / a3
* \|/ \ /
* ' '
* o a
*/
// this = (oda)
symOTri(this, work[0]); // (don)
// Clear SWAPPED flag for all edges of the 2 triangles
clearAttributes(SWAPPED);
work[0].clearAttributes(SWAPPED);
nextOTri(this, work[1]); // (dao)
work[1].clearAttributes(SWAPPED);
int attr1 = work[1].attributes;
work[1].symOTri(); // a1 = (ad*)
work[1].clearAttributes(SWAPPED);
prevOTri(this, work[2]); // (aod)
work[2].clearAttributes(SWAPPED);
int attr2 = work[2].attributes;
work[2].symOTri(); // a2 = (oa*)
work[2].clearAttributes(SWAPPED);
nextOTri(); // (dao)
work[2].glue(this); // a2 and (dao)
nextOTri(work[0], work[2]); // (ond)
work[2].clearAttributes(SWAPPED);
int attr3 = work[2].attributes;
work[2].symOTri(); // a3 = (no*)
work[2].clearAttributes(SWAPPED);
nextOTri(); // (aod)
work[2].glue(this); // a3 and (aod)
// Reset 'this' to (oda)
nextOTri(); // (oda)
prevOTri(work[0], work[2]); // (ndo)
work[2].clearAttributes(SWAPPED);
int attr4 = work[2].attributes;
work[2].symOTri(); // a4 = (dn*)
work[2].clearAttributes(SWAPPED);
work[0].nextOTri(); // (ond)
work[2].glue(work[0]); // a4 and (ond)
work[0].nextOTri(); // (ndo)
work[1].glue(work[0]); // a1 and (ndo)
work[0].nextOTri(); // (don)
// Adjust vertices
setOrigin(n);
setDestination(a);
setApex(o);
work[0].setOrigin(a);
work[0].setDestination(n);
work[0].setApex(d);
// Fix links to triangles
n.tri = tri;
a.tri = tri;
o.tri = tri;
d.tri = work[0].tri;
// Fix attributes
tri.adjPos &= 0xff;
tri.adjPos |= ((attr2 & 0xff) << (8*(1+next3[orientation])));
tri.adjPos |= ((attr3 & 0xff) << (8*(1+prev3[orientation])));
work[0].tri.adjPos &= 0xff;
work[0].tri.adjPos |= ((attr4 & 0xff) << (8*(1+next3[work[0].orientation])));
work[0].tri.adjPos |= ((attr1 & 0xff) << (8*(1+prev3[work[0].orientation])));
// Mark new edge
setAttributes(SWAPPED);
work[0].setAttributes(SWAPPED);
// Eventually change 'this' to (ona) to ease moving around o.
prevOTri(); // (ona)
return this;
}
/**
* Tries to rebuild a boundary edge by swapping edges.
*
* This routine is applied to an oriented triangle, its origin
* is an end point of the boundary edge to rebuild. The other end
* point is passed as an argument. Current oriented triangle has
* been set up by calling routine so that it is the leftmost edge
* standing to the right of the boundary edge.
* A traversal between end points is performed, and intersected
* edges are swapped if possible. At exit, current oriented
* triangle has <code>end</code> as its origin, and is the
* rightmost edge standing to the left of the inverted edge.
* This algorithm can then be called iteratively back and forth,
* and it is known that it is guaranteed to finish.
*
* @param end end point of the boundary edge.
* @return the number of intersected edges.
*/
public final int forceBoundaryEdge(Vertex end)
{
long newl, oldl;
int count = 0;
Vertex start = origin();
nextOTri();
while (true)
{
count++;
Vertex o = origin();
Vertex d = destination();
Vertex a = apex();
symOTri(this, work[0]);
work[0].nextOTri();
Vertex n = work[0].destination();
newl = n.onLeft(start, end);
oldl = a.onLeft(start, end);
boolean canSwap = (n != Vertex.outer) && (a.onLeft(n, d) > 0L) && (a.onLeft(o, n) > 0L) && !hasAttributes(BOUNDARY);
if (newl > 0L)
{
// o stands to the right of (start,end), d and n to the left.
if (!canSwap)
prevOTriOrigin(); // = (ond)
else if (oldl >= 0L)
{
// a stands to the left of (start,end).
swapOTriangle(a, n); // = (ona)
}
else if (rand.nextBoolean())
swapOTriangle(a, n); // = (ona)
else
prevOTriOrigin(); // = (ond)
}
else if (newl < 0L)
{
// o and n stand to the right of (start,end), d to the left.
if (!canSwap)
nextOTriDest(); // = (ndo)
else if (oldl <= 0L)
{
// a stands to the right of (start,end).
swapOTriangle(a, n); // = (ona)
nextOTri(); // = (nao)
prevOTriOrigin(); // = (nda)
}
else if (rand.nextBoolean())
{
swapOTriangle(a, n); // = (ona)
nextOTri(); // = (nao)
prevOTriOrigin(); // = (nda)
}
else
nextOTriDest(); // = (ndo)
}
else
{
// n is the end point.
if (!canSwap)
nextOTriDest(); // = (ndo)
else
{
swapOTriangle(a, n); // = (ona)
nextOTri(); // = (nao)
if (oldl < 0L)
prevOTriOrigin();// = (nda)
}
break;
}
}
if (origin() != end)
{
// A midpoint is aligned with start and end, this should
// never happen.
throw new RuntimeException("Point "+origin()+" is aligned with "+start+" and "+end);
}
return count;
}
/**
* Check whether an edge can be contracted.
* @return <code>true</code> if this edge can be contracted, <code>flase</code> otherwise.
*/
public final boolean canContract(Vertex n)
{
if (hasAttributes(OUTER))
return false;
if (n.mesh.dim == 3 && !checkInversion(n))
return false;
-
- // Check topology
- HashSet link = origin().getNeighboursNodes();
- link.retainAll(destination().getNeighboursNodes());
- link.remove(Vertex.outer);
- return link.size() < 3;
- //return true;
+ return true;
}
public double [] getTempVector()
{
return tempD;
}
private final boolean checkInversion(Vertex n)
{
Vertex o = origin();
Vertex d = destination();
symOTri(this, work[1]);
// Loop around o to check that triangles will not be inverted
copyOTri(this, work[0]);
work[0].nextOTri();
work[0].prevOTriApex();
double [] v1 = new double[3];
double [] xn = n.getUV();
double [] xo = o.getUV();
do
{
work[0].nextOTriApex();
if (work[0].tri != tri && work[0].tri != work[1].tri && !work[0].hasAttributes(OUTER))
{
work[0].computeNormal3DT();
double [] nu = work[0].getTempVector();
double [] x1 = work[0].origin().getUV();
for (int i = 0; i < 3; i++)
v1[i] = xn[i] - x1[i];
if (Metric3D.prodSca(v1, nu) >= 0.0)
return false;
}
}
while (work[0].destination() != d);
// Loop around d to check that triangles will not be inverted
work[0].prevOTri();
xo = d.getUV();
do
{
work[0].nextOTriApex();
if (work[0].tri != tri && work[0].tri != work[1].tri && !work[0].hasAttributes(OUTER))
{
work[0].computeNormal3DT();
double [] nu = work[0].getTempVector();
double [] x1 = work[0].origin().getUV();
for (int i = 0; i < 3; i++)
v1[i] = xn[i] - x1[i];
if (Metric3D.prodSca(v1, nu) >= 0.0)
return false;
}
}
while (work[0].destination() != o);
return true;
}
// Warning: this vectore is not normalized, it has the same length as
// this.
public void computeNormal3DT()
{
double [] p0 = origin().getUV();
double [] p1 = destination().getUV();
double [] p2 = apex().getUV();
tempD1[0] = p1[0] - p0[0];
tempD1[1] = p1[1] - p0[1];
tempD1[2] = p1[2] - p0[2];
tempD[0] = p2[0] - p0[0];
tempD[1] = p2[1] - p0[1];
tempD[2] = p2[2] - p0[2];
Metric3D.prodVect3D(tempD1, tempD, tempD2);
double norm = Metric3D.norm(tempD2);
if (norm != 0.0)
{
tempD2[0] /= norm;
tempD2[1] /= norm;
tempD2[2] /= norm;
}
Metric3D.prodVect3D(tempD1, tempD2, tempD);
}
public void computeNormal3D()
{
double [] p0 = origin().getUV();
double [] p1 = destination().getUV();
double [] p2 = apex().getUV();
tempD1[0] = p1[0] - p0[0];
tempD1[1] = p1[1] - p0[1];
tempD1[2] = p1[2] - p0[2];
tempD2[0] = p2[0] - p0[0];
tempD2[1] = p2[1] - p0[1];
tempD2[2] = p2[2] - p0[2];
Metric3D.prodVect3D(tempD1, tempD2, tempD);
double norm = Metric3D.norm(tempD);
if (norm != 0.0)
{
tempD[0] /= norm;
tempD[1] /= norm;
tempD[2] /= norm;
}
}
/**
* Contract an edge.
* TODO: Attributes are not checked.
* @param n the resulting vertex
*/
public final void contract(Vertex n)
{
Vertex o = origin();
Vertex d = destination();
/*
* V1 V1
* V3._______._______. V4 V3 .______.______. V4
* \ t3 / \ t4 / \ t3 | t4 /
* \ / \ / \ | /
* \ / t1 \ / \ | /
* o +-------+ d ------> n +
* / \ t2 / \ / | \
* / \ / \ / | \
* / t5 \ / t6 \ / t5 | t6 \
* +-------'-------+ +------+------+
* V5 V2 V6 V5 V2 V6
*/
// this = (odV1)
// Replace o by n in all incident triangles
copyOTri(this, work[0]);
work[0].setDestination(n);
while (true)
{
work[0].setOrigin(n);
work[0].nextOTriOrigin();
if (work[0].destination() == n)
break;
}
// Replace d by n in all incident triangles
symOTri(this, work[0]); // (doV2)
work[0].setDestination(n);
while (true)
{
work[0].setOrigin(n);
work[0].nextOTriOrigin();
// Warning: o has been replaced by n above!
if (work[0].destination() == n)
break;
}
// Update adjacency links. For clarity, o and d are
// written instead of n.
nextOTri(); // (dV1o)
symOTri(this, work[0]); // (V1dV4)
nextOTri(); // (V1od)
symOTri(this, work[1]); // (oV1V3)
work[0].glue(work[1]);
Triangle t3 = work[1].tri;
Vertex V1 = work[1].destination();
if (V1 == Vertex.outer)
{
work[0].setAttributes(OUTER);
work[1].setAttributes(OUTER);
}
nextOTri(); // (odV1)
symOTri(); // (doV2)
nextOTri(); // (oV2d)
symOTri(this, work[0]); // (V2oV5)
nextOTri(); // (V2do)
symOTri(this, work[1]); // (dV2V6)
work[0].glue(work[1]);
Triangle t5 = work[0].tri;
Vertex V2 = work[0].origin();
if (V2 == Vertex.outer)
{
work[0].setAttributes(OUTER);
work[1].setAttributes(OUTER);
}
// Fix links to triangles
V1.tri = t3;
V2.tri = t5;
n.tri = t5;
// Restore 'this' to its initial value
nextOTri(); // (doV2)
clearAttributes(MARKED);
pushAttributes();
symOTri(); // (odV1)
clearAttributes(MARKED);
pushAttributes();
}
public final String toString()
{
String r = "Orientation: "+orientation+"\n";
r += "HashCode Tri: "+tri.hashCode()+"\n";
r += "Attributes: "+attributes+" "+Integer.toHexString(tri.adjPos >> 8)+"\n";
r += "Vertices:\n";
r += " Origin: "+origin()+"\n";
r += " Destination: "+destination()+"\n";
r += " Apex: "+apex();
return r;
}
}
| true | false | null | null |
diff --git a/MeetUpScheduler/src/com/cs310/ubc/meetupscheduler/client/CreateEventView.java b/MeetUpScheduler/src/com/cs310/ubc/meetupscheduler/client/CreateEventView.java
index aff6a24..948ae06 100644
--- a/MeetUpScheduler/src/com/cs310/ubc/meetupscheduler/client/CreateEventView.java
+++ b/MeetUpScheduler/src/com/cs310/ubc/meetupscheduler/client/CreateEventView.java
@@ -1,246 +1,246 @@
package com.cs310.ubc.meetupscheduler.client;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DatePicker;
public class CreateEventView extends Composite implements View {
private final DataObjectServiceAsync objectService = GWT.create(DataObjectService.class);
private ArrayList<HashMap<String, String>> allParks;
//event fields
private String eventName;
private String userName;
private String userEmail;
private String park_name;
private String park_id;
private String eventType;
private String date;
private String startTime;
private String endTime;
//Panel to hold Create Event Components
private VerticalPanel rightPanel = new VerticalPanel();
private VerticalPanel leftPanel = new VerticalPanel();
private HorizontalPanel createEventPanel = new HorizontalPanel();
//Name boxes
private TextBox eventNameBox = new TextBox();
private Label eventNameLabel = new Label("Event Name");
//Date Selector for Event
private DatePicker eventDatePicker = new DatePicker();
private Label eventDatePickerLabel = new Label();
//Time selectors
private ListBox startTimeList = new ListBox();
private ListBox endTimeList = new ListBox();
//Category selector
private ListBox categoriesListBox = new ListBox();
//Park Selector
private ListBox parksListBox = new ListBox();
private SimplePanel viewPanel = new SimplePanel();
private Element nameSpan = DOM.createSpan();
//TODO Have to figure this out
public CreateEventView() {
viewPanel.getElement().appendChild(nameSpan);
initWidget(viewPanel);
}
public CreateEventView(String parkID) {
viewPanel.getElement().appendChild(nameSpan);
initWidget(viewPanel);
park_id = parkID;
}
@Override
public Widget asWidget() {
//Sets the label when a date is selected
eventDatePicker.addValueChangeHandler(new ValueChangeHandler<Date>() {
public void onValueChange(ValueChangeEvent<Date> event) {
Date eventDate = event.getValue();
String eventDateString = DateTimeFormat.getMediumDateFormat().format(eventDate);
eventDatePickerLabel.setText(eventDateString);
}
});
//Default Value for date
eventDatePicker.setValue(new Date(), true);
//populate time lists
setHoursList(startTimeList);
setHoursList(endTimeList);
//categories set-up
categoriesListBox.addItem("Default Category");
populateCategories(categoriesListBox);
categoriesListBox.setVisibleItemCount(1);
//get parks for parks list
getParks(parksListBox);
parksListBox.setVisibleItemCount(1);
Button submitButton = new Button("Submit", new ClickHandler() {
public void onClick(ClickEvent event) {
//TODO: Implement verifier call, submit call, and route to event view tab
setEventFields();
if (verifyFields()) {
createEvent();
}
else {
Window.alert("Please ensure all event fields are filled out");
}
}
});
//Add items to panel
//TODO: fix appearance through sub-panels
leftPanel.add(eventNameLabel);
leftPanel.add(eventNameBox);
leftPanel.add(parksListBox);
leftPanel.add(categoriesListBox);
leftPanel.add(submitButton);
rightPanel.add(eventDatePickerLabel);
rightPanel.add(eventDatePicker);
rightPanel.add(startTimeList);
rightPanel.add(endTimeList);
createEventPanel.add(leftPanel);
createEventPanel.add(rightPanel);
return createEventPanel;
}
private void getParks(final ListBox parksList) {
allParks = MeetUpScheduler.getParks();
addParksToParksListBox(allParks, parksList);
}
private void addParksToParksListBox(ArrayList<HashMap<String, String>> parks, ListBox parksList){
ArrayList<String> parkNames = new ArrayList<String>();
for(int i = 0; i<parks.size(); i++){
parkNames.add(parks.get(i).get("name"));
}
Collections.sort(parkNames);
for(int i = 0; i<parks.size(); i++){
parksList.addItem(parkNames.get(i));
}
}
private String getParkID(String parkName) {
String id = "";
- for (int i=0;i<allParks.size(); i++) {
- if (allParks.get(i).get("name") == parkName) {
- id = allParks.get(i).get("pid");
+ for (int i=0;i<allParks.size(); i++) {
+ if (allParks.get(i).get("name").equals(parkName)) {
+ id = allParks.get(i).get("id");
}
}
return id;
}
private void setEventFields() {
eventName = eventNameBox.getValue();
LoginInfo loginInfo = MeetUpScheduler.SharedData.getLoginInfo();
userName = loginInfo.getNickname();
userEmail = loginInfo.getEmailAddress();
park_name = parksListBox.getValue(parksListBox.getSelectedIndex());
park_id = getParkID(park_name);
eventType = categoriesListBox.getValue(categoriesListBox.getSelectedIndex());
date = DateTimeFormat.getMediumDateFormat().format(eventDatePicker.getValue());
startTime = startTimeList.getValue(startTimeList.getSelectedIndex());
endTime = endTimeList.getValue(endTimeList.getSelectedIndex());
}
private boolean verifyFields() {
//TODO: specify conditions for field verification, add field specific errors
if (eventName == null || userName == null || park_name == null || date == null || startTime == null || endTime == null) return false;
return true;
}
//TODO: Use the ENUM from event for the field names. Note: breaks compilation at this point
private void createEvent() {
HashMap<String, String> event = new HashMap<String, String>();
event.put("name", eventName);
event.put("park_name", park_name);
event.put("park_id", park_id);
event.put("creator_name", userName);
event.put("creator_email", userEmail);
event.put("category", eventType);
event.put("date", date);
event.put("start_time", startTime);
event.put("end_time", endTime);
event.put("num_attending", "1");
event.put("attending_names", userName);
event.put("attending_emails", userEmail);
//TODO: move to static data object? Make call to reload method to re get events and load views
objectService.add("Event", event, new AsyncCallback<HashMap<String, String>>() {
public void onFailure(Throwable error) {
System.out.println("Flip a table! (>o.o)> _|__|_)");
}
public void onSuccess(HashMap<String, String> newEvent) {
//TODO: Add call to helper to scheduler to get event view based on event id
System.out.println(newEvent);
Window.alert("Event Created with ID " + newEvent.get("id"));
}
});
}
private void setHoursList(ListBox list) {
for (int i=0; i<=23; i++ ) {
list.addItem(i+":00");
}
list.setVisibleItemCount(1);
}
private void populateCategories(ListBox categoriesList) {
categoriesList.addItem("Sack-race");
categoriesList.addItem("Larping");
categoriesList.addItem("Ultimate");
categoriesList.addItem("Spelling-B");
categoriesList.addItem("Judo");
categoriesList.addItem("Arctic Char Fishing");
categoriesList.addItem("Treasure Hunt");
categoriesList.addItem("Night Soccer");
categoriesList.addItem("Dog Show");
categoriesList.addItem("Chili Cook-off");
}
@Override
public void setName(String name) {
nameSpan.setInnerText("Create Event " + name);
}
}
diff --git a/MeetUpScheduler/src/com/cs310/ubc/meetupscheduler/client/EventView.java b/MeetUpScheduler/src/com/cs310/ubc/meetupscheduler/client/EventView.java
index e9694f3..295d7ae 100644
--- a/MeetUpScheduler/src/com/cs310/ubc/meetupscheduler/client/EventView.java
+++ b/MeetUpScheduler/src/com/cs310/ubc/meetupscheduler/client/EventView.java
@@ -1,302 +1,302 @@
package com.cs310.ubc.meetupscheduler.client;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.maps.client.Maps;
import com.google.gwt.maps.client.control.LargeMapControl3D;
import com.google.gwt.maps.client.control.MapTypeControl;
import com.google.gwt.maps.client.geom.LatLng;
import com.google.gwt.maps.client.overlay.Marker;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
public class EventView extends Composite implements View{
/**
* EventView for looking at the details of a specific event
*
* @author Ben
*/
private final int MAP_HEIGHT = 400;
private final int MAP_WIDTH = 500;
private TextBox loadText = new TextBox();
private HorizontalPanel rootPanel = new HorizontalPanel();
private Label eventName = new Label();
private Button joinButton = new Button();
private TextBox joinName = new TextBox();
private Button loadButton = new Button();
private VerticalPanel parkPanel = new VerticalPanel();
private ListBox attendeesBox = new ListBox();
private VerticalPanel attendeePanel = new VerticalPanel();
private VerticalPanel infoPanel = new VerticalPanel();
private Label eventCreator = new Label();
private Label eventLoc = new Label();
private Label eventTime = new Label();
private Label eventNotes = new Label();
private Label eventCategory = new Label();
private Button shareButton = new Button();
private MapWidget eventMap;
private ArrayList<String> members = new ArrayList<String>();
private Integer attendeeCount = 0;
private Label attCountLabel = new Label();
private ArrayList<HashMap<String, String>> allEvents;
private SimplePanel viewPanel = new SimplePanel();
private ArrayList<HashMap<String, String>> allParks;
Element nameSpan = DOM.createSpan();
private HashMap<String, String> event = new HashMap<String, String>();
private LoginInfo loginInfo;
private final DataObjectServiceAsync objectService = GWT.create(DataObjectService.class);
public EventView() {
viewPanel.getElement().appendChild(nameSpan);
loadData();
initWidget(viewPanel);
}
public EventView(int eventID){
viewPanel.getElement().appendChild(nameSpan);
loadData();
initWidget(viewPanel);
loadEvent(eventID);
}
// TODO: Make this into a working constructor that takes an eventID string
// public Widget createPage (String eventID) {
// currentEvent = event;
// //Initialize Map, needs a key before it can be deployed
// Maps.loadMapsApi("", "2", false, new Runnable() {
// public void run() {
// buildUI();
// }
// });
// return panel;
// }
@Override
public Widget asWidget() {
//Initialize Map, needs a key before it can be deployed
Maps.loadMapsApi("", "2", false, new Runnable() {
public void run() {
buildUI();
}
});
return rootPanel;
}
/**
* Constructs the UI elements of EventView
*/
public void buildUI(){
loginInfo = MeetUpScheduler.SharedData.getLoginInfo();
// set up the Map
// TODO: Make the map relevant. Load markers of the location, etc.
LatLng vancouver = LatLng.newInstance(49.258480, -123.094574);
eventMap = new MapWidget(vancouver, 11);
eventMap.setPixelSize(MAP_WIDTH, MAP_HEIGHT);
eventMap.setScrollWheelZoomEnabled(true);
eventMap.addControl(new LargeMapControl3D());
eventMap.checkResizeAndCenter();
eventMap.addControl(new MapTypeControl());
// Sets the eventLoad button to load the events
loadText.setText("Enter the number of the event to load");
loadButton.setText("Click to load an event");
loadButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
loadEvent(Integer.parseInt(loadText.getText()));
}
});
//set up the shareButton
//TODO: Make this work with the proper URL
shareButton.setText("Share on Google Plus.");
shareButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event){
com.google.gwt.user.client.Window.open("https://plus.google.com/share?url=vancitymeetupscheduler.appspot.com", "Share the Meetup Scheduler!", "");
}
});
//set up the joinButton
joinButton.setText("Join event!");
joinButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent clickEvent) {
members.add(loginInfo.getNickname());
//Add username to event
String newNames = event.get("attending_names") + "," + loginInfo.getNickname();
event.put("attending_names", newNames);
//Add user email to event
String newEmails = event.get("attending_emails") + "," + loginInfo.getEmailAddress();
event.put("attending_emails", newEmails);
//Increment number attending
Integer numAttending = Integer.parseInt(event.get("num_attending"));
numAttending++;
event.put("num_attending", numAttending.toString());
objectService.update("Event", "id=="+event.get("id"), event, new AsyncCallback<ArrayList<HashMap<String, String>>>() {
public void onFailure(Throwable error) {
System.out.println("Joining the event failed!");
}
public void onSuccess(ArrayList<HashMap<String, String>> newEvent) {
attendeesBox.clear();
setUpAttendees();
joinButton.setEnabled(false);
- Window.alert("You are attending the event with ID " + newEvent.get(0).get("id"));
+ Window.alert("You are attending this event!");
}
});
}
});
setUpInfoPanel();
// Add items to panels
parkPanel.add(eventMap);
attendeePanel.add(attCountLabel);
attendeePanel.add(attendeesBox);
rootPanel.add(loadText);
rootPanel.add(loadButton);
rootPanel.add(infoPanel);
rootPanel.add(joinButton);
rootPanel.add(shareButton);
rootPanel.add(parkPanel);
}
/**
* This loads the specifics of the event into the info panel.
*
* @param eventID: The id of the event you want to load to the page.
*
* TODO: - Add event positions to map
* - Get the park information loaded into a parks page
*/
private void loadEvent(int eventID) {
if (allEvents != null && allEvents.size() > 0){
try {
for (int i = 0; i < allEvents.size(); i++){
if (Integer.parseInt(allEvents.get(i).get("id")) == eventID){
event = allEvents.get(i);
eventCreator.setText("Welcome to " + event.get("creator_name") + "'s event.");
eventName.setText("The name of the event is " + event.get("name"));
eventTime.setText("The event is from " + event.get("start_time") + " to " + event.get("end_time") + " on " + event.get("date"));
eventLoc.setText("The event is at " + event.get("park_name") + ".");
//eventMap.checkResizeAndCenter();
eventCategory.setText("This event is in the category: " + event.get("category"));
ArrayList<String> attendees = new ArrayList<String>(Arrays.asList(event.get("attending_names").split(",")));
members.clear();
for (String attendee : attendees){
members.add(attendee);
}
attendeesBox.clear();
setUpAttendees();
zoomMap();
ArrayList<String> attendingEmails = new ArrayList<String>(Arrays.asList(event.get("attending_emails").split(",")));
if (attendingEmails.contains(loginInfo.getEmailAddress()))
joinButton.setEnabled(false);
else
joinButton.setEnabled(true);
}
}
} catch (Exception e) {
e.printStackTrace();
Window.alert("There is no event " + eventID + ".");
}
}
else Window.alert("No events!");
}
private void zoomMap(){
for(int i=0; i<allParks.size(); i++){
if(allParks.get(i).get("name").equals(event.get("park_name"))){
String latLong = allParks.get(i).get("google_map_dest");
int index = latLong.indexOf(",");
double lat = Double.parseDouble(latLong.substring(0, index));
double lon = Double.parseDouble(latLong.substring(index+1));
eventMap.setCenter(LatLng.newInstance(lat, lon), 17);
final Marker eventMarker = new Marker(LatLng.newInstance(lat, lon));
eventMap.addOverlay(eventMarker);
}
}
}
/**
* Loads all existing Events into a list.
*/
private void loadData(){
allEvents = MeetUpScheduler.getEvents();
allParks = MeetUpScheduler.getParks();
}
/**
* This creates the panel with the relevant information of the event.
*/
private void setUpInfoPanel() {
infoPanel.add(eventCreator);
infoPanel.add(eventCategory);
infoPanel.add(eventLoc);
infoPanel.add(eventTime);
infoPanel.add(attendeePanel);
infoPanel.add(eventNotes);
eventNotes.setText("This is the information for the event. Needs to be persistent.");
}
/**
* Helper to manage the list of attendees at the event.
*/
private void setUpAttendees() {
for (int i = 0; i< members.size(); i++){
attendeesBox.addItem(members.get(i));
}
attendeesBox.setVisibleItemCount(members.size());
attendeeCount = members.size();
attCountLabel.setText(attendeeCount + " people are attending.");
}
@Override
public void setName(String name) {
nameSpan.setInnerText("Event " + name);
}
//TODO:
/**
* Add styling with CSS
* Fix up the interface to make it look nice
* make Attendees a JDO, and persistent
* Catch exceptions from creating jdo objects, etc.
*
*/
}
| false | false | null | null |
diff --git a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/wizards/JoinSessionWizard.java b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/wizards/JoinSessionWizard.java
index 88df0a9bf..60eb1169c 100644
--- a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/wizards/JoinSessionWizard.java
+++ b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/wizards/JoinSessionWizard.java
@@ -1,446 +1,446 @@
/*
* DPP - Serious Distributed Pair Programming
* (c) Freie Universitaet Berlin - Fachbereich Mathematik und Informatik - 2006
* (c) Riad Djemili - 2006
*
* 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 1, 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package de.fu_berlin.inf.dpp.ui.wizards;
import java.lang.reflect.InvocationTargetException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Button;
import de.fu_berlin.inf.dpp.FileList;
import de.fu_berlin.inf.dpp.invitation.IIncomingInvitationProcess;
import de.fu_berlin.inf.dpp.invitation.IInvitationProcess.IInvitationUI;
import de.fu_berlin.inf.dpp.invitation.IInvitationProcess.State;
import de.fu_berlin.inf.dpp.net.JID;
/**
* A wizard that guides the user through an incoming invitiation process.
*
* Todo: - Enhance Usability of this dialog: - Automatically switch to follow
* mode - Make a suggestion for the name of the project - Suggest if the project
* is a CVS project that the user checks it out and offers an option to transfer
* the settings
*
* @author rdjemili
*/
public class JoinSessionWizard extends Wizard implements IInvitationUI {
private static Logger log = Logger.getLogger(JoinSessionWizard.class.getName());
private ShowDescriptionPage descriptionPage;
private WizardDialogAccessable myWizardDlg;
private EnterNamePage namePage;
private final IIncomingInvitationProcess process;
private Display display = null;
/**
* A wizard page that displays the name of the inviter and the description
* provided with the invitation.
*/
private class ShowDescriptionPage extends WizardPage {
protected ShowDescriptionPage() {
super("firstPage");
setTitle("Session Invitation");
setDescription("You have been invited to join on a session for a "
+ "shared project. Click next if you want to accept the invitation.");
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.dialogs.IDialogPage
*/
public void createControl(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(2, false));
Label inviterLabel = new Label(composite, SWT.NONE);
inviterLabel.setText("Inviter");
Text inviterText = new Text(composite, SWT.READ_ONLY | SWT.SINGLE | SWT.BORDER);
inviterText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
inviterText.setText(process.getPeer().getBase());
Label descriptionLabel = new Label(composite, SWT.NONE);
descriptionLabel.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, false, false));
descriptionLabel.setText("Project");
Text descriptionText = new Text(composite, SWT.READ_ONLY | SWT.BORDER);
descriptionText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
descriptionText.setText(process.getDescription());
setControl(composite);
}
}
/**
* A wizard page that allows to enter the new project name or to choose to
* overwrite the project selected by the {@link ProjectSelectionPage}.
*/
private class EnterNamePage extends WizardPage {
private Text newProjectNameText;
private Button projUpd;
protected EnterNamePage() {
super("namePage");
setPageComplete(false);
setTitle("Session Invitation");
setDescription("Enter the name of the new project.");
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.dialogs.IDialogPage
*/
public void createControl(Composite parent) {
if ( process.getState()==State.CANCELED)
return;
requestRemoteFileList();
if (process.getRemoteFileList() == null)
getShell().close();
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(2, false));
GridData gridData;
IProject project = getLocalProject();
Label helpLabel = new Label(composite, SWT.WRAP);
helpLabel.setText(getHelpText(project));
helpLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false, 2, 1));
Button projCopy = new Button(composite, SWT.RADIO);
projCopy.setText("Create new project copy");
projCopy.setSelection(true);
gridData = new GridData(SWT.FILL, SWT.BEGINNING, false, false,2,1);
gridData.verticalIndent = 20;
projCopy.setLayoutData(gridData);
Label newProjectNameLabel = new Label(composite, SWT.NONE);
newProjectNameLabel.setText("Project name");
gridData = new GridData(SWT.FILL, SWT.BEGINNING, false, false);
gridData.verticalIndent = 3;
newProjectNameLabel.setLayoutData(gridData);
newProjectNameText = new Text(composite, SWT.BORDER);
gridData = new GridData(SWT.FILL, SWT.BEGINNING, true, false);
gridData.verticalIndent = 1;
newProjectNameText.setLayoutData(gridData);
newProjectNameText.setFocus();
newProjectNameText.setText(findProjectNameProposal());
projUpd = new Button(composite, SWT.RADIO);
projUpd.setText("Update and use existing project");
if (project==null)
projUpd.setEnabled(false);
else
projUpd.setText("Update and use existing project ("+ project.getName() +")");
gridData = new GridData(SWT.FILL, SWT.BEGINNING, false, false,2,1);
gridData.verticalIndent = 20;
projUpd.setLayoutData(gridData);
attachListeners();
setControl(composite);
updatePageComplete();
}
/**
* @return the project name of the project that should be created or
* <code>null</code> if the user chose to overwrite an
* existing project.
*/
public String getNewProjectName() {
return projUpd.getSelection()?null:newProjectNameText.getText();
}
private IProject getLocalProject() {
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IProject[] projects = workspace.getRoot().getProjects();
int maxMatch = 0;
IProject selectedProject = null;
for (int i = 0; i < projects.length; i++) {
if (!projects[i].isOpen())
continue;
int match = getMatch(projects[i]);
if (match > maxMatch) {
maxMatch = match;
selectedProject = projects[i];
}
}
return selectedProject;
}
private int getMatch(IProject project) {
try {
FileList remoteFileList = process.getRemoteFileList();
return remoteFileList.match(new FileList(project));
} catch (CoreException e) {
log.log(Level.FINE, "Couldn't calculate match for project " + project, e);
return 0;
}
}
private void requestRemoteFileList() {
try {
getContainer().run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) {
process.requestRemoteFileList(monitor);
}
});
} catch (InvocationTargetException e) {
log.log(Level.WARNING, "Exception while requesting remote file list", e);
} catch (InterruptedException e) {
log.log(Level.FINE, "Request of remote file list canceled/interrupted", e);
}
}
private String getHelpText(IProject project) {
if (project == null) {
return "Project replication will start from scratch.";
}
return "It has been detected that one of your local projects (" + project.getName()
+ ") has an identicallness of " + getMatch(project) + "%.\n"
+ "This fact will used to shorten the process of "
+ "replicating the remote project.";
}
private void attachListeners() {
newProjectNameText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
updatePageComplete();
}
});
}
private void updatePageComplete() {
String newText = newProjectNameText.getText();
if (newText.length() == 0) {
setMessage(null);
setErrorMessage("Please set a project name");
setPageComplete(false);
} else {
if (projectIsUnique(newText)) {
setMessage(null);
setErrorMessage(null);
setPageComplete(true);
} else {
setMessage(null);
setErrorMessage("A project with this name already exists");
setPageComplete(false);
}
}
}
}
public JoinSessionWizard(IIncomingInvitationProcess process) {
this.process = process;
setWindowTitle("Session Invitation");
setHelpAvailable(false);
setNeedsProgressMonitor(true);
display=Display.getCurrent();
}
public boolean projectIsUnique(String name) {
// Then check with all the projects
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IProject[] projects = workspace.getRoot().getProjects();
return projectIsUnique(name, projects);
}
public boolean projectIsUnique(String name, IProject[] projects) {
for (int i = 0; i < projects.length; i++) {
IProject p = projects[i];
if (p.getName().equals(name))
return false;
}
return true;
}
public String findProjectNameProposal() {
// Start with the projects name
String projectProposal = process.getProjectName();
// Then check with all the projects
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IProject[] projects = workspace.getRoot().getProjects();
if (projectIsUnique(projectProposal, projects)) {
return projectProposal;
} else {
// Name is already in use!
Pattern p = Pattern.compile("^(.*)(\\d+)$");
Matcher m = p.matcher(projectProposal);
int i;
// Check whether the name ends in a number or not
if (m.find()) {
projectProposal = m.group(1).trim();
i = Integer.parseInt(m.group(2));
} else {
i = 2;
}
// Then find the next available number
while (!projectIsUnique(projectProposal + " " + i, projects)) {
i++;
}
return projectProposal + " " + i;
}
}
@Override
public void addPages() {
descriptionPage = new ShowDescriptionPage();
namePage = new EnterNamePage();
addPage(descriptionPage);
addPage(namePage);
}
@Override
public void createPageControls(Composite pageContainer) {
descriptionPage.createControl(pageContainer);
// create namePage lazily
}
@Override
public boolean performFinish() {
if ( process.getState()==State.CANCELED)
return true;
final IProject project = namePage.getLocalProject();
final String newProjectName = namePage.getNewProjectName();
try {
getContainer().run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException,
InterruptedException {
process.accept(project, newProjectName, monitor);
}
});
} catch (InvocationTargetException e) {
log.log(Level.WARNING, "Exception while requesting remote file list", e);
} catch (InterruptedException e) {
log.log(Level.FINE, "Request of remote file list canceled/interrupted", e);
}
return true;
}
@Override
public boolean performCancel() {
- process.cancel(null, false);
+ process.cancel("Cancel Invitation Process!", false);
return super.performCancel();
}
public void cancel(final String errorMsg, final boolean replicated) {
display.asyncExec(new Runnable() {
public void run() {
cancelRunASync(errorMsg, replicated);
}} );
}
private void cancelRunASync(String errorMsg, boolean replicated){
if (replicated) {
if (errorMsg != null) {
MessageDialog.openError(getShell(), "Invitation aborted",
"Could not complete invitation. ("+ errorMsg + ")");
} else {
MessageDialog.openInformation(getShell(), "Invitation cancelled",
"Invitation was cancelled by peer.");
}
}
myWizardDlg.setWizardButtonEnabled(IDialogConstants.BACK_ID, false);
myWizardDlg.setWizardButtonEnabled(IDialogConstants.NEXT_ID, false);
myWizardDlg.setWizardButtonEnabled(IDialogConstants.FINISH_ID, false);
}
public void updateInvitationProgress(JID jid) {
// ignored, not needed atm
}
public void setWizardDlg(WizardDialogAccessable wd) {
myWizardDlg=wd;
}
public void runGUIAsynch(Runnable runnable) {
// TODO Auto-generated method stub
}
}
| true | false | null | null |
diff --git a/api/src/main/java/org/jboss/marshalling/FieldSetter.java b/api/src/main/java/org/jboss/marshalling/FieldSetter.java
index cfbcf82..79d9d15 100644
--- a/api/src/main/java/org/jboss/marshalling/FieldSetter.java
+++ b/api/src/main/java/org/jboss/marshalling/FieldSetter.java
@@ -1,243 +1,243 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2009, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.marshalling;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.security.AccessController;
import java.security.PrivilegedAction;
/**
* A setter for a (possibly final) field, which allows for correct object initialization of {@link java.io.Serializable} objects
* with {@code readObject()} methods, even in the presence of {@code final} fields.
*/
public final class FieldSetter {
private final Field field;
private FieldSetter(final Field field) {
this.field = field;
}
/**
* Set the value of the field to the given object.
*
* @param instance the instance to set
* @param value the new value
* @throws IllegalArgumentException if the given instance is {@code null} or not of the correct class
*/
public void set(Object instance, Object value) throws IllegalArgumentException {
try {
field.set(instance, value);
} catch (IllegalAccessException e) {
throw illegalState(e);
}
}
/**
* Set the value of the field to the given value.
*
* @param instance the instance to set
* @param value the new value
* @throws IllegalArgumentException if the given instance is {@code null} or not of the correct class
*/
public void setBoolean(Object instance, boolean value) throws IllegalArgumentException {
try {
field.setBoolean(instance, value);
} catch (IllegalAccessException e) {
throw illegalState(e);
}
}
/**
* Set the value of the field to the given value.
*
* @param instance the instance to set
* @param value the new value
* @throws IllegalArgumentException if the given instance is {@code null} or not of the correct class
*/
public void setByte(Object instance, byte value) throws IllegalArgumentException {
try {
field.setByte(instance, value);
} catch (IllegalAccessException e) {
throw illegalState(e);
}
}
/**
* Set the value of the field to the given value.
*
* @param instance the instance to set
* @param value the new value
* @throws IllegalArgumentException if the given instance is {@code null} or not of the correct class
*/
public void setChar(Object instance, char value) throws IllegalArgumentException {
try {
field.setChar(instance, value);
} catch (IllegalAccessException e) {
throw illegalState(e);
}
}
/**
* Set the value of the field to the given value.
*
* @param instance the instance to set
* @param value the new value
* @throws IllegalArgumentException if the given instance is {@code null} or not of the correct class
*/
public void setDouble(Object instance, double value) throws IllegalArgumentException {
try {
field.setDouble(instance, value);
} catch (IllegalAccessException e) {
throw illegalState(e);
}
}
/**
* Set the value of the field to the given value.
*
* @param instance the instance to set
* @param value the new value
* @throws IllegalArgumentException if the given instance is {@code null} or not of the correct class
*/
public void setFloat(Object instance, float value) throws IllegalArgumentException {
try {
field.setFloat(instance, value);
} catch (IllegalAccessException e) {
throw illegalState(e);
}
}
/**
* Set the value of the field to the given value.
*
* @param instance the instance to set
* @param value the new value
* @throws IllegalArgumentException if the given instance is {@code null} or not of the correct class
*/
public void setInt(Object instance, int value) throws IllegalArgumentException {
try {
field.setInt(instance, value);
} catch (IllegalAccessException e) {
throw illegalState(e);
}
}
/**
* Set the value of the field to the given value.
*
* @param instance the instance to set
* @param value the new value
* @throws IllegalArgumentException if the given instance is {@code null} or not of the correct class
*/
public void setLong(Object instance, long value) throws IllegalArgumentException {
try {
field.setLong(instance, value);
} catch (IllegalAccessException e) {
throw illegalState(e);
}
}
/**
* Set the value of the field to the given value.
*
* @param instance the instance to set
* @param value the new value
* @throws IllegalArgumentException if the given instance is {@code null} or not of the correct class
*/
public void setShort(Object instance, short value) throws IllegalArgumentException {
try {
field.setShort(instance, value);
} catch (IllegalAccessException e) {
throw illegalState(e);
}
}
private IllegalStateException illegalState(final IllegalAccessException e) {
return new IllegalStateException("Unexpected illegal access of accessible field", e);
}
/**
* Get an instance for the current class.
*
* @param clazz the class containing the field
* @param name the name of the field
* @return the {@code Field} instance
* @throws SecurityException if the field does not belong to the caller's class, or the field is static
* @throws IllegalArgumentException if there is no field of the given name on the given class
*/
public static <T> FieldSetter get(final Class<T> clazz, final String name) throws SecurityException, IllegalArgumentException {
- final Class[] stackTrace = getInstance.STACK_TRACE_READER.getClassContext();
+ final Class[] stackTrace = Holder.STACK_TRACE_READER.getClassContext();
if (stackTrace[2] != clazz) {
throw new SecurityException("Cannot get accessible field from someone else's class");
}
return new FieldSetter(AccessController.doPrivileged(new GetFieldAction(clazz, name)));
}
- private static final class getInstance {
+ private static final class Holder {
static final StackTraceReader STACK_TRACE_READER;
static {
STACK_TRACE_READER = AccessController.doPrivileged(new PrivilegedAction<StackTraceReader>() {
public StackTraceReader run() {
return new StackTraceReader();
}
});
}
- private getInstance() {
+ private Holder() {
}
static final class StackTraceReader extends SecurityManager {
protected Class[] getClassContext() {
return super.getClassContext();
}
}
}
private static class GetFieldAction implements PrivilegedAction<Field> {
private final Class<?> clazz;
private final String name;
private GetFieldAction(final Class<?> clazz, final String name) {
this.clazz = clazz;
this.name = name;
}
public Field run() {
try {
final Field field = clazz.getDeclaredField(name);
final int modifiers = field.getModifiers();
if (Modifier.isStatic(modifiers)) {
throw new SecurityException("Cannot get access to static field '" + name + "'");
}
field.setAccessible(true);
return field;
} catch (NoSuchFieldException e) {
throw new IllegalArgumentException("No such field '" + name + "'", e);
}
}
}
}
| false | false | null | null |
diff --git a/src/main/java/com/samskivert/mustache/Mustache.java b/src/main/java/com/samskivert/mustache/Mustache.java
index 57cc278..71ebbb0 100644
--- a/src/main/java/com/samskivert/mustache/Mustache.java
+++ b/src/main/java/com/samskivert/mustache/Mustache.java
@@ -1,651 +1,654 @@
//
// JMustache - A Java implementation of the Mustache templating language
// http://github.com/samskivert/jmustache/blob/master/LICENSE
package com.samskivert.mustache;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Provides <a href="http://mustache.github.com/">Mustache</a> templating services.
*
* <p> Basic usage:
* <pre>{@code
* String source = "Hello {{arg}}!";
* Template tmpl = Mustache.compiler().compile(source);
* Map<String, Object> context = new HashMap<String, Object>();
* context.put("arg", "world");
* tmpl.execute(context); // returns "Hello world!"
* }</pre>
*/
public class Mustache
{
/** An interface to the Mustache compilation process. See {@link Mustache}. */
public static class Compiler
{
/** Whether or not HTML entities are escaped by default. */
public final boolean escapeHTML;
/** Whether or not standards mode is enabled. */
public final boolean standardsMode;
/** A value to use when a variable resolves to null. If this value is null (which is the
* default null value), an exception will be thrown. If {@link #missingIsNull} is also
* true, this value will be used when a variable cannot be resolved. */
public final String nullValue;
/** If this value is true, missing variables will be treated like variables that return
* null. {@link #nullValue} will be used in their place, assuming {@link #nullValue} is
* configured to a non-null value. */
public final boolean missingIsNull;
/** The template loader in use during this compilation. */
public final TemplateLoader loader;
/** The collector used by templates compiled with this compiler. */
public final Collector collector;
/** Compiles the supplied template into a repeatedly executable intermediate form. */
public Template compile (String template) {
return compile(new StringReader(template));
}
/** Compiles the supplied template into a repeatedly executable intermediate form. */
public Template compile (Reader source) {
return Mustache.compile(source, this);
}
/** Returns a compiler that either does or does not escape HTML by default. */
public Compiler escapeHTML (boolean escapeHTML) {
return new Compiler(escapeHTML, this.standardsMode, this.nullValue, this.missingIsNull,
this.loader, this.collector);
}
/** Returns a compiler that either does or does not use standards mode. Standards mode
* disables the non-standard JMustache extensions like looking up missing names in a parent
* context. */
public Compiler standardsMode (boolean standardsMode) {
return new Compiler(this.escapeHTML, standardsMode, this.nullValue, this.missingIsNull,
this.loader, this.collector);
}
/** Returns a compiler that will use the given value for any variable that is missing, or
* otherwise resolves to null. This is like {@link #nullValue} except that it returns the
* supplied default for missing keys and existing keys that return null values. */
public Compiler defaultValue (String defaultValue) {
return new Compiler(this.escapeHTML, this.standardsMode, defaultValue, true,
this.loader, this.collector);
}
/** Returns a compiler that will use the given value for any variable that resolves to
* null, but will still raise an exception for variables for which an accessor cannot be
* found. This is like {@link #defaultValue} except that it differentiates between missing
* accessors, and accessors that exist but return null.
* <ul>
* <li>In the case of a Java object being used as a context, if no field or method can be
* found for a variable, an exception will be raised.</li>
* <li>In the case of a {@link Map} being used as a context, all possible accessors are
* assumed to exist (but potentially return null), and no exception will ever be
* raised.</li>
* </ul> */
public Compiler nullValue (String nullValue) {
return new Compiler(this.escapeHTML, this.standardsMode, nullValue, false,
this.loader, this.collector);
}
/** Returns a compiler configured to use the supplied template loader to handle partials. */
public Compiler withLoader (TemplateLoader loader) {
return new Compiler(this.escapeHTML, this.standardsMode, this.nullValue,
this.missingIsNull, loader, this.collector);
}
/** Returns a compiler configured to use the supplied collector. */
public Compiler withCollector (Collector collector) {
return new Compiler(this.escapeHTML, this.standardsMode, this.nullValue,
this.missingIsNull, this.loader, collector);
}
protected Compiler (boolean escapeHTML, boolean standardsMode, String nullValue,
boolean missingIsNull, TemplateLoader loader, Collector collector) {
this.escapeHTML = escapeHTML;
this.standardsMode = standardsMode;
this.nullValue = nullValue;
this.missingIsNull = missingIsNull;
this.loader = loader;
this.collector = collector;
}
}
/** Used to handle partials. */
public interface TemplateLoader
{
/** Returns a reader for the template with the supplied name.
* @throws Exception if the template could not be loaded for any reason. */
public Reader getTemplate (String name) throws Exception;
}
/** Used to read variables from values. */
public interface VariableFetcher
{
/** Reads the so-named variable from the supplied context object. */
Object get (Object ctx, String name) throws Exception;
}
/** Handles interpreting objects as collections. */
public interface Collector
{
/** Returns an iterator that can iterate over the supplied value, or null if the value is
* not a collection. */
Iterator<?> toIterator (final Object value);
/** Creates a fetcher for a so-named variable in the supplied context object, which will
* never be null. The fetcher will be cached and reused for future contexts for which
* {@code octx.getClass().equals(nctx.getClass()}. */
VariableFetcher createFetcher (Object ctx, String name);
}
/**
* Returns a compiler that escapes HTML by default and does not use standards mode.
*/
public static Compiler compiler ()
{
return new Compiler(true, false, null, true, FAILING_LOADER, new DefaultCollector());
}
/**
* Compiles the supplied template into a repeatedly executable intermediate form.
*/
protected static Template compile (Reader source, Compiler compiler)
{
Accumulator accum = new Parser(compiler).parse(source);
return new Template(accum.finish(), compiler);
}
private Mustache () {} // no instantiateski
protected static void restoreStartTag (StringBuilder text, Delims starts)
{
text.insert(0, starts.start1);
if (starts.start2 != NO_CHAR) {
text.insert(1, starts.start2);
}
}
protected static String escapeHTML (String text)
{
for (String[] escape : ATTR_ESCAPES) {
text = text.replace(escape[0], escape[1]);
}
return text;
}
protected static boolean allowsWhitespace (char typeChar)
{
return (typeChar == '=') || // change delimiters
(typeChar == '!'); // comment
}
protected static final int TEXT = 0;
protected static final int MATCHING_START = 1;
protected static final int MATCHING_END = 2;
protected static final int TAG = 3;
// a hand-rolled parser; whee!
protected static class Parser {
final Delims delims = new Delims();
final StringBuilder text = new StringBuilder();
Reader source;
Accumulator accum;
int state = TEXT;
int line = 1, column = 0;
int tagStartColumn = -1;
boolean skipNewline = false;
public Parser (Compiler compiler) {
this.accum = new Accumulator(compiler);
}
public Accumulator parse (Reader source) {
this.source = source;
while (true) {
char c;
try {
int v = source.read();
if (v == -1) {
break;
}
c = (char)v;
} catch (IOException e) {
throw new MustacheException(e);
}
if (c == '\n') {
column = 0;
line++;
// skip this newline character if we're configured to do so; TODO: handle CR
if (skipNewline) {
skipNewline = false;
continue;
}
} else {
column++;
skipNewline = false;
}
parseChar(c);
}
// accumulate any trailing text
switch (state) {
case TAG:
restoreStartTag(text, delims);
break;
case MATCHING_END:
restoreStartTag(text, delims);
text.append(delims.end1);
break;
case MATCHING_START:
text.append(delims.start1);
break;
// case TEXT: // do nothing
}
accum.addTextSegment(text);
return accum;
}
protected void parseChar (char c) {
switch (state) {
case TEXT:
if (c == delims.start1) {
state = MATCHING_START;
tagStartColumn = column;
if (delims.start2 == NO_CHAR) {
parseChar(NO_CHAR);
}
} else {
text.append(c);
}
break;
case MATCHING_START:
if (c == delims.start2) {
accum.addTextSegment(text);
state = TAG;
} else {
text.append(delims.start1);
state = TEXT;
parseChar(c);
}
break;
case TAG:
if (c == delims.end1) {
state = MATCHING_END;
if (delims.end2 == NO_CHAR) {
parseChar(NO_CHAR);
}
} else if (c == delims.start1 && text.length() > 0) {
// if we've already matched some tag characters and we see a new start tag
// character (e.g. "{{foo {" but not "{{{"), treat the already matched text as
// plain text and start matching a new tag from this point
restoreStartTag(text, delims);
accum.addTextSegment(text);
tagStartColumn = column;
if (delims.start2 == NO_CHAR) {
accum.addTextSegment(text);
state = TAG;
} else {
state = MATCHING_START;
}
} else {
text.append(c);
}
break;
case MATCHING_END:
if (c == delims.end2) {
if (text.charAt(0) == '=') {
delims.updateDelims(text.substring(1, text.length()-1));
text.setLength(0);
} else {
// if we haven't remapped the delimiters, and the tag starts with {{{ then
// require that it end with }}} and disable HTML escaping
if (delims.isDefault() && text.charAt(0) == delims.start1) {
try {
// we've only parsed }} at this point, so we have to slurp in
// another character from the input stream and check it
int end3 = (char)source.read();
if (end3 != '}') {
throw new MustacheParseException(
"Invalid triple-mustache tag: {{{" + text + "}}", line);
}
} catch (IOException e) {
throw new MustacheException(e);
}
// convert it into (equivalent) {{&text}} which addTagSegment handles
text.replace(0, 1, "&");
}
// process the tag between the mustaches
accum = accum.addTagSegment(text, line);
skipNewline = (tagStartColumn == 1) && accum.justOpenedOrClosedBlock();
}
state = TEXT;
} else {
text.append(delims.end1);
state = TAG;
parseChar(c);
}
break;
}
}
}
protected static class Delims {
public char start1 = '{';
public char start2 = '{';
public char end1 = '}';
public char end2 = '}';
public boolean isDefault () {
return start1 == '{' && start2 == '{' && end1 == '}' && end2 == '}';
}
public void updateDelims (String dtext) {
String errmsg = "Invalid delimiter configuration '" + dtext + "'. Must be of the " +
"form {{=1 2=}} or {{=12 34=}} where 1, 2, 3 and 4 are delimiter chars.";
String[] delims = dtext.split(" ");
if (delims.length != 2) throw new MustacheException(errmsg);
switch (delims[0].length()) {
case 1:
start1 = delims[0].charAt(0);
start2 = NO_CHAR;
break;
case 2:
start1 = delims[0].charAt(0);
start2 = delims[0].charAt(1);
break;
default:
throw new MustacheException(errmsg);
}
switch (delims[1].length()) {
case 1:
end1 = delims[1].charAt(0);
end2 = NO_CHAR;
break;
case 2:
end1 = delims[1].charAt(0);
end2 = delims[1].charAt(1);
break;
default:
throw new MustacheException(errmsg);
}
}
}
protected static class Accumulator {
public Accumulator (Compiler compiler) {
_compiler = compiler;
}
public boolean justOpenedOrClosedBlock () {
// return true if we just closed a block segment; we'll handle just opened elsewhere
return (!_segs.isEmpty() && _segs.get(_segs.size()-1) instanceof BlockSegment);
}
public void addTextSegment (StringBuilder text) {
if (text.length() > 0) {
_segs.add(new StringSegment(text.toString()));
text.setLength(0);
}
}
public Accumulator addTagSegment (final StringBuilder accum, final int tagLine) {
final Accumulator outer = this;
String tag = accum.toString().trim();
final String tag1 = tag.substring(1).trim();
accum.setLength(0);
switch (tag.charAt(0)) {
case '#':
requireNoNewlines(tag, tagLine);
return new Accumulator(_compiler) {
@Override public boolean justOpenedOrClosedBlock () {
// if we just opened this section, we'll have no segments
return (_segs.isEmpty()) || super.justOpenedOrClosedBlock();
}
@Override public Template.Segment[] finish () {
throw new MustacheParseException(
"Section missing close tag '" + tag1 + "'", tagLine);
}
@Override protected Accumulator addCloseSectionSegment (String itag, int line) {
requireSameName(tag1, itag, line);
outer._segs.add(new SectionSegment(itag, super.finish(), tagLine));
return outer;
}
};
case '>':
_segs.add(new IncludedTemplateSegment(tag1, _compiler));
return this;
case '^':
requireNoNewlines(tag, tagLine);
return new Accumulator(_compiler) {
@Override public boolean justOpenedOrClosedBlock () {
// if we just opened this section, we'll have no segments
return (_segs.isEmpty()) || super.justOpenedOrClosedBlock();
}
@Override public Template.Segment[] finish () {
throw new MustacheParseException(
"Inverted section missing close tag '" + tag1 + "'", tagLine);
}
@Override protected Accumulator addCloseSectionSegment (String itag, int line) {
requireSameName(tag1, itag, line);
outer._segs.add(new InvertedSectionSegment(itag, super.finish(), tagLine));
return outer;
}
};
case '/':
requireNoNewlines(tag, tagLine);
return addCloseSectionSegment(tag1, tagLine);
case '!':
// comment!, ignore
return this;
case '&':
requireNoNewlines(tag, tagLine);
_segs.add(new VariableSegment(tag1, false, tagLine));
return this;
default:
requireNoNewlines(tag, tagLine);
_segs.add(new VariableSegment(tag, _compiler.escapeHTML, tagLine));
return this;
}
}
public Template.Segment[] finish () {
return _segs.toArray(new Template.Segment[_segs.size()]);
}
protected Accumulator addCloseSectionSegment (String tag, int line) {
throw new MustacheParseException(
"Section close tag with no open tag '" + tag + "'", line);
}
protected static void requireNoNewlines (String tag, int line) {
if (tag.indexOf("\n") != -1 || tag.indexOf("\r") != -1) {
throw new MustacheParseException(
"Invalid tag name: contains newline '" + tag + "'", line);
}
}
protected static void requireSameName (String name1, String name2, int line)
{
if (!name1.equals(name2)) {
throw new MustacheParseException("Section close tag with mismatched open tag '" +
name2 + "' != '" + name1 + "'", line);
}
}
protected Compiler _compiler;
protected final List<Template.Segment> _segs = new ArrayList<Template.Segment>();
}
/** A simple segment that reproduces a string. */
protected static class StringSegment extends Template.Segment {
public StringSegment (String text) {
_text = text;
}
@Override public void execute (Template tmpl, Template.Context ctx, Writer out) {
write(out, _text);
}
protected final String _text;
}
protected static class IncludedTemplateSegment extends Template.Segment {
public IncludedTemplateSegment (final String templateName, final Compiler compiler) {
+ this.compiler = compiler;
+ this.templateName = templateName;
+ }
+ @Override public void execute (Template tmpl, Template.Context ctx, Writer out) {
Reader r;
try {
r = compiler.loader.getTemplate(templateName);
} catch (Exception e) {
if (e instanceof RuntimeException) {
throw (RuntimeException)e;
} else {
throw new MustacheException("Unable to load template: " + templateName, e);
}
}
- _template = compiler.compile(r);
- }
- @Override public void execute (Template tmpl, Template.Context ctx, Writer out) {
+ Template _template = compiler.compile(r);
// we must take care to preserve our context rather than creating a new one, which
// would happen if we just called execute() with ctx.data
_template.executeSegs(ctx, out);
}
- protected final Template _template;
+ protected String templateName;
+ protected Compiler compiler;
}
/** A helper class for named segments. */
protected static abstract class NamedSegment extends Template.Segment {
protected NamedSegment (String name, int line) {
_name = name.intern();
_line = line;
}
protected final String _name;
protected final int _line;
}
/** A segment that substitutes the contents of a variable. */
protected static class VariableSegment extends NamedSegment {
public VariableSegment (String name, boolean escapeHTML, int line) {
super(name, line);
_escapeHTML = escapeHTML;
}
@Override public void execute (Template tmpl, Template.Context ctx, Writer out) {
Object value = tmpl.getValueOrDefault(ctx, _name, _line);
if (value == null) {
throw new MustacheException(
"No key, method or field with name '" + _name + "' on line " + _line);
}
String text = String.valueOf(value);
write(out, _escapeHTML ? escapeHTML(text) : text);
}
protected boolean _escapeHTML;
}
/** A helper class for block segments. */
protected static abstract class BlockSegment extends NamedSegment {
protected BlockSegment (String name, Template.Segment[] segs, int line) {
super(name, line);
_segs = segs;
}
protected void executeSegs (Template tmpl, Template.Context ctx, Writer out) {
for (Template.Segment seg : _segs) {
seg.execute(tmpl, ctx, out);
}
}
protected final Template.Segment[] _segs;
}
/** A segment that represents a section. */
protected static class SectionSegment extends BlockSegment {
public SectionSegment (String name, Template.Segment[] segs, int line) {
super(name, segs, line);
}
@Override public void execute (Template tmpl, Template.Context ctx, Writer out) {
Object value = tmpl.getSectionValue(ctx, _name, _line); // won't return null
Iterator<?> iter = tmpl._compiler.collector.toIterator(value);
if (iter != null) {
int index = 0;
while (iter.hasNext()) {
Object elem = iter.next();
boolean onFirst = (index == 0), onLast = !iter.hasNext();
executeSegs(tmpl, ctx.nest(elem, ++index, onFirst, onLast), out);
}
} else if (value instanceof Boolean) {
if ((Boolean)value) {
executeSegs(tmpl, ctx, out);
}
} else {
executeSegs(tmpl, ctx.nest(value, 0, false, false), out);
}
}
}
/** A segment that represents an inverted section. */
protected static class InvertedSectionSegment extends BlockSegment {
public InvertedSectionSegment (String name, Template.Segment[] segs, int line) {
super(name, segs, line);
}
@Override public void execute (Template tmpl, Template.Context ctx, Writer out) {
Object value = tmpl.getSectionValue(ctx, _name, _line); // won't return null
Iterator<?> iter = tmpl._compiler.collector.toIterator(value);
if (iter != null) {
if (!iter.hasNext()) {
executeSegs(tmpl, ctx, out);
}
} else if (value instanceof Boolean) {
if (!(Boolean)value) {
executeSegs(tmpl, ctx, out);
}
} // TODO: fail?
}
}
/** Map of strings that must be replaced inside html attributes and their replacements. (They
* need to be applied in order so amps are not double escaped.) */
protected static final String[][] ATTR_ESCAPES = {
{ "&", "&" },
{ "'", "'" },
{ "\"", """ },
{ "<", "<" },
{ ">", ">" },
};
/** Used when we have only a single character delimiter. */
protected static final char NO_CHAR = Character.MIN_VALUE;
protected static final TemplateLoader FAILING_LOADER = new TemplateLoader() {
public Reader getTemplate (String name) {
throw new UnsupportedOperationException("Template loading not configured");
}
};
}
| false | false | null | null |
diff --git a/src/com/android/camera/PhotoModule.java b/src/com/android/camera/PhotoModule.java
index 8f8bf7bd..79d5e59d 100644
--- a/src/com/android/camera/PhotoModule.java
+++ b/src/com/android/camera/PhotoModule.java
@@ -1,2739 +1,2739 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.camera;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.SurfaceTexture;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Face;
import android.hardware.Camera.FaceDetectionListener;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.Size;
import android.location.Location;
import android.media.CameraProfile;
import android.net.Uri;
import android.os.Bundle;
import android.os.ConditionVariable;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.MessageQueue;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.OrientationEventListener;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.camera.CameraManager.CameraProxy;
import com.android.camera.ui.AbstractSettingPopup;
import com.android.camera.ui.FaceView;
import com.android.camera.ui.PieRenderer;
import com.android.camera.ui.PopupManager;
import com.android.camera.ui.PreviewSurfaceView;
import com.android.camera.ui.RenderOverlay;
import com.android.camera.ui.Rotatable;
import com.android.camera.ui.RotateLayout;
import com.android.camera.ui.RotateTextToast;
import com.android.camera.ui.TwoStateImageView;
import com.android.camera.ui.ZoomRenderer;
import com.android.gallery3d.app.CropImage;
import com.android.gallery3d.common.ApiHelper;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Formatter;
import java.util.List;
public class PhotoModule
implements CameraModule,
FocusOverlayManager.Listener,
CameraPreference.OnPreferenceChangedListener,
LocationManager.Listener,
PreviewFrameLayout.OnSizeChangedListener,
ShutterButton.OnShutterButtonListener,
SurfaceHolder.Callback,
PieRenderer.PieListener {
private static final String TAG = "CAM_PhotoModule";
private boolean mRestartPreview = false;
private boolean mAspectRatioChanged = false;
// We number the request code from 1000 to avoid collision with Gallery.
private static final int REQUEST_CROP = 1000;
private static final int SETUP_PREVIEW = 1;
private static final int FIRST_TIME_INIT = 2;
private static final int CLEAR_SCREEN_DELAY = 3;
private static final int SET_CAMERA_PARAMETERS_WHEN_IDLE = 4;
private static final int CHECK_DISPLAY_ROTATION = 5;
private static final int SHOW_TAP_TO_FOCUS_TOAST = 6;
private static final int SWITCH_CAMERA = 7;
private static final int SWITCH_CAMERA_START_ANIMATION = 8;
private static final int CAMERA_OPEN_DONE = 9;
private static final int START_PREVIEW_DONE = 10;
private static final int OPEN_CAMERA_FAIL = 11;
private static final int CAMERA_DISABLED = 12;
// The subset of parameters we need to update in setCameraParameters().
private static final int UPDATE_PARAM_INITIALIZE = 1;
private static final int UPDATE_PARAM_ZOOM = 2;
private static final int UPDATE_PARAM_PREFERENCE = 4;
private static final int UPDATE_PARAM_ALL = -1;
// This is the timeout to keep the camera in onPause for the first time
// after screen on if the activity is started from secure lock screen.
private static final int KEEP_CAMERA_TIMEOUT = 1000; // ms
// copied from Camera hierarchy
private CameraActivity mActivity;
private View mRootView;
private CameraProxy mCameraDevice;
private int mCameraId;
private Parameters mParameters;
private boolean mPaused;
private AbstractSettingPopup mPopup;
// these are only used by Camera
// The activity is going to switch to the specified camera id. This is
// needed because texture copy is done in GL thread. -1 means camera is not
// switching.
protected int mPendingSwitchCameraId = -1;
private boolean mOpenCameraFail;
private boolean mCameraDisabled;
// When setCameraParametersWhenIdle() is called, we accumulate the subsets
// needed to be updated in mUpdateSet.
private int mUpdateSet;
private static final int SCREEN_DELAY = 2 * 60 * 1000;
private int mZoomValue; // The current zoom value.
private int mZoomMax;
private List<Integer> mZoomRatios;
private Parameters mInitialParams;
private boolean mFocusAreaSupported;
private boolean mMeteringAreaSupported;
private boolean mAeLockSupported;
private boolean mAwbLockSupported;
private boolean mContinousFocusSupported;
// The degrees of the device rotated clockwise from its natural orientation.
private int mOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
// The orientation compensation for icons and dialogs. Ex: if the value
// is 90, the UI components should be rotated 90 degrees counter-clockwise.
private int mOrientationCompensation = 0;
private ComboPreferences mPreferences;
private static final String sTempCropFilename = "crop-temp";
private ContentProviderClient mMediaProviderClient;
private ShutterButton mShutterButton;
private boolean mFaceDetectionStarted = false;
private PreviewFrameLayout mPreviewFrameLayout;
private Object mSurfaceTexture;
// for API level 10
private PreviewSurfaceView mPreviewSurfaceView;
private volatile SurfaceHolder mCameraSurfaceHolder;
private FaceView mFaceView;
private RenderOverlay mRenderOverlay;
private Rotatable mReviewCancelButton;
private Rotatable mReviewDoneButton;
private View mReviewRetakeButton;
// mCropValue and mSaveUri are used only if isImageCaptureIntent() is true.
private String mCropValue;
private Uri mSaveUri;
private View mMenu;
private View mBlocker;
// Small indicators which show the camera settings in the viewfinder.
private ImageView mExposureIndicator;
private ImageView mFlashIndicator;
private ImageView mSceneIndicator;
private ImageView mHdrIndicator;
// A view group that contains all the small indicators.
private View mOnScreenIndicators;
// We use a thread in ImageSaver to do the work of saving images. This
// reduces the shot-to-shot time.
private ImageSaver mImageSaver;
// Similarly, we use a thread to generate the name of the picture and insert
// it into MediaStore while picture taking is still in progress.
private ImageNamer mImageNamer;
private Runnable mDoSnapRunnable = new Runnable() {
@Override
public void run() {
onShutterButtonClick();
}
};
private final StringBuilder mBuilder = new StringBuilder();
private final Formatter mFormatter = new Formatter(mBuilder);
private final Object[] mFormatterArgs = new Object[1];
/**
* An unpublished intent flag requesting to return as soon as capturing
* is completed.
*
* TODO: consider publishing by moving into MediaStore.
*/
private static final String EXTRA_QUICK_CAPTURE =
"android.intent.extra.quickCapture";
// The display rotation in degrees. This is only valid when mCameraState is
// not PREVIEW_STOPPED.
private int mDisplayRotation;
// The value for android.hardware.Camera.setDisplayOrientation.
private int mCameraDisplayOrientation;
// The value for UI components like indicators.
private int mDisplayOrientation;
// The value for android.hardware.Camera.Parameters.setRotation.
private int mJpegRotation;
private boolean mFirstTimeInitialized;
private boolean mIsImageCaptureIntent;
private static final int PREVIEW_STOPPED = 0;
private static final int IDLE = 1; // preview is active
// Focus is in progress. The exact focus state is in Focus.java.
private static final int FOCUSING = 2;
private static final int SNAPSHOT_IN_PROGRESS = 3;
// Switching between cameras.
private static final int SWITCHING_CAMERA = 4;
private int mCameraState = PREVIEW_STOPPED;
private boolean mSnapshotOnIdle = false;
private ContentResolver mContentResolver;
private LocationManager mLocationManager;
private final ShutterCallback mShutterCallback = new ShutterCallback();
private final PostViewPictureCallback mPostViewPictureCallback =
new PostViewPictureCallback();
private final RawPictureCallback mRawPictureCallback =
new RawPictureCallback();
private final AutoFocusCallback mAutoFocusCallback =
new AutoFocusCallback();
private final Object mAutoFocusMoveCallback =
ApiHelper.HAS_AUTO_FOCUS_MOVE_CALLBACK
? new AutoFocusMoveCallback()
: null;
private final CameraErrorCallback mErrorCallback = new CameraErrorCallback();
private long mFocusStartTime;
private long mShutterCallbackTime;
private long mPostViewPictureCallbackTime;
private long mRawPictureCallbackTime;
private long mJpegPictureCallbackTime;
private long mOnResumeTime;
private byte[] mJpegImageData;
// These latency time are for the CameraLatency test.
public long mAutoFocusTime;
public long mShutterLag;
public long mShutterToPictureDisplayedTime;
public long mPictureDisplayedToJpegCallbackTime;
public long mJpegCallbackFinishTime;
public long mCaptureStartTime;
// This handles everything about focus.
private FocusOverlayManager mFocusManager;
private PieRenderer mPieRenderer;
private PhotoController mPhotoControl;
private ZoomRenderer mZoomRenderer;
private String mSceneMode;
private Toast mNotSelectableToast;
private final Handler mHandler = new MainHandler();
private PreferenceGroup mPreferenceGroup;
// Burst mode
private int mBurstShotsDone = 0;
private boolean mBurstShotInProgress = false;
private boolean mQuickCapture;
CameraStartUpThread mCameraStartUpThread;
ConditionVariable mStartPreviewPrerequisiteReady = new ConditionVariable();
private PreviewGestures mGestures;
// The purpose is not to block the main thread in onCreate and onResume.
private class CameraStartUpThread extends Thread {
private volatile boolean mCancelled;
public void cancel() {
mCancelled = true;
}
@Override
public void run() {
try {
// We need to check whether the activity is paused before long
// operations to ensure that onPause() can be done ASAP.
if (mCancelled) return;
mCameraDevice = Util.openCamera(mActivity, mCameraId);
mParameters = mCameraDevice.getParameters();
// Wait until all the initialization needed by startPreview are
// done.
mStartPreviewPrerequisiteReady.block();
initializeCapabilities();
if (mFocusManager == null) initializeFocusManager();
if (mCancelled) return;
setCameraParameters(UPDATE_PARAM_ALL);
mHandler.sendEmptyMessage(CAMERA_OPEN_DONE);
if (mCancelled) return;
startPreview();
mHandler.sendEmptyMessage(START_PREVIEW_DONE);
mOnResumeTime = SystemClock.uptimeMillis();
mHandler.sendEmptyMessage(CHECK_DISPLAY_ROTATION);
} catch (CameraHardwareException e) {
mHandler.sendEmptyMessage(OPEN_CAMERA_FAIL);
} catch (CameraDisabledException e) {
mHandler.sendEmptyMessage(CAMERA_DISABLED);
}
}
}
/**
* This Handler is used to post message back onto the main thread of the
* application
*/
private class MainHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SETUP_PREVIEW: {
setupPreview();
break;
}
case CLEAR_SCREEN_DELAY: {
mActivity.getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
break;
}
case FIRST_TIME_INIT: {
initializeFirstTime();
break;
}
case SET_CAMERA_PARAMETERS_WHEN_IDLE: {
setCameraParametersWhenIdle(0);
break;
}
case CHECK_DISPLAY_ROTATION: {
// Set the display orientation if display rotation has changed.
// Sometimes this happens when the device is held upside
// down and camera app is opened. Rotation animation will
// take some time and the rotation value we have got may be
// wrong. Framework does not have a callback for this now.
if (Util.getDisplayRotation(mActivity) != mDisplayRotation) {
setDisplayOrientation();
}
if (SystemClock.uptimeMillis() - mOnResumeTime < 5000) {
mHandler.sendEmptyMessageDelayed(CHECK_DISPLAY_ROTATION, 100);
}
break;
}
case SHOW_TAP_TO_FOCUS_TOAST: {
showTapToFocusToast();
break;
}
case SWITCH_CAMERA: {
switchCamera();
break;
}
case SWITCH_CAMERA_START_ANIMATION: {
((CameraScreenNail) mActivity.mCameraScreenNail).animateSwitchCamera();
break;
}
case CAMERA_OPEN_DONE: {
initializeAfterCameraOpen();
break;
}
case START_PREVIEW_DONE: {
mCameraStartUpThread = null;
setCameraState(IDLE);
if (!ApiHelper.HAS_SURFACE_TEXTURE) {
// This may happen if surfaceCreated has arrived.
mCameraDevice.setPreviewDisplayAsync(mCameraSurfaceHolder);
}
startFaceDetection();
locationFirstRun();
break;
}
case OPEN_CAMERA_FAIL: {
mCameraStartUpThread = null;
mOpenCameraFail = true;
Util.showErrorAndFinish(mActivity,
R.string.cannot_connect_camera);
break;
}
case CAMERA_DISABLED: {
mCameraStartUpThread = null;
mCameraDisabled = true;
Util.showErrorAndFinish(mActivity,
R.string.camera_disabled);
break;
}
}
}
}
@Override
public void init(CameraActivity activity, View parent, boolean reuseNail) {
mActivity = activity;
mRootView = parent;
mPreferences = new ComboPreferences(mActivity);
CameraSettings.upgradeGlobalPreferences(mPreferences.getGlobal());
mCameraId = getPreferredCameraId(mPreferences);
mContentResolver = mActivity.getContentResolver();
// To reduce startup time, open the camera and start the preview in
// another thread.
mCameraStartUpThread = new CameraStartUpThread();
mCameraStartUpThread.start();
mActivity.getLayoutInflater().inflate(R.layout.photo_module, (ViewGroup) mRootView);
// Surface texture is from camera screen nail and startPreview needs it.
// This must be done before startPreview.
mIsImageCaptureIntent = isImageCaptureIntent();
if (reuseNail) {
mActivity.reuseCameraScreenNail(!mIsImageCaptureIntent);
} else {
mActivity.createCameraScreenNail(!mIsImageCaptureIntent);
}
mPreferences.setLocalId(mActivity, mCameraId);
CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
// we need to reset exposure for the preview
resetExposureCompensation();
// Starting the preview needs preferences, camera screen nail, and
// focus area indicator.
mStartPreviewPrerequisiteReady.open();
initializeControlByIntent();
mQuickCapture = mActivity.getIntent().getBooleanExtra(EXTRA_QUICK_CAPTURE, false);
initializeMiscControls();
mLocationManager = new LocationManager(mActivity, this);
initOnScreenIndicator();
}
// Prompt the user to pick to record location for the very first run of
// camera only
private void locationFirstRun() {
if (RecordLocationPreference.isSet(mPreferences)) {
return;
}
// Check if the back camera exists
int backCameraId = CameraHolder.instance().getBackCameraId();
if (backCameraId == -1) {
// If there is no back camera, do not show the prompt.
return;
}
new AlertDialog.Builder(mActivity)
.setTitle(R.string.remember_location_title)
.setMessage(R.string.remember_location_prompt)
.setPositiveButton(R.string.remember_location_yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int arg1) {
setLocationPreference(CameraSettings.VALUE_ON);
}
})
.setNegativeButton(R.string.remember_location_no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int arg1) {
dialog.cancel();
}
})
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
setLocationPreference(CameraSettings.VALUE_OFF);
}
})
.show();
}
private void setLocationPreference(String value) {
mPreferences.edit()
.putString(RecordLocationPreference.KEY, value)
.apply();
// TODO: Fix this to use the actual onSharedPreferencesChanged listener
// instead of invoking manually
onSharedPreferenceChanged();
}
private void initializeRenderOverlay() {
if (mPieRenderer != null) {
mRenderOverlay.addRenderer(mPieRenderer);
mFocusManager.setFocusRenderer(mPieRenderer);
}
if (mZoomRenderer != null) {
mRenderOverlay.addRenderer(mZoomRenderer);
}
if (mGestures != null) {
mGestures.clearTouchReceivers();
mGestures.setRenderOverlay(mRenderOverlay);
mGestures.addTouchReceiver(mMenu);
mGestures.addTouchReceiver(mBlocker);
if (isImageCaptureIntent()) {
if (mReviewCancelButton != null) {
mGestures.addTouchReceiver((View) mReviewCancelButton);
}
if (mReviewDoneButton != null) {
mGestures.addTouchReceiver((View) mReviewDoneButton);
}
}
}
mRenderOverlay.requestLayout();
}
private void initializeAfterCameraOpen() {
if (mPieRenderer == null) {
mPieRenderer = new PieRenderer(mActivity);
mPhotoControl = new PhotoController(mActivity, this, mPieRenderer);
mPhotoControl.setListener(this);
mPieRenderer.setPieListener(this);
}
if (mZoomRenderer == null) {
mZoomRenderer = new ZoomRenderer(mActivity);
}
if (mGestures == null) {
// this will handle gesture disambiguation and dispatching
mGestures = new PreviewGestures(mActivity, this, mZoomRenderer, mPieRenderer);
}
initializeRenderOverlay();
initializePhotoControl();
// These depend on camera parameters.
setPreviewFrameLayoutAspectRatio();
mFocusManager.setPreviewSize(mPreviewFrameLayout.getWidth(),
mPreviewFrameLayout.getHeight());
loadCameraPreferences();
initializeZoom();
updateOnScreenIndicators();
showTapToFocusToastIfNeeded();
}
private void initializePhotoControl() {
loadCameraPreferences();
if (mPhotoControl != null) {
mPhotoControl.initialize(mPreferenceGroup);
}
updateSceneModeUI();
}
private void resetExposureCompensation() {
String value = mPreferences.getString(CameraSettings.KEY_EXPOSURE,
CameraSettings.EXPOSURE_DEFAULT_VALUE);
if (!CameraSettings.EXPOSURE_DEFAULT_VALUE.equals(value)) {
Editor editor = mPreferences.edit();
editor.putString(CameraSettings.KEY_EXPOSURE, "0");
editor.apply();
}
}
private void keepMediaProviderInstance() {
// We want to keep a reference to MediaProvider in camera's lifecycle.
// TODO: Utilize mMediaProviderClient instance to replace
// ContentResolver calls.
if (mMediaProviderClient == null) {
mMediaProviderClient = mContentResolver
.acquireContentProviderClient(MediaStore.AUTHORITY);
}
}
// Snapshots can only be taken after this is called. It should be called
// once only. We could have done these things in onCreate() but we want to
// make preview screen appear as soon as possible.
private void initializeFirstTime() {
if (mFirstTimeInitialized) return;
// Initialize location service.
boolean recordLocation = RecordLocationPreference.get(
mPreferences, mContentResolver);
mLocationManager.recordLocation(recordLocation);
keepMediaProviderInstance();
// Initialize shutter button.
mShutterButton = mActivity.getShutterButton();
mShutterButton.setImageResource(R.drawable.btn_new_shutter);
mShutterButton.setOnShutterButtonListener(this);
mShutterButton.setVisibility(View.VISIBLE);
mImageSaver = new ImageSaver();
mImageNamer = new ImageNamer();
mFirstTimeInitialized = true;
addIdleHandler();
mActivity.updateStorageSpaceAndHint();
}
private void showTapToFocusToastIfNeeded() {
// Show the tap to focus toast if this is the first start.
if (mFocusAreaSupported &&
mPreferences.getBoolean(CameraSettings.KEY_CAMERA_FIRST_USE_HINT_SHOWN, true)) {
// Delay the toast for one second to wait for orientation.
mHandler.sendEmptyMessageDelayed(SHOW_TAP_TO_FOCUS_TOAST, 1000);
}
}
private void addIdleHandler() {
MessageQueue queue = Looper.myQueue();
queue.addIdleHandler(new MessageQueue.IdleHandler() {
@Override
public boolean queueIdle() {
Storage.ensureOSXCompatible();
return false;
}
});
}
// If the activity is paused and resumed, this method will be called in
// onResume.
private void initializeSecondTime() {
// Start location update if needed.
boolean recordLocation = RecordLocationPreference.get(
mPreferences, mContentResolver);
mLocationManager.recordLocation(recordLocation);
mImageSaver = new ImageSaver();
mImageNamer = new ImageNamer();
initializeZoom();
keepMediaProviderInstance();
hidePostCaptureAlert();
if (mPhotoControl != null) {
mPhotoControl.reloadPreferences();
}
}
private void processZoomValueChanged(int index) {
if (index >= 0 && index <= mZoomMax) {
mZoomRenderer.setZoom(index);
// Not useful to change zoom value when the activity is paused.
if (mPaused) return;
mZoomValue = index;
if (mParameters == null || mCameraDevice == null) return;
// Set zoom parameters asynchronously
mParameters.setZoom(mZoomValue);
mCameraDevice.setParametersAsync(mParameters);
if (mZoomRenderer != null) {
Parameters p = mCameraDevice.getParameters();
mZoomRenderer.setZoomValue(mZoomRatios.get(p.getZoom()));
}
}
}
private class ZoomChangeListener implements ZoomRenderer.OnZoomChangedListener {
@Override
public void onZoomValueChanged(int index) {
processZoomValueChanged(index);
}
@Override
public void onZoomStart() {
if (mPieRenderer != null) {
mPieRenderer.setBlockFocus(true);
}
}
@Override
public void onZoomEnd() {
if (mPieRenderer != null) {
mPieRenderer.setBlockFocus(false);
}
}
}
private void initializeZoom() {
if ((mParameters == null) || !mParameters.isZoomSupported()
|| (mZoomRenderer == null)) return;
mZoomMax = mParameters.getMaxZoom();
mZoomRatios = mParameters.getZoomRatios();
// Currently we use immediate zoom for fast zooming to get better UX and
// there is no plan to take advantage of the smooth zoom.
if (mZoomRenderer != null) {
mZoomRenderer.setZoomMax(mZoomMax);
mZoomRenderer.setZoom(mParameters.getZoom());
mZoomRenderer.setZoomValue(mZoomRatios.get(mParameters.getZoom()));
mZoomRenderer.setOnZoomChangeListener(new ZoomChangeListener());
}
}
@TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
public void startFaceDetection() {
if (!ApiHelper.HAS_FACE_DETECTION) return;
// Workaround for a buggy camera library
if (Util.noFaceDetectOnFrontCamera()
&& (CameraHolder.instance().getCameraInfo()[mCameraId].facing == CameraInfo.CAMERA_FACING_FRONT)) {
return;
}
if (mFaceDetectionStarted || mCameraState != IDLE) return;
if (mParameters.getMaxNumDetectedFaces() > 0) {
mFaceDetectionStarted = true;
mFaceView.clear();
mFaceView.setVisibility(View.VISIBLE);
mFaceView.setDisplayOrientation(mDisplayOrientation);
CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
mFaceView.setMirror(info.facing == CameraInfo.CAMERA_FACING_FRONT);
mFaceView.resume();
mFocusManager.setFaceView(mFaceView);
mCameraDevice.setFaceDetectionListener(new FaceDetectionListener() {
@Override
public void onFaceDetection(Face[] faces, android.hardware.Camera camera) {
mFaceView.setFaces(faces);
}
});
mCameraDevice.startFaceDetection();
}
}
@TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
public void stopFaceDetection() {
if (!ApiHelper.HAS_FACE_DETECTION) return;
if (!mFaceDetectionStarted) return;
if (mParameters.getMaxNumDetectedFaces() > 0) {
mFaceDetectionStarted = false;
mCameraDevice.setFaceDetectionListener(null);
mCameraDevice.stopFaceDetection();
if (mFaceView != null) mFaceView.clear();
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent m) {
if (mCameraState == SWITCHING_CAMERA) return true;
if (mPopup != null) {
return mActivity.superDispatchTouchEvent(m);
} else if (mGestures != null && mRenderOverlay != null) {
return mGestures.dispatchTouch(m);
}
return false;
}
private void initOnScreenIndicator() {
mOnScreenIndicators = mRootView.findViewById(R.id.on_screen_indicators);
mExposureIndicator = (ImageView) mOnScreenIndicators.findViewById(R.id.menu_exposure_indicator);
mFlashIndicator = (ImageView) mOnScreenIndicators.findViewById(R.id.menu_flash_indicator);
mSceneIndicator = (ImageView) mOnScreenIndicators.findViewById(R.id.menu_scenemode_indicator);
mHdrIndicator = (ImageView) mOnScreenIndicators.findViewById(R.id.menu_hdr_indicator);
}
@Override
public void showGpsOnScreenIndicator(boolean hasSignal) { }
@Override
public void hideGpsOnScreenIndicator() { }
private void updateExposureOnScreenIndicator(int value) {
if (mExposureIndicator == null) {
return;
}
int id = 0;
float step = mParameters.getExposureCompensationStep();
value = (int) Math.round(value * step);
switch(value) {
case -3:
id = R.drawable.ic_indicator_ev_n3;
break;
case -2:
id = R.drawable.ic_indicator_ev_n2;
break;
case -1:
id = R.drawable.ic_indicator_ev_n1;
break;
case 0:
id = R.drawable.ic_indicator_ev_0;
break;
case 1:
id = R.drawable.ic_indicator_ev_p1;
break;
case 2:
id = R.drawable.ic_indicator_ev_p2;
break;
case 3:
id = R.drawable.ic_indicator_ev_p3;
break;
}
mExposureIndicator.setImageResource(id);
}
private void updateFlashOnScreenIndicator(String value) {
if (mFlashIndicator == null) {
return;
}
if (value == null || Parameters.FLASH_MODE_OFF.equals(value)) {
mFlashIndicator.setImageResource(R.drawable.ic_indicator_flash_off);
} else {
if (Parameters.FLASH_MODE_AUTO.equals(value)) {
mFlashIndicator.setImageResource(R.drawable.ic_indicator_flash_auto);
} else if (Parameters.FLASH_MODE_ON.equals(value)) {
mFlashIndicator.setImageResource(R.drawable.ic_indicator_flash_on);
} else {
mFlashIndicator.setImageResource(R.drawable.ic_indicator_flash_off);
}
}
}
private void updateSceneOnScreenIndicator(String value) {
if (mSceneIndicator == null) {
return;
}
if ((value == null) || Parameters.SCENE_MODE_AUTO.equals(value)
|| Parameters.SCENE_MODE_HDR.equals(value)) {
mSceneIndicator.setImageResource(R.drawable.ic_indicator_sce_off);
} else {
mSceneIndicator.setImageResource(R.drawable.ic_indicator_sce_on);
}
}
private void updateHdrOnScreenIndicator(String value) {
if (mHdrIndicator == null) {
return;
}
if ((value != null) && Parameters.SCENE_MODE_HDR.equals(value)) {
mHdrIndicator.setImageResource(R.drawable.ic_indicator_hdr_on);
} else {
mHdrIndicator.setImageResource(R.drawable.ic_indicator_hdr_off);
}
}
private void updateOnScreenIndicators() {
updateSceneOnScreenIndicator(mParameters.getSceneMode());
updateExposureOnScreenIndicator(CameraSettings.readExposure(mPreferences));
updateFlashOnScreenIndicator(mParameters.getFlashMode());
updateHdrOnScreenIndicator(mParameters.getSceneMode());
}
private final class ShutterCallback
implements android.hardware.Camera.ShutterCallback {
@Override
public void onShutter() {
mShutterCallbackTime = System.currentTimeMillis();
mShutterLag = mShutterCallbackTime - mCaptureStartTime;
Log.v(TAG, "mShutterLag = " + mShutterLag + "ms");
}
}
private final class PostViewPictureCallback implements PictureCallback {
@Override
public void onPictureTaken(
byte [] data, android.hardware.Camera camera) {
mPostViewPictureCallbackTime = System.currentTimeMillis();
Log.v(TAG, "mShutterToPostViewCallbackTime = "
+ (mPostViewPictureCallbackTime - mShutterCallbackTime)
+ "ms");
}
}
private final class RawPictureCallback implements PictureCallback {
@Override
public void onPictureTaken(
byte [] rawData, android.hardware.Camera camera) {
mRawPictureCallbackTime = System.currentTimeMillis();
Log.v(TAG, "mShutterToRawCallbackTime = "
+ (mRawPictureCallbackTime - mShutterCallbackTime) + "ms");
}
}
private final class JpegPictureCallback implements PictureCallback {
Location mLocation;
public JpegPictureCallback(Location loc) {
mLocation = loc;
}
@Override
public void onPictureTaken(
final byte [] jpegData, final android.hardware.Camera camera) {
if (mPaused) {
return;
}
if (mSceneMode == Util.SCENE_MODE_HDR) {
mActivity.showSwitcher();
mActivity.setSwipingEnabled(true);
}
mJpegPictureCallbackTime = System.currentTimeMillis();
// If postview callback has arrived, the captured image is displayed
// in postview callback. If not, the captured image is displayed in
// raw picture callback.
if (mPostViewPictureCallbackTime != 0) {
mShutterToPictureDisplayedTime =
mPostViewPictureCallbackTime - mShutterCallbackTime;
mPictureDisplayedToJpegCallbackTime =
mJpegPictureCallbackTime - mPostViewPictureCallbackTime;
} else {
mShutterToPictureDisplayedTime =
mRawPictureCallbackTime - mShutterCallbackTime;
mPictureDisplayedToJpegCallbackTime =
mJpegPictureCallbackTime - mRawPictureCallbackTime;
}
Log.v(TAG, "mPictureDisplayedToJpegCallbackTime = "
+ mPictureDisplayedToJpegCallbackTime + "ms");
// Only animate when in full screen capture mode
// i.e. If monkey/a user swipes to the gallery during picture taking,
// don't show animation
if (ApiHelper.HAS_SURFACE_TEXTURE && !mIsImageCaptureIntent
&& mActivity.mShowCameraAppView) {
// Finish capture animation
((CameraScreenNail) mActivity.mCameraScreenNail).animateSlide();
}
mFocusManager.updateFocusUI(); // Ensure focus indicator is hidden.
if (!mIsImageCaptureIntent && !Util.enableZSL()) {
if (ApiHelper.CAN_START_PREVIEW_IN_JPEG_CALLBACK) {
setupPreview();
} else {
// Camera HAL of some devices have a bug. Starting preview
// immediately after taking a picture will fail. Wait some
// time before starting the preview.
mHandler.sendEmptyMessageDelayed(SETUP_PREVIEW, 300);
}
} else {
mFocusManager.resetTouchFocus();
setCameraState(IDLE);
}
if (!mIsImageCaptureIntent) {
// Calculate the width and the height of the jpeg.
Size s = mParameters.getPictureSize();
int orientation = Exif.getOrientation(jpegData);
int width, height;
if ((mJpegRotation + orientation) % 180 == 0) {
width = s.width;
height = s.height;
} else {
width = s.height;
height = s.width;
}
Uri uri = mImageNamer.getUri();
mActivity.addSecureAlbumItemIfNeeded(false, uri);
String title = mImageNamer.getTitle();
mImageSaver.addImage(jpegData, uri, title, mLocation,
width, height, orientation);
} else {
mJpegImageData = jpegData;
if (!mQuickCapture) {
showPostCaptureAlert();
} else {
doAttach();
}
}
// Check this in advance of each shot so we don't add to shutter
// latency. It's true that someone else could write to the SD card in
// the mean time and fill it, but that could have happened between the
// shutter press and saving the JPEG too.
mActivity.updateStorageSpaceAndHint();
long now = System.currentTimeMillis();
mJpegCallbackFinishTime = now - mJpegPictureCallbackTime;
Log.v(TAG, "mJpegCallbackFinishTime = "
+ mJpegCallbackFinishTime + "ms");
mJpegPictureCallbackTime = 0;
if (mSnapshotOnIdle && mBurstShotsDone > 0) {
mHandler.post(mDoSnapRunnable);
}
}
}
private final class AutoFocusCallback
implements android.hardware.Camera.AutoFocusCallback {
@Override
public void onAutoFocus(
boolean focused, android.hardware.Camera camera) {
if (mPaused) return;
mAutoFocusTime = System.currentTimeMillis() - mFocusStartTime;
Log.v(TAG, "mAutoFocusTime = " + mAutoFocusTime + "ms");
setCameraState(IDLE);
mFocusManager.onAutoFocus(focused, mShutterButton.isPressed());
}
}
@TargetApi(ApiHelper.VERSION_CODES.JELLY_BEAN)
private final class AutoFocusMoveCallback
implements android.hardware.Camera.AutoFocusMoveCallback {
@Override
public void onAutoFocusMoving(
boolean moving, android.hardware.Camera camera) {
mFocusManager.onAutoFocusMoving(moving);
}
}
// Each SaveRequest remembers the data needed to save an image.
private static class SaveRequest {
byte[] data;
Uri uri;
String title;
Location loc;
int width, height;
int orientation;
}
// We use a queue to store the SaveRequests that have not been completed
// yet. The main thread puts the request into the queue. The saver thread
// gets it from the queue, does the work, and removes it from the queue.
//
// The main thread needs to wait for the saver thread to finish all the work
// in the queue, when the activity's onPause() is called, we need to finish
// all the work, so other programs (like Gallery) can see all the images.
//
// If the queue becomes too long, adding a new request will block the main
// thread until the queue length drops below the threshold (QUEUE_LIMIT).
// If we don't do this, we may face several problems: (1) We may OOM
// because we are holding all the jpeg data in memory. (2) We may ANR
// when we need to wait for saver thread finishing all the work (in
// onPause() or gotoGallery()) because the time to finishing a long queue
// of work may be too long.
private class ImageSaver extends Thread {
private static final int QUEUE_LIMIT = 3;
private ArrayList<SaveRequest> mQueue;
private boolean mStop;
// Runs in main thread
public ImageSaver() {
mQueue = new ArrayList<SaveRequest>();
start();
}
// Runs in main thread
public void addImage(final byte[] data, Uri uri, String title,
Location loc, int width, int height, int orientation) {
SaveRequest r = new SaveRequest();
r.data = data;
r.uri = uri;
r.title = title;
r.loc = (loc == null) ? null : new Location(loc); // make a copy
r.width = width;
r.height = height;
r.orientation = orientation;
synchronized (this) {
while (mQueue.size() >= QUEUE_LIMIT) {
try {
wait();
} catch (InterruptedException ex) {
// ignore.
}
}
mQueue.add(r);
notifyAll(); // Tell saver thread there is new work to do.
}
}
// Runs in saver thread
@Override
public void run() {
while (true) {
SaveRequest r;
synchronized (this) {
if (mQueue.isEmpty()) {
notifyAll(); // notify main thread in waitDone
// Note that we can only stop after we saved all images
// in the queue.
if (mStop) break;
try {
wait();
} catch (InterruptedException ex) {
// ignore.
}
continue;
}
r = mQueue.get(0);
}
storeImage(r.data, r.uri, r.title, r.loc, r.width, r.height,
r.orientation);
synchronized (this) {
mQueue.remove(0);
notifyAll(); // the main thread may wait in addImage
}
}
}
// Runs in main thread
public void waitDone() {
synchronized (this) {
while (!mQueue.isEmpty()) {
try {
wait();
} catch (InterruptedException ex) {
// ignore.
}
}
}
}
// Runs in main thread
public void finish() {
waitDone();
synchronized (this) {
mStop = true;
notifyAll();
}
try {
join();
} catch (InterruptedException ex) {
// ignore.
}
}
// Runs in saver thread
private void storeImage(final byte[] data, Uri uri, String title,
Location loc, int width, int height, int orientation) {
boolean ok = Storage.updateImage(mContentResolver, uri, title, loc,
orientation, data, width, height);
if (ok) {
Util.broadcastNewPicture(mActivity, uri);
}
}
}
private static class ImageNamer extends Thread {
private boolean mRequestPending;
private ContentResolver mResolver;
private long mDateTaken;
private int mWidth, mHeight;
private boolean mStop;
private Uri mUri;
private String mTitle;
// Runs in main thread
public ImageNamer() {
start();
}
// Runs in main thread
public synchronized void prepareUri(ContentResolver resolver,
long dateTaken, int width, int height, int rotation) {
if (rotation % 180 != 0) {
int tmp = width;
width = height;
height = tmp;
}
mRequestPending = true;
mResolver = resolver;
mDateTaken = dateTaken;
mWidth = width;
mHeight = height;
notifyAll();
}
// Runs in main thread
public synchronized Uri getUri() {
// wait until the request is done.
while (mRequestPending) {
try {
wait();
} catch (InterruptedException ex) {
// ignore.
}
}
// return the uri generated
Uri uri = mUri;
mUri = null;
return uri;
}
// Runs in main thread, should be called after getUri().
public synchronized String getTitle() {
return mTitle;
}
// Runs in namer thread
@Override
public synchronized void run() {
while (true) {
if (mStop) break;
if (!mRequestPending) {
try {
wait();
} catch (InterruptedException ex) {
// ignore.
}
continue;
}
cleanOldUri();
generateUri();
mRequestPending = false;
notifyAll();
}
cleanOldUri();
}
// Runs in main thread
public synchronized void finish() {
mStop = true;
notifyAll();
}
// Runs in namer thread
private void generateUri() {
mTitle = Util.createJpegName(mDateTaken);
mUri = Storage.newImage(mResolver, mTitle, mDateTaken, mWidth, mHeight);
}
// Runs in namer thread
private void cleanOldUri() {
if (mUri == null) return;
Storage.deleteImage(mResolver, mUri);
mUri = null;
}
}
private void setCameraState(int state) {
mCameraState = state;
switch (state) {
case PREVIEW_STOPPED:
case SNAPSHOT_IN_PROGRESS:
case FOCUSING:
case SWITCHING_CAMERA:
if (mGestures != null) mGestures.setEnabled(false);
break;
case IDLE:
if (mGestures != null && mActivity.mShowCameraAppView) {
// Enable gestures only when the camera app view is visible
mGestures.setEnabled(true);
}
break;
}
}
private void animateFlash() {
// Only animate when in full screen capture mode
// i.e. If monkey/a user swipes to the gallery during picture taking,
// don't show animation
if (ApiHelper.HAS_SURFACE_TEXTURE && !mIsImageCaptureIntent
&& mActivity.mShowCameraAppView) {
// Start capture animation.
((CameraScreenNail) mActivity.mCameraScreenNail).animateFlash(mDisplayRotation);
}
}
@Override
public boolean capture() {
// If we are already in the middle of taking a snapshot then ignore.
if (mCameraDevice == null || mCameraState == SNAPSHOT_IN_PROGRESS
|| mCameraState == SWITCHING_CAMERA) {
return false;
}
mCaptureStartTime = System.currentTimeMillis();
mPostViewPictureCallbackTime = 0;
mJpegImageData = null;
final boolean animateBefore = (mSceneMode == Util.SCENE_MODE_HDR);
if (animateBefore) {
animateFlash();
}
// Set rotation and gps data.
mJpegRotation = Util.getJpegRotation(mCameraId, mOrientation);
mParameters.setRotation(mJpegRotation);
Location loc = mLocationManager.getCurrentLocation();
Util.setGpsParameters(mParameters, loc);
mCameraDevice.setParameters(mParameters);
mCameraDevice.takePicture2(mShutterCallback, mRawPictureCallback,
mPostViewPictureCallback, new JpegPictureCallback(loc),
mCameraState, mFocusManager.getFocusState());
if (Util.enableZSL()) {
mRestartPreview = false;
}
if (!animateBefore) {
animateFlash();
}
Size size = mParameters.getPictureSize();
mImageNamer.prepareUri(mContentResolver, mCaptureStartTime,
size.width, size.height, mJpegRotation);
mFaceDetectionStarted = false;
setCameraState(SNAPSHOT_IN_PROGRESS);
return true;
}
@Override
public void setFocusParameters() {
setCameraParameters(UPDATE_PARAM_PREFERENCE);
}
private int getPreferredCameraId(ComboPreferences preferences) {
int intentCameraId = Util.getCameraFacingIntentExtras(mActivity);
if (intentCameraId != -1) {
// Testing purpose. Launch a specific camera through the intent
// extras.
return intentCameraId;
} else {
return CameraSettings.readPreferredCameraId(preferences);
}
}
private void setShowMenu(boolean show) {
if (mOnScreenIndicators != null) {
mOnScreenIndicators.setVisibility(show ? View.VISIBLE : View.GONE);
}
if (mMenu != null) {
mMenu.setVisibility(show ? View.VISIBLE : View.GONE);
}
}
@Override
public void onFullScreenChanged(boolean full) {
if (mFaceView != null) {
mFaceView.setBlockDraw(!full);
}
if (mPopup != null) {
dismissPopup(false, full);
}
if (mGestures != null) {
mGestures.setEnabled(full);
}
if (mRenderOverlay != null) {
// this can not happen in capture mode
mRenderOverlay.setVisibility(full ? View.VISIBLE : View.GONE);
}
if (mPieRenderer != null) {
mPieRenderer.setBlockFocus(!full);
}
setShowMenu(full);
if (mBlocker != null) {
mBlocker.setVisibility(full ? View.VISIBLE : View.GONE);
}
if (ApiHelper.HAS_SURFACE_TEXTURE) {
if (mActivity.mCameraScreenNail != null) {
((CameraScreenNail) mActivity.mCameraScreenNail).setFullScreen(full);
}
return;
}
if (full) {
mPreviewSurfaceView.expand();
} else {
mPreviewSurfaceView.shrink();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Log.v(TAG, "surfaceChanged:" + holder + " width=" + width + ". height="
+ height);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
Log.v(TAG, "surfaceCreated: " + holder);
mCameraSurfaceHolder = holder;
// Do not access the camera if camera start up thread is not finished.
if (mCameraDevice == null || mCameraStartUpThread != null) return;
mCameraDevice.setPreviewDisplayAsync(holder);
// This happens when onConfigurationChanged arrives, surface has been
// destroyed, and there is no onFullScreenChanged.
if (mCameraState == PREVIEW_STOPPED) {
setupPreview();
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.v(TAG, "surfaceDestroyed: " + holder);
mCameraSurfaceHolder = null;
stopPreview();
}
private void updateSceneModeUI() {
// If scene mode is set, we cannot set flash mode, white balance, and
// focus mode, instead, we read it from driver
if (!Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
overrideCameraSettings(mParameters.getFlashMode(),
mParameters.getWhiteBalance(), mParameters.getFocusMode());
} else {
overrideCameraSettings(null, null, null);
}
}
private void overrideCameraSettings(final String flashMode,
final String whiteBalance, final String focusMode) {
if (mPhotoControl != null) {
// mPieControl.enableFilter(true);
mPhotoControl.overrideSettings(
CameraSettings.KEY_FLASH_MODE, flashMode,
CameraSettings.KEY_WHITE_BALANCE, whiteBalance,
CameraSettings.KEY_FOCUS_MODE, focusMode);
// mPieControl.enableFilter(false);
}
}
private void loadCameraPreferences() {
CameraSettings settings = new CameraSettings(mActivity, mInitialParams,
mCameraId, CameraHolder.instance().getCameraInfo());
mPreferenceGroup = settings.getPreferenceGroup(R.xml.camera_preferences);
}
@Override
public boolean collapseCameraControls() {
// Remove all the popups/dialog boxes
boolean ret = false;
if (mPopup != null) {
dismissPopup(false);
ret = true;
}
return ret;
}
public boolean removeTopLevelPopup() {
// Remove the top level popup or dialog box and return true if there's any
if (mPopup != null) {
dismissPopup(true);
return true;
}
return false;
}
@Override
public void onOrientationChanged(int orientation) {
// We keep the last known orientation. So if the user first orient
// the camera then point the camera to floor or sky, we still have
// the correct orientation.
if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN) return;
mOrientation = Util.roundOrientation(orientation, mOrientation);
// When the screen is unlocked, display rotation may change. Always
// calculate the up-to-date orientationCompensation.
int orientationCompensation =
(mOrientation + Util.getDisplayRotation(mActivity)) % 360;
if (mOrientationCompensation != orientationCompensation) {
mOrientationCompensation = orientationCompensation;
if (mFaceView != null) {
mFaceView.setOrientation(mOrientationCompensation, true);
}
setDisplayOrientation();
}
// Show the toast after getting the first orientation changed.
if (mHandler.hasMessages(SHOW_TAP_TO_FOCUS_TOAST)) {
mHandler.removeMessages(SHOW_TAP_TO_FOCUS_TOAST);
showTapToFocusToast();
}
}
@Override
public void onStop() {
if (mMediaProviderClient != null) {
mMediaProviderClient.release();
mMediaProviderClient = null;
}
}
// onClick handler for R.id.btn_done
@OnClickAttr
public void onReviewDoneClicked(View v) {
doAttach();
}
// onClick handler for R.id.btn_cancel
@OnClickAttr
public void onReviewCancelClicked(View v) {
doCancel();
}
// onClick handler for R.id.btn_retake
@OnClickAttr
public void onReviewRetakeClicked(View v) {
if (mPaused)
return;
hidePostCaptureAlert();
setupPreview();
}
private void doAttach() {
if (mPaused) {
return;
}
byte[] data = mJpegImageData;
if (mCropValue == null) {
// First handle the no crop case -- just return the value. If the
// caller specifies a "save uri" then write the data to its
// stream. Otherwise, pass back a scaled down version of the bitmap
// directly in the extras.
if (mSaveUri != null) {
OutputStream outputStream = null;
try {
outputStream = mContentResolver.openOutputStream(mSaveUri);
outputStream.write(data);
outputStream.close();
mActivity.setResultEx(Activity.RESULT_OK);
mActivity.finish();
} catch (IOException ex) {
// ignore exception
} finally {
Util.closeSilently(outputStream);
}
} else {
int orientation = Exif.getOrientation(data);
Bitmap bitmap = Util.makeBitmap(data, 50 * 1024);
bitmap = Util.rotate(bitmap, orientation);
mActivity.setResultEx(Activity.RESULT_OK,
new Intent("inline-data").putExtra("data", bitmap));
mActivity.finish();
}
} else {
// Save the image to a temp file and invoke the cropper
Uri tempUri = null;
FileOutputStream tempStream = null;
try {
File path = mActivity.getFileStreamPath(sTempCropFilename);
path.delete();
tempStream = mActivity.openFileOutput(sTempCropFilename, 0);
tempStream.write(data);
tempStream.close();
tempUri = Uri.fromFile(path);
} catch (FileNotFoundException ex) {
mActivity.setResultEx(Activity.RESULT_CANCELED);
mActivity.finish();
return;
} catch (IOException ex) {
mActivity.setResultEx(Activity.RESULT_CANCELED);
mActivity.finish();
return;
} finally {
Util.closeSilently(tempStream);
}
Bundle newExtras = new Bundle();
if (mCropValue.equals("circle")) {
newExtras.putString("circleCrop", "true");
}
if (mSaveUri != null) {
newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, mSaveUri);
} else {
newExtras.putBoolean("return-data", true);
}
if (mActivity.isSecureCamera()) {
newExtras.putBoolean(CropImage.KEY_SHOW_WHEN_LOCKED, true);
}
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setData(tempUri);
cropIntent.putExtras(newExtras);
mActivity.startActivityForResult(cropIntent, REQUEST_CROP);
}
}
private void doCancel() {
mActivity.setResultEx(Activity.RESULT_CANCELED, new Intent());
mActivity.finish();
}
@Override
public void onShutterButtonFocus(boolean pressed) {
if (mPaused || collapseCameraControls()
|| (mCameraState == SNAPSHOT_IN_PROGRESS)
|| (mCameraState == PREVIEW_STOPPED)) return;
// Do not do focus if there is not enough storage.
if (pressed && !canTakePicture()) return;
if (pressed) {
if (mSceneMode == Util.SCENE_MODE_HDR) {
mActivity.hideSwitcher();
mActivity.setSwipingEnabled(false);
}
mFocusManager.onShutterDown();
} else {
mFocusManager.onShutterUp();
}
}
@Override
public void onShutterButtonClick() {
int nbBurstShots = Integer.valueOf(mPreferences.getString(CameraSettings.KEY_BURST_MODE, "1"));
if (mPaused || collapseCameraControls()
|| (mCameraState == SWITCHING_CAMERA)
|| (mCameraState == PREVIEW_STOPPED)) return;
// Do not take the picture if there is not enough storage.
if (mActivity.getStorageSpace() <= Storage.LOW_STORAGE_THRESHOLD) {
Log.i(TAG, "Not enough space or storage not ready. remaining="
+ mActivity.getStorageSpace());
return;
}
Log.v(TAG, "onShutterButtonClick: mCameraState=" + mCameraState);
// If the user wants to do a snapshot while the previous one is still
// in progress, remember the fact and do it after we finish the previous
// one and re-start the preview. Snapshot in progress also includes the
// state that autofocus is focusing and a picture will be taken when
// focus callback arrives.
if ((mFocusManager.isFocusingSnapOnFinish() || mCameraState == SNAPSHOT_IN_PROGRESS)
&& !mIsImageCaptureIntent) {
mSnapshotOnIdle = true;
return;
}
mFocusManager.doSnap();
mBurstShotsDone++;
if (mBurstShotsDone == nbBurstShots) {
mBurstShotsDone = 0;
mSnapshotOnIdle = false;
} else if (mSnapshotOnIdle == false) {
// queue a new shot until we done all our shots
mSnapshotOnIdle = true;
}
}
@Override
public void installIntentFilter() {
}
@Override
public boolean updateStorageHintOnResume() {
return mFirstTimeInitialized;
}
@Override
public void updateCameraAppView() {
// Setup Power shutter
mActivity.initPowerShutter(mPreferences);
}
@Override
public void onResumeBeforeSuper() {
mPaused = false;
}
@Override
public void onResumeAfterSuper() {
if (mOpenCameraFail || mCameraDisabled) return;
mJpegPictureCallbackTime = 0;
mZoomValue = 0;
// Start the preview if it is not started.
if (mCameraState == PREVIEW_STOPPED && mCameraStartUpThread == null) {
resetExposureCompensation();
mCameraStartUpThread = new CameraStartUpThread();
mCameraStartUpThread.start();
}
// If first time initialization is not finished, put it in the
// message queue.
if (!mFirstTimeInitialized) {
mHandler.sendEmptyMessage(FIRST_TIME_INIT);
} else {
initializeSecondTime();
}
keepScreenOnAwhile();
// Dismiss open menu if exists.
PopupManager.getInstance(mActivity).notifyShowPopup(null);
}
void waitCameraStartUpThread() {
try {
if (mCameraStartUpThread != null) {
mCameraStartUpThread.cancel();
mCameraStartUpThread.join();
mCameraStartUpThread = null;
setCameraState(IDLE);
}
} catch (InterruptedException e) {
// ignore
}
}
@Override
public void onPauseBeforeSuper() {
mPaused = true;
}
@Override
public void onPauseAfterSuper() {
// Wait the camera start up thread to finish.
waitCameraStartUpThread();
// When camera is started from secure lock screen for the first time
// after screen on, the activity gets onCreate->onResume->onPause->onResume.
// To reduce the latency, keep the camera for a short time so it does
// not need to be opened again.
if (mCameraDevice != null && mActivity.isSecureCamera()
&& ActivityBase.isFirstStartAfterScreenOn()) {
ActivityBase.resetFirstStartAfterScreenOn();
CameraHolder.instance().keep(KEEP_CAMERA_TIMEOUT);
}
// Reset the focus first. Camera CTS does not guarantee that
// cancelAutoFocus is allowed after preview stops.
if (mCameraDevice != null && mCameraState != PREVIEW_STOPPED) {
mCameraDevice.cancelAutoFocus();
}
stopPreview();
// Close the camera now because other activities may need to use it.
closeCamera();
if (mSurfaceTexture != null) {
((CameraScreenNail) mActivity.mCameraScreenNail).releaseSurfaceTexture();
mSurfaceTexture = null;
}
resetScreenOn();
// Load the power shutter
mActivity.initPowerShutter(mPreferences);
// Clear UI.
collapseCameraControls();
if (mFaceView != null) mFaceView.clear();
if (mFirstTimeInitialized) {
if (mImageSaver != null) {
mImageSaver.finish();
mImageSaver = null;
mImageNamer.finish();
mImageNamer = null;
}
}
if (mLocationManager != null) mLocationManager.recordLocation(false);
// If we are in an image capture intent and has taken
// a picture, we just clear it in onPause.
mJpegImageData = null;
// Remove the messages in the event queue.
mHandler.removeMessages(SETUP_PREVIEW);
mHandler.removeMessages(FIRST_TIME_INIT);
mHandler.removeMessages(CHECK_DISPLAY_ROTATION);
mHandler.removeMessages(SWITCH_CAMERA);
mHandler.removeMessages(SWITCH_CAMERA_START_ANIMATION);
mHandler.removeMessages(CAMERA_OPEN_DONE);
mHandler.removeMessages(START_PREVIEW_DONE);
mHandler.removeMessages(OPEN_CAMERA_FAIL);
mHandler.removeMessages(CAMERA_DISABLED);
mPendingSwitchCameraId = -1;
if (mFocusManager != null) mFocusManager.removeMessages();
}
private void initializeControlByIntent() {
mBlocker = mRootView.findViewById(R.id.blocker);
mMenu = mRootView.findViewById(R.id.menu);
mMenu.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mPieRenderer != null) {
mPieRenderer.showInCenter();
}
}
});
if (mIsImageCaptureIntent) {
mActivity.hideSwitcher();
// Cannot use RotateImageView for "done" and "cancel" button because
// the tablet layout uses RotateLayout, which cannot be cast to
// RotateImageView.
mReviewDoneButton = (Rotatable) mRootView.findViewById(R.id.btn_done);
mReviewCancelButton = (Rotatable) mRootView.findViewById(R.id.btn_cancel);
mReviewRetakeButton = mRootView.findViewById(R.id.btn_retake);
((View) mReviewCancelButton).setVisibility(View.VISIBLE);
((View) mReviewDoneButton).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onReviewDoneClicked(v);
}
});
((View) mReviewCancelButton).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onReviewCancelClicked(v);
}
});
mReviewRetakeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onReviewRetakeClicked(v);
}
});
// Not grayed out upon disabled, to make the follow-up fade-out
// effect look smooth. Note that the review done button in tablet
// layout is not a TwoStateImageView.
if (mReviewDoneButton instanceof TwoStateImageView) {
((TwoStateImageView) mReviewDoneButton).enableFilter(false);
}
setupCaptureParams();
}
}
/**
* The focus manager is the first UI related element to get initialized,
* and it requires the RenderOverlay, so initialize it here
*/
private void initializeFocusManager() {
// Create FocusManager object. startPreview needs it.
mRenderOverlay = (RenderOverlay) mRootView.findViewById(R.id.render_overlay);
// if mFocusManager not null, reuse it
// otherwise create a new instance
if (mFocusManager != null) {
mFocusManager.removeMessages();
} else {
CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
boolean mirror = (info.facing == CameraInfo.CAMERA_FACING_FRONT);
String[] defaultFocusModes = mActivity.getResources().getStringArray(
R.array.pref_camera_focusmode_default_array);
mFocusManager = new FocusOverlayManager(mPreferences, defaultFocusModes,
mInitialParams, this, mirror,
mActivity.getMainLooper());
}
}
private void initializeMiscControls() {
// startPreview needs this.
mPreviewFrameLayout = (PreviewFrameLayout) mRootView.findViewById(R.id.frame);
// Set touch focus listener.
mActivity.setSingleTapUpListener(mPreviewFrameLayout);
mFaceView = (FaceView) mRootView.findViewById(R.id.face_view);
mPreviewFrameLayout.setOnSizeChangedListener(this);
mPreviewFrameLayout.setOnLayoutChangeListener(mActivity);
if (!ApiHelper.HAS_SURFACE_TEXTURE) {
mPreviewSurfaceView =
(PreviewSurfaceView) mRootView.findViewById(R.id.preview_surface_view);
mPreviewSurfaceView.setVisibility(View.VISIBLE);
mPreviewSurfaceView.getHolder().addCallback(this);
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
Log.v(TAG, "onConfigurationChanged");
setDisplayOrientation();
((ViewGroup) mRootView).removeAllViews();
LayoutInflater inflater = mActivity.getLayoutInflater();
inflater.inflate(R.layout.photo_module, (ViewGroup) mRootView);
// from onCreate()
initializeControlByIntent();
initializeFocusManager();
initializeMiscControls();
loadCameraPreferences();
// from initializeFirstTime()
mShutterButton = mActivity.getShutterButton();
mShutterButton.setOnShutterButtonListener(this);
initializeZoom();
initOnScreenIndicator();
updateOnScreenIndicators();
if (mFaceView != null) {
mFaceView.clear();
mFaceView.setVisibility(View.VISIBLE);
mFaceView.setDisplayOrientation(mDisplayOrientation);
CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
mFaceView.setMirror(info.facing == CameraInfo.CAMERA_FACING_FRONT);
mFaceView.resume();
mFocusManager.setFaceView(mFaceView);
}
initializeRenderOverlay();
onFullScreenChanged(mActivity.isInCameraApp());
if (mJpegImageData != null) { // Jpeg data found, picture has been taken.
showPostCaptureAlert();
}
}
@Override
public void onActivityResult(
int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CROP: {
Intent intent = new Intent();
if (data != null) {
Bundle extras = data.getExtras();
if (extras != null) {
intent.putExtras(extras);
}
}
mActivity.setResultEx(resultCode, intent);
mActivity.finish();
File path = mActivity.getFileStreamPath(sTempCropFilename);
path.delete();
break;
}
}
}
private boolean canTakePicture() {
return isCameraIdle() && (mActivity.getStorageSpace() > Storage.LOW_STORAGE_THRESHOLD);
}
@Override
public void autoFocus() {
mFocusStartTime = System.currentTimeMillis();
mCameraDevice.autoFocus(mAutoFocusCallback);
setCameraState(FOCUSING);
}
@Override
public void cancelAutoFocus() {
mCameraDevice.cancelAutoFocus();
setCameraState(IDLE);
setCameraParameters(UPDATE_PARAM_PREFERENCE);
}
// Preview area is touched. Handle touch focus.
@Override
public void onSingleTapUp(View view, int x, int y) {
if (mPaused || mCameraDevice == null || !mFirstTimeInitialized
|| mCameraState == SNAPSHOT_IN_PROGRESS
|| mCameraState == SWITCHING_CAMERA
|| mCameraState == PREVIEW_STOPPED) {
return;
}
// Do not trigger touch focus if popup window is opened.
if (removeTopLevelPopup()) return;
// Check if metering area or focus area is supported.
if (!mFocusAreaSupported && !mMeteringAreaSupported) return;
mFocusManager.onSingleTapUp(x, y);
}
@Override
public boolean onBackPressed() {
if (mPieRenderer != null && mPieRenderer.showsItems()) {
mPieRenderer.hide();
return true;
}
// In image capture mode, back button should:
// 1) if there is any popup, dismiss them, 2) otherwise, get out of image capture
if (mIsImageCaptureIntent) {
if (!removeTopLevelPopup()) {
// no popup to dismiss, cancel image capture
doCancel();
}
return true;
} else if (!isCameraIdle()) {
// ignore backs while we're taking a picture
return true;
} else {
return removeTopLevelPopup();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (!mActivity.mShowCameraAppView) {
return false;
}
switch (keyCode) {
case KeyEvent.KEYCODE_FOCUS:
if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
onShutterButtonFocus(true);
}
return true;
case KeyEvent.KEYCODE_CAMERA:
if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
onShutterButtonClick();
}
return true;
case KeyEvent.KEYCODE_DPAD_CENTER:
// If we get a dpad center event without any focused view, move
// the focus to the shutter button and press it.
if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
// Start auto-focus immediately to reduce shutter lag. After
// the shutter button gets the focus, onShutterButtonFocus()
// will be called again but it is fine.
if (removeTopLevelPopup()) return true;
onShutterButtonFocus(true);
if (mShutterButton.isInTouchMode()) {
mShutterButton.requestFocusFromTouch();
} else {
mShutterButton.requestFocus();
}
mShutterButton.setPressed(true);
}
return true;
case KeyEvent.KEYCODE_POWER:
if (mFirstTimeInitialized && event.getRepeatCount() == 0 && ActivityBase.mPowerShutter) {
onShutterButtonFocus(true);
}
return true;
case KeyEvent.KEYCODE_VOLUME_UP:
if (mParameters.isZoomSupported() && mZoomRenderer != null) {
int index = mZoomValue + 1;
processZoomValueChanged(index);
}
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (mParameters.isZoomSupported() && mZoomRenderer != null) {
int index = mZoomValue - 1;
processZoomValueChanged(index);
}
return true;
}
return false;
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (!mActivity.mShowCameraAppView) {
return false;
}
switch (keyCode) {
case KeyEvent.KEYCODE_FOCUS:
if (mFirstTimeInitialized) {
onShutterButtonFocus(false);
}
return true;
case KeyEvent.KEYCODE_POWER:
if (ActivityBase.mPowerShutter) {
onShutterButtonClick();
}
return true;
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (mParameters.isZoomSupported() && mZoomRenderer != null) {
return true;
}
break;
}
return false;
}
@TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
private void closeCamera() {
if (mCameraDevice != null) {
mCameraDevice.setZoomChangeListener(null);
if(ApiHelper.HAS_FACE_DETECTION) {
mCameraDevice.setFaceDetectionListener(null);
}
mCameraDevice.setErrorCallback(null);
CameraHolder.instance().release();
mFaceDetectionStarted = false;
mCameraDevice = null;
setCameraState(PREVIEW_STOPPED);
mFocusManager.onCameraReleased();
}
}
private void setDisplayOrientation() {
mDisplayRotation = Util.getDisplayRotation(mActivity);
mDisplayOrientation = Util.getDisplayOrientation(mDisplayRotation, mCameraId);
mCameraDisplayOrientation = Util.getDisplayOrientation(0, mCameraId);
if (mFaceView != null) {
mFaceView.setDisplayOrientation(mDisplayOrientation);
}
if (mFocusManager != null) {
mFocusManager.setDisplayOrientation(mDisplayOrientation);
}
// GLRoot also uses the DisplayRotation, and needs to be told to layout to update
mActivity.getGLRoot().requestLayoutContentPane();
}
// Only called by UI thread.
private void setupPreview() {
mFocusManager.resetTouchFocus();
startPreview();
setCameraState(IDLE);
startFaceDetection();
}
// This can be called by UI Thread or CameraStartUpThread. So this should
// not modify the views.
private void startPreview() {
mCameraDevice.setErrorCallback(mErrorCallback);
// ICS camera frameworks has a bug. Face detection state is not cleared
// after taking a picture. Stop the preview to work around it. The bug
// was fixed in JB.
if (mCameraState != PREVIEW_STOPPED &&
(!mActivity.getResources().getBoolean(R.bool.previewStopsDuringSnapshot) ||
mCameraState != SNAPSHOT_IN_PROGRESS)
)
stopPreview();
setDisplayOrientation();
if (!mSnapshotOnIdle && !mAspectRatioChanged) {
// If the focus mode is continuous autofocus, call cancelAutoFocus to
// resume it because it may have been paused by autoFocus call.
if (Util.FOCUS_MODE_CONTINUOUS_PICTURE.equals(mFocusManager.getFocusMode())) {
mCameraDevice.cancelAutoFocus();
}
mFocusManager.setAeAwbLock(false); // Unlock AE and AWB.
}
setCameraParameters(UPDATE_PARAM_ALL);
if (ApiHelper.HAS_SURFACE_TEXTURE) {
CameraScreenNail screenNail = (CameraScreenNail) mActivity.mCameraScreenNail;
if (mSurfaceTexture == null) {
Size size = mParameters.getPreviewSize();
if (mCameraDisplayOrientation % 180 == 0) {
screenNail.setSize(size.width, size.height);
} else {
screenNail.setSize(size.height, size.width);
}
screenNail.enableAspectRatioClamping();
mActivity.notifyScreenNailChanged();
screenNail.acquireSurfaceTexture();
mSurfaceTexture = screenNail.getSurfaceTexture();
}
mCameraDevice.setDisplayOrientation(mCameraDisplayOrientation);
mCameraDevice.setPreviewTextureAsync((SurfaceTexture) mSurfaceTexture);
} else {
mCameraDevice.setDisplayOrientation(mDisplayOrientation);
mCameraDevice.setPreviewDisplayAsync(mCameraSurfaceHolder);
}
Log.v(TAG, "startPreview");
mCameraDevice.startPreviewAsync();
mFocusManager.onPreviewStarted();
// Set camera mode
CameraSettings.setVideoMode(mParameters, false);
mCameraDevice.setParameters(mParameters);
if (mSnapshotOnIdle && mBurstShotsDone > 0) {
mHandler.post(mDoSnapRunnable);
}
}
private void stopPreview() {
if (mCameraDevice != null && mCameraState != PREVIEW_STOPPED) {
Log.v(TAG, "stopPreview");
mCameraDevice.stopPreview();
mFaceDetectionStarted = false;
}
setCameraState(PREVIEW_STOPPED);
if (mFocusManager != null) mFocusManager.onPreviewStopped();
}
@SuppressWarnings("deprecation")
private void updateCameraParametersInitialize() {
// Reset preview frame rate to the maximum because it may be lowered by
// video camera application.
List<Integer> frameRates = mParameters.getSupportedPreviewFrameRates();
if (frameRates != null) {
Integer max = Collections.max(frameRates);
mParameters.setPreviewFrameRate(max);
}
mParameters.set(Util.RECORDING_HINT, Util.FALSE);
// Disable video stabilization. Convenience methods not available in API
// level <= 14
String vstabSupported = mParameters.get("video-stabilization-supported");
if ("true".equals(vstabSupported)) {
mParameters.set("video-stabilization", "false");
}
}
private void updateCameraParametersZoom() {
// Set zoom.
if (mParameters.isZoomSupported()) {
mParameters.setZoom(mZoomValue);
}
}
@TargetApi(ApiHelper.VERSION_CODES.JELLY_BEAN)
private void setAutoExposureLockIfSupported() {
if (mAeLockSupported) {
mParameters.setAutoExposureLock(mFocusManager.getAeAwbLock());
}
}
@TargetApi(ApiHelper.VERSION_CODES.JELLY_BEAN)
private void setAutoWhiteBalanceLockIfSupported() {
if (mAwbLockSupported) {
mParameters.setAutoWhiteBalanceLock(mFocusManager.getAeAwbLock());
}
}
@TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
private void setFocusAreasIfSupported() {
- if (mFocusAreaSupported) {
+ if (mFocusAreaSupported && mFocusManager.getFocusAreas() != null) {
mParameters.setFocusAreas(mFocusManager.getFocusAreas());
}
}
@TargetApi(ApiHelper.VERSION_CODES.ICE_CREAM_SANDWICH)
private void setMeteringAreasIfSupported() {
- if (mMeteringAreaSupported) {
+ if (mMeteringAreaSupported && mFocusManager.getMeteringAreas() != null) {
// Use the same area for focus and metering.
mParameters.setMeteringAreas(mFocusManager.getMeteringAreas());
}
}
private void updateCameraParametersPreference() {
setAutoExposureLockIfSupported();
setAutoWhiteBalanceLockIfSupported();
setFocusAreasIfSupported();
setMeteringAreasIfSupported();
// Set picture size.
String pictureSize = mPreferences.getString(
CameraSettings.KEY_PICTURE_SIZE, null);
if (pictureSize == null) {
CameraSettings.initialCameraPictureSize(mActivity, mParameters);
} else {
Size oldSize = mParameters.getPictureSize();
List<Size> supported = mParameters.getSupportedPictureSizes();
CameraSettings.setCameraPictureSize(
pictureSize, supported, mParameters);
Size size = mParameters.getPictureSize();
if (oldSize != null && size != null) {
if(!size.equals(oldSize) && mCameraState != PREVIEW_STOPPED) {
Log.d(TAG, "Picture size changed. Restart preview");
mAspectRatioChanged = true;
stopPreview();
}
}
}
Size size = mParameters.getPictureSize();
// Set a preview size that is closest to the viewfinder height and has
// the right aspect ratio.
List<Size> sizes = mParameters.getSupportedPreviewSizes();
Size optimalSize = Util.getOptimalPreviewSize(mActivity, sizes,
(double) size.width / size.height);
Size original = mParameters.getPreviewSize();
if (!original.equals(optimalSize)) {
mParameters.setPreviewSize(optimalSize.width, optimalSize.height);
// Zoom related settings will be changed for different preview
// sizes, so set and read the parameters to get latest values
mCameraDevice.setParameters(mParameters);
mParameters = mCameraDevice.getParameters();
}
Log.v(TAG, "Preview size is " + optimalSize.width + "x" + optimalSize.height);
// Since changing scene mode may change supported values, set scene mode
// first. HDR is a scene mode. To promote it in UI, it is stored in a
// separate preference.
String hdr = mPreferences.getString(CameraSettings.KEY_CAMERA_HDR,
mActivity.getString(R.string.pref_camera_hdr_default));
if (mActivity.getString(R.string.setting_on_value).equals(hdr)) {
mSceneMode = Util.SCENE_MODE_HDR;
} else {
mSceneMode = mPreferences.getString(
CameraSettings.KEY_SCENE_MODE,
mActivity.getString(R.string.pref_camera_scenemode_default));
}
if (Util.isSupported(mSceneMode, mParameters.getSupportedSceneModes())) {
if (!mParameters.getSceneMode().equals(mSceneMode)) {
mParameters.setSceneMode(mSceneMode);
// Setting scene mode will change the settings of flash mode,
// white balance, and focus mode. Here we read back the
// parameters, so we can know those settings.
mCameraDevice.setParameters(mParameters);
mParameters = mCameraDevice.getParameters();
}
} else {
mSceneMode = mParameters.getSceneMode();
if (mSceneMode == null) {
mSceneMode = Parameters.SCENE_MODE_AUTO;
}
}
if (Util.enableZSL()) {
// Switch on ZSL mode
mParameters.set("camera-mode", "1");
} else {
//mParameters.setCameraMode(0);
}
// Set JPEG quality.
int jpegQuality = Integer.parseInt(mPreferences.getString(
CameraSettings.KEY_JPEG,
mActivity.getString(R.string.pref_camera_jpeg_default)));
mParameters.setJpegQuality(jpegQuality);
// For the following settings, we need to check if the settings are
// still supported by latest driver, if not, ignore the settings.
// Set ISO speed.
String isoMode = mPreferences.getString(CameraSettings.KEY_ISO_MODE,
mActivity.getString(R.string.pref_camera_iso_default));
if (Util.isSupported(isoMode, mParameters.getSupportedIsoValues()))
mParameters.setISOValue(isoMode);
// Color effect
String colorEffect = mPreferences.getString(
CameraSettings.KEY_COLOR_EFFECT,
mActivity.getString(R.string.pref_camera_coloreffect_default));
if (Util.isSupported(colorEffect, mParameters.getSupportedColorEffects())) {
mParameters.setColorEffect(colorEffect);
}
// Set exposure compensation
int value = CameraSettings.readExposure(mPreferences);
int max = mParameters.getMaxExposureCompensation();
int min = mParameters.getMinExposureCompensation();
if (value >= min && value <= max) {
mParameters.setExposureCompensation(value);
} else {
Log.w(TAG, "invalid exposure range: " + value);
}
if (Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) {
// Set flash mode.
String flashMode = mPreferences.getString(
CameraSettings.KEY_FLASH_MODE,
mActivity.getString(R.string.pref_camera_flashmode_default));
List<String> supportedFlash = mParameters.getSupportedFlashModes();
if (Util.isSupported(flashMode, supportedFlash)) {
mParameters.setFlashMode(flashMode);
} else {
flashMode = mParameters.getFlashMode();
if (flashMode == null) {
flashMode = mActivity.getString(
R.string.pref_camera_flashmode_no_flash);
}
}
// Set white balance parameter.
String whiteBalance = mPreferences.getString(
CameraSettings.KEY_WHITE_BALANCE,
mActivity.getString(R.string.pref_camera_whitebalance_default));
if (Util.isSupported(whiteBalance,
mParameters.getSupportedWhiteBalance())) {
mParameters.setWhiteBalance(whiteBalance);
} else {
whiteBalance = mParameters.getWhiteBalance();
if (whiteBalance == null) {
whiteBalance = Parameters.WHITE_BALANCE_AUTO;
}
}
// Set focus mode.
mFocusManager.overrideFocusMode(null);
mParameters.setFocusMode(mFocusManager.getFocusMode());
// Set focus time.
mFocusManager.setFocusTime(Integer.valueOf(
mPreferences.getString(CameraSettings.KEY_FOCUS_TIME,
mActivity.getString(R.string.pref_camera_focustime_default))));
} else {
mFocusManager.overrideFocusMode(mParameters.getFocusMode());
}
if (mContinousFocusSupported && ApiHelper.HAS_AUTO_FOCUS_MOVE_CALLBACK) {
updateAutoFocusMoveCallback();
}
}
@TargetApi(ApiHelper.VERSION_CODES.JELLY_BEAN)
private void updateAutoFocusMoveCallback() {
if (mParameters.getFocusMode().equals(Util.FOCUS_MODE_CONTINUOUS_PICTURE)) {
mCameraDevice.setAutoFocusMoveCallback(
(AutoFocusMoveCallback) mAutoFocusMoveCallback);
} else {
mCameraDevice.setAutoFocusMoveCallback(null);
}
}
// We separate the parameters into several subsets, so we can update only
// the subsets actually need updating. The PREFERENCE set needs extra
// locking because the preference can be changed from GLThread as well.
private void setCameraParameters(int updateSet) {
if ((updateSet & UPDATE_PARAM_INITIALIZE) != 0) {
updateCameraParametersInitialize();
// Set camera mode
CameraSettings.setVideoMode(mParameters, false);
}
if ((updateSet & UPDATE_PARAM_ZOOM) != 0) {
updateCameraParametersZoom();
}
if ((updateSet & UPDATE_PARAM_PREFERENCE) != 0) {
updateCameraParametersPreference();
}
CameraSettings.dumpParameters(mParameters);
mCameraDevice.setParameters(mParameters);
}
// If the Camera is idle, update the parameters immediately, otherwise
// accumulate them in mUpdateSet and update later.
private void setCameraParametersWhenIdle(int additionalUpdateSet) {
mUpdateSet |= additionalUpdateSet;
if (mCameraDevice == null) {
// We will update all the parameters when we open the device, so
// we don't need to do anything now.
mUpdateSet = 0;
return;
} else if (isCameraIdle()) {
if (mRestartPreview) {
Log.d(TAG, "Restarting preview");
startPreview();
mRestartPreview = false;
}
setCameraParameters(mUpdateSet);
updateSceneModeUI();
mUpdateSet = 0;
} else {
if (!mHandler.hasMessages(SET_CAMERA_PARAMETERS_WHEN_IDLE)) {
mHandler.sendEmptyMessageDelayed(
SET_CAMERA_PARAMETERS_WHEN_IDLE, 1000);
}
}
if (mAspectRatioChanged) {
Log.e(TAG, "Aspect ratio changed, restarting preview");
startPreview();
mAspectRatioChanged = false;
mHandler.sendEmptyMessage(START_PREVIEW_DONE);
}
}
private boolean isCameraIdle() {
return (mCameraState == IDLE) ||
((mFocusManager != null) && mFocusManager.isFocusCompleted()
&& (mCameraState != SWITCHING_CAMERA));
}
private boolean isImageCaptureIntent() {
String action = mActivity.getIntent().getAction();
return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action)
|| ActivityBase.ACTION_IMAGE_CAPTURE_SECURE.equals(action));
}
private void setupCaptureParams() {
Bundle myExtras = mActivity.getIntent().getExtras();
if (myExtras != null) {
mSaveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT);
mCropValue = myExtras.getString("crop");
}
}
private void showPostCaptureAlert() {
if (mIsImageCaptureIntent) {
mOnScreenIndicators.setVisibility(View.GONE);
mMenu.setVisibility(View.GONE);
Util.fadeIn((View) mReviewDoneButton);
mShutterButton.setVisibility(View.INVISIBLE);
Util.fadeIn(mReviewRetakeButton);
}
}
private void hidePostCaptureAlert() {
if (mIsImageCaptureIntent) {
mOnScreenIndicators.setVisibility(View.VISIBLE);
mMenu.setVisibility(View.VISIBLE);
Util.fadeOut((View) mReviewDoneButton);
mShutterButton.setVisibility(View.VISIBLE);
Util.fadeOut(mReviewRetakeButton);
}
}
@Override
public void onSharedPreferenceChanged() {
// ignore the events after "onPause()"
if (mPaused) return;
boolean recordLocation = RecordLocationPreference.get(
mPreferences, mContentResolver);
mLocationManager.recordLocation(recordLocation);
setCameraParametersWhenIdle(UPDATE_PARAM_PREFERENCE);
setPreviewFrameLayoutAspectRatio();
updateOnScreenIndicators();
mActivity.initPowerShutter(mPreferences);
}
@Override
public void onCameraPickerClicked(int cameraId) {
if (mPaused || mPendingSwitchCameraId != -1) return;
mPendingSwitchCameraId = cameraId;
if (ApiHelper.HAS_SURFACE_TEXTURE) {
Log.v(TAG, "Start to copy texture. cameraId=" + cameraId);
// We need to keep a preview frame for the animation before
// releasing the camera. This will trigger onPreviewTextureCopied.
((CameraScreenNail) mActivity.mCameraScreenNail).copyTexture();
// Disable all camera controls.
setCameraState(SWITCHING_CAMERA);
} else {
switchCamera();
}
}
private void switchCamera() {
if (mPaused) return;
Log.v(TAG, "Start to switch camera. id=" + mPendingSwitchCameraId);
mCameraId = mPendingSwitchCameraId;
mPendingSwitchCameraId = -1;
mPhotoControl.setCameraId(mCameraId);
// from onPause
closeCamera();
collapseCameraControls();
if (mFaceView != null) mFaceView.clear();
if (mFocusManager != null) mFocusManager.removeMessages();
// Restart the camera and initialize the UI. From onCreate.
mPreferences.setLocalId(mActivity, mCameraId);
CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
try {
mCameraDevice = Util.openCamera(mActivity, mCameraId);
mParameters = mCameraDevice.getParameters();
} catch (CameraHardwareException e) {
Util.showErrorAndFinish(mActivity, R.string.cannot_connect_camera);
return;
} catch (CameraDisabledException e) {
Util.showErrorAndFinish(mActivity, R.string.camera_disabled);
return;
}
initializeCapabilities();
CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
boolean mirror = (info.facing == CameraInfo.CAMERA_FACING_FRONT);
mFocusManager.setMirror(mirror);
mFocusManager.setParameters(mInitialParams);
setupPreview();
loadCameraPreferences();
initializePhotoControl();
// from initializeFirstTime
initializeZoom();
updateOnScreenIndicators();
showTapToFocusToastIfNeeded();
if (ApiHelper.HAS_SURFACE_TEXTURE) {
// Start switch camera animation. Post a message because
// onFrameAvailable from the old camera may already exist.
mHandler.sendEmptyMessage(SWITCH_CAMERA_START_ANIMATION);
}
}
@Override
public void onPieOpened(int centerX, int centerY) {
mActivity.cancelActivityTouchHandling();
mActivity.setSwipingEnabled(false);
if (mFaceView != null) {
mFaceView.setBlockDraw(true);
}
}
@Override
public void onPieClosed() {
mActivity.setSwipingEnabled(true);
if (mFaceView != null) {
mFaceView.setBlockDraw(false);
}
}
// Preview texture has been copied. Now camera can be released and the
// animation can be started.
@Override
public void onPreviewTextureCopied() {
mHandler.sendEmptyMessage(SWITCH_CAMERA);
}
@Override
public void onCaptureTextureCopied() {
}
@Override
public void onUserInteraction() {
if (!mActivity.isFinishing()) keepScreenOnAwhile();
}
private void resetScreenOn() {
mHandler.removeMessages(CLEAR_SCREEN_DELAY);
mActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
private void keepScreenOnAwhile() {
mHandler.removeMessages(CLEAR_SCREEN_DELAY);
mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mHandler.sendEmptyMessageDelayed(CLEAR_SCREEN_DELAY, SCREEN_DELAY);
}
// TODO: Delete this function after old camera code is removed
@Override
public void onRestorePreferencesClicked() {
}
@Override
public void onOverriddenPreferencesClicked() {
if (mPaused) return;
if (mNotSelectableToast == null) {
String str = mActivity.getResources().getString(R.string.not_selectable_in_scene_mode);
mNotSelectableToast = Toast.makeText(mActivity, str, Toast.LENGTH_SHORT);
}
mNotSelectableToast.show();
}
private void showTapToFocusToast() {
new RotateTextToast(mActivity, R.string.tap_to_focus, mOrientationCompensation).show();
// Clear the preference.
Editor editor = mPreferences.edit();
editor.putBoolean(CameraSettings.KEY_CAMERA_FIRST_USE_HINT_SHOWN, false);
editor.apply();
}
private void initializeCapabilities() {
mInitialParams = mCameraDevice.getParameters();
mFocusAreaSupported = Util.isFocusAreaSupported(mInitialParams);
mMeteringAreaSupported = Util.isMeteringAreaSupported(mInitialParams);
mAeLockSupported = Util.isAutoExposureLockSupported(mInitialParams);
mAwbLockSupported = Util.isAutoWhiteBalanceLockSupported(mInitialParams);
mContinousFocusSupported = mInitialParams.getSupportedFocusModes().contains(
Util.FOCUS_MODE_CONTINUOUS_PICTURE);
}
// PreviewFrameLayout size has changed.
@Override
public void onSizeChanged(int width, int height) {
if (mFocusManager != null) mFocusManager.setPreviewSize(width, height);
}
void setPreviewFrameLayoutAspectRatio() {
// Set the preview frame aspect ratio according to the picture size.
Size size = mParameters.getPictureSize();
mPreviewFrameLayout.setAspectRatio((double) size.width / size.height);
}
@Override
public boolean needsSwitcher() {
return !mIsImageCaptureIntent;
}
public void showPopup(AbstractSettingPopup popup) {
mActivity.hideUI();
mBlocker.setVisibility(View.INVISIBLE);
setShowMenu(false);
mPopup = popup;
// Make sure popup is brought up with the right orientation
mPopup.setOrientation(mOrientationCompensation, false);
mPopup.setVisibility(View.VISIBLE);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER;
((FrameLayout) mRootView).addView(mPopup, lp);
}
public void dismissPopup(boolean topPopupOnly) {
dismissPopup(topPopupOnly, true);
}
private void dismissPopup(boolean topOnly, boolean fullScreen) {
if (fullScreen) {
mActivity.showUI();
mBlocker.setVisibility(View.VISIBLE);
}
setShowMenu(fullScreen);
if (mPopup != null) {
((FrameLayout) mRootView).removeView(mPopup);
mPopup = null;
}
mPhotoControl.popupDismissed(topOnly);
}
@Override
public void onShowSwitcherPopup() {
if (mPieRenderer != null && mPieRenderer.showsItems()) {
mPieRenderer.hide();
}
}
}
| false | false | null | null |
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ProfileLaunchConfigurationDelegate.java b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ProfileLaunchConfigurationDelegate.java
index 53adddead..6f19915b5 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ProfileLaunchConfigurationDelegate.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch/src/org/eclipse/linuxtools/profiling/launch/ProfileLaunchConfigurationDelegate.java
@@ -1,211 +1,205 @@
package org.eclipse.linuxtools.profiling.launch;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import org.eclipse.cdt.launch.AbstractCLaunchDelegate;
import org.eclipse.cdt.utils.pty.PTY;
import org.eclipse.cdt.utils.spawner.ProcessFactory;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.model.IProcess;
import org.eclipse.jface.text.IDocument;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.TextConsole;
/**
* Helper class for launching command line tools. Contains methods for creating a process and
* one method for fetching from the console.
*
*
* @author chwang
*
*/
public abstract class ProfileLaunchConfigurationDelegate extends AbstractCLaunchDelegate{
/**
* Deletes and recreates the file at outputPath
*
* @param outputPath
* @return false if there is an IOException
*/
protected boolean testOutput(String outputPath) {
try {
//Make sure the output file exists
File tempFile = new File(outputPath);
tempFile.delete();
tempFile.createNewFile();
} catch (IOException e1) {
return false;
}
return true;
}
/**
* This method will create a process in the command line with I/O directed to the Eclipse console.
* It returns a reference to the process. Note that the process runs independently of Eclipse's threads,
* so you will have to poll the process to determine when it has terminated. To grab output from the
* process, either attach a <code>org.eclipse.debug.core.model.IStreamMonitor</code> to one of the monitors
* in <code>process.getStreamsProxy()</code>, or use the static get methods in
* <code>ProfileLaunchConfigurationDelegate</code>.
*
* <br>
* Will call generateCommand(config) to create the command line.
*
*
* @param config -- Use the configuration passed as a parameter to the launch method.
* @param cmd -- Command string, as it would appear on the command line.
* @param launch -- use the launch passed as a parameter to the launch method.
* @return
* @throws CoreException
* @throws IOException
*/
protected IProcess createProcess(ILaunchConfiguration config, ILaunch launch) throws CoreException, IOException {
File workDir = getWorkingDirectory(config);
if (workDir == null) {
workDir = new File(System.getProperty("user.home", ".")); //$NON-NLS-1$ //$NON-NLS-2$
}
//Put command into a shell script
String cmd = generateCommand(config);
- File script = File.createTempFile("org.eclipse.linuxtools.profiling.launch" + System.currentTimeMillis(),
- ".sh");
+ File script = File.createTempFile("org.eclipse.linuxtools.profiling.launch" + System.currentTimeMillis(), ".sh");
String data = "#!/bin/sh\nexec " + cmd; //$NON-NLS-1$
FileOutputStream out = new FileOutputStream(script);
out.write(data.getBytes());
-
String[] commandArray = prepareCommand("sh " + script.getAbsolutePath());
Process subProcess = execute(commandArray, getEnvironment(config),
workDir, true);
- if (subProcess == null){
- return null;
- }
-
IProcess process = createNewProcess(launch, subProcess,commandArray[0]);
// set the command line used
process.setAttribute(IProcess.ATTR_CMDLINE,cmd);
return process;
}
/**
* Use to generate the command.
* @param config
* @return The command string, as it would appear on command-line
*/
public abstract String generateCommand(ILaunchConfiguration config);
/**
* Prepare cmd for execution - we need a command array of strings,
* no string can contain a space character. The resulting command
* array will be passed in to the process.
*/
protected String[] prepareCommand(String cmd) {
String tmp[] = cmd.split(" "); //$NON-NLS-1$
ArrayList<String> cmdLine = new ArrayList<String>();
for (String str : tmp) {
cmdLine.add(str);
}
return (String[]) cmdLine.toArray(new String[cmdLine.size()]);
}
/**
* Executes a command array using pty
*
* @param commandArray -- Split a command string on the ' ' character
* @param env -- Use <code>getEnvironment(ILaunchConfiguration)</code> in the AbstractCLaunchDelegate.
* @param wd -- Working directory
* @param usePty -- A value of 'true' usually suffices
* @return A properly formed process, or null
* @throws IOException -- If the process cannot be created
*/
public Process execute(String[] commandArray, String[] env, File wd,
boolean usePty) throws IOException {
Process process = null;
try {
if (wd == null) {
process = ProcessFactory.getFactory().exec(commandArray, env);
} else {
if (PTY.isSupported() && usePty) {
process = ProcessFactory.getFactory().exec(commandArray,
env, wd, new PTY());
} else {
process = ProcessFactory.getFactory().exec(commandArray,
env, wd);
}
}
} catch (IOException e) {
if (process != null) {
process.destroy();
}
return null;
}
return process;
}
/**
* Spawn a new IProcess using the Debug Plugin.
*
* @param launch
* @param systemProcess
* @param programName
* @return
*/
protected IProcess createNewProcess(ILaunch launch, Process systemProcess,
String programName) {
return DebugPlugin.newProcess(launch, systemProcess,
renderProcessLabel(programName));
}
/**
*
* @param search : A String that can be found in the console
* @return The TextConsole having 'name' somewhere within it's name
*/
public static TextConsole getConsole(String search) {
for (int i = 0; i < ConsolePlugin.getDefault().getConsoleManager()
.getConsoles().length; i++) {
if (ConsolePlugin.getDefault().getConsoleManager().
getConsoles()[i].getName().contains(search)) {
return (TextConsole)ConsolePlugin.getDefault().getConsoleManager().getConsoles()[i];
}
}
return null;
}
/**
* Returns the contents of a console as a String
*
* @param search : Console name
* @return The text contained within that console
*/
public static String getMainConsoleText(String search){
TextConsole proc = (TextConsole) getConsole(search);
return ((IDocument)proc.getDocument()).get();
}
/**
* Return the document attached to containing the given string. For best results,
* use <code>ILaunchConfiguration.getName()</code>.
* @param search
* @return
*/
public static IDocument getConsoleDocument(String search) {
return ((TextConsole)getConsole(search)).getDocument();
}
}
| false | false | null | null |
diff --git a/src/com/group7/project/MainActivity.java b/src/com/group7/project/MainActivity.java
index 24da757..2955e53 100644
--- a/src/com/group7/project/MainActivity.java
+++ b/src/com/group7/project/MainActivity.java
@@ -1,484 +1,484 @@
package com.group7.project;
import java.lang.reflect.Field;
import java.util.List;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MapController;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.group7.project.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.GpsStatus;
import android.location.GpsStatus.Listener;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
public class MainActivity extends MapActivity implements BuildingCoordinates
{
private MapView mapView; // The map view used for higher level functions
private MapController mapController; // But most processing will happen with the map controller
private LocationManager locationManager; // Location manager deals with things to do with current device location (GPS)
private LocationListener locationListener; // The listener that checks for all events to do with location (GPS turned on/off, location change, etc.
private boolean trackingUser = false; // Boolean value keeps track of whether or not we are currently locked onto and tracking the user's location
static int markerLoc = -1; // Used to keep track of the user's location marker in the mapView list of overlays
ToggleButton toggleTrackingButton; // The button used to toggle turning user lock-on tracking on and off
GeoPoint userPoint; // The user's coordinates
// List<Building> listOfBuildings; // Listing of all buildings in BuildingCoordinates.java
private float distanceToBuilding; // Calculates distance between user and center point of building
private String currentBuilding = "(none)"; // String value to keep track of the building we are currently in
private Activity activity = this;
// private GoogleMap mMap;
/****************
* toggleUserTracking
*
* @param v - The view that called this function
*
* Called on click of toggleTrackingButton.
* Will turn lock-on tracking on and off, and update variables and buttons accordingly
*
*/
public void toggleUserTracking(View v)
{
//checks if a user point is set yet, or if the GPS is not turned on
if (userPoint == null || !locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
Toast.makeText(getBaseContext(), "Location not set by GPS", Toast.LENGTH_SHORT).show();
toggleTrackingButton.setChecked(false);
trackingUser = false; //redundant code for just in case situations
}
else
{
trackingUser = !trackingUser; //toggle the lock-on
toggleTrackingButton.setChecked(trackingUser); //turn button on/off
if (trackingUser)
{
mapController.animateTo(userPoint); //instantly focus on user's current location
}
}
}
/****************
* dispatchTouchEvent
*
* @param event - The event that called this function
*
* dispatchTouchEvent can handle many, MANY things. Right now all we need it for is to check
* when the user has panned the screen (MotionEvent.ACTION_MOVE).
* If the user has moved the screen around, then we should turn off the lock-on tracking of their location
* But they will have needed to have moved more than 70... units?
* This was to fix issues with pressing the toggle button and it also registering as movement, meaning the toggle
* would want to turn tracking off, but this function would do it first, so then the toggle would just turn it back
* on again
*
* Could use this function later to check on keeping the user within our required boundaries with use of LatLngBounds
*
*/
@Override
public boolean dispatchTouchEvent(MotionEvent event)
{
if (event.getAction() == MotionEvent.ACTION_MOVE)
{
float startX = event.getX();
float startY = event.getY();
float distanceSum = 0;
final int historySize = event.getHistorySize();
for (int h = 0; h < historySize; h++)
{
// historical point
float hx = event.getHistoricalX(0, h);
float hy = event.getHistoricalY(0, h);
// distance between startX,startY and historical point
float dx = (hx-startX);
float dy = (hy-startY);
distanceSum += Math.sqrt(dx*dx+dy*dy);
// make historical point the start point for next loop iteration
startX = hx;
startY = hy;
}
// add distance from last historical point to event's point
float dx = (event.getX(0)-startX);
float dy = (event.getY(0)-startY);
distanceSum += Math.sqrt(dx*dx+dy*dy);
if (distanceSum > 70.0)
{
trackingUser = false;
toggleTrackingButton.setChecked(false);
}
}
return super.dispatchTouchEvent(event);
}
/*
//LIMIT TO CAMPUS - THIS IS HARD
@Override
public boolean dispatchTouchEvent(MotionEvent event)
{
GeoPoint newPoint;
final float minLong = -97.156992f;
final float maxLong = -97.123303f;
final float minLat = 49.805292f;
final float maxLat = 49.813758f;
int currLat;
int currLong;
if (event.getAction() == MotionEvent.ACTION_MOVE)
{
newPoint = mapView.getProjection().fromPixels((int)event.getX(), (int)event.getY());
currLat = newPoint.getLatitudeE6();
currLong = newPoint.getLongitudeE6();
float temp = currLat - minLat;
int minLatInt = (int)(minLat * 1E6);
if ((currLat - minLatInt) < 0)
{
newPoint = new GeoPoint(minLatInt, currLong);
//mapController.stopPanning();
//mapController.setCenter(newPoint);
mapView.invalidate();
}
}
return super.dispatchTouchEvent(event);
}
*/
/****************
* onCreate
*
* @param savedInstanceState - Holds any dynamic data held in onSaveInstanceState (we don't need to worry about this)
*
* The initial set up of everything that needs to be done when the view is first created
* ie. when the app is first run
*
*/
@Override
protected void onCreate(Bundle savedInstanceState)
{
//Get a listing of all the buildings and save them so we can
// access them easier later
AllBuildings[0] = E1;
AllBuildings[1] = E2;
AllBuildings[2] = E3;
AllBuildings[3] = UCENTRE;
AllBuildings[4] = HOUSE;
//starting latitude and longitude. currently a location near EITC
final float startLat = 49.808503f;
final float startLong = -97.135824f;
super.onCreate(savedInstanceState); //run the parent's onCreate, where I imagine the UI stuff gets taken care of
setContentView(R.layout.activity_main); //set our main activity to be the default view
GeoPoint centerPoint = new GeoPoint((int)(startLat * 1E6), (int)(startLong * 1E6)); //create a GeoPoint based on those values
mapView = (MapView) findViewById(R.id.mapView); //get the MapView object from activity_main
toggleTrackingButton = (ToggleButton) findViewById(R.id.toggleTrackingButton); //get the toggleTrackingButton from activity_main
//settings on what to show on the map
//mapView.setSatellite(true);
//mapView.setTraffic(true);
//GPS setup stuff
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new GPSLocationListener();
locationManager.addGpsStatusListener((Listener) locationListener);
//This next line here sets our listener to check for changes to the GPS
//The first integer value is the minimum time to wait before taking another update (in milliseconds)
//So entering 500 here means it will only listen and run it's functions every 0.5 seconds
//The second integer value is the minimum change in distance required before the functions will be called (in metres)
//So entering 4 here means that unless the user has moved 4 metres from the last time we did an update, nothing will be called
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
//mapView.setBuiltInZoomControls(true); //turn on zoom controls
mapController = mapView.getController();
mapController.setZoom(20); //set default zoom level
mapController.setCenter(centerPoint); //move center of map
// Overlays stuff could be very important later on. I don't quite fully understand it yet myself
// All these do right now is display little Android icons at the North-East and South-West corners
// of a building (which I currently have set to E1).
// ***** THIS IS ONLY DEBUG CODE USED TO CHECK THE BOUNDS OF BUILDINGS ENTERED *******
// See the BuildingCoordinates.java file for more details on buildings
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.marker);
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable, this);
for(Building b:AllBuildings)
{
GeoPoint point = new GeoPoint(
(int) (b.getCenter().latitude * 1E6),
(int) (b.getCenter().longitude * 1E6)
);
OverlayItem overlayitem = new OverlayItem(point, b.getName(), "Founded: 1900");
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
}
}
/****************
* onCreateOptionsMenu
*
* @param menu - The menu we're gonna create? Not too sure about this function
*
* I imagine this could come in handy later if we want to do some menu stuff.
* Would need to read up on it more
*
*/
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/****************
* onBackPressed
*
* Called when the user presses the back button on the device
*
*/
public void onBackPressed()
{
//pressing the back button on the device will kill the app
System.exit(0);
}
/****************
* isRouteDisplayed
*
* Used if we want to display routing information
*/
@Override
protected boolean isRouteDisplayed()
{
//I should figure out what this is about
return true;
}
private class GPSLocationListener implements LocationListener, GpsStatus.Listener
{
private int GPSEvent = GpsStatus.GPS_EVENT_STOPPED; // Keeps track of the current status of the GPS
/****************
* onLocationChanged
*
* @param location - User's changed location
*
* Called any time the user's location changes
* So far, we're using it to update the location of the user's icon, but can later be used to check
* if a user is within the range of a building
*
*/
@Override
public void onLocationChanged(Location location) {
// Run the very first time the GPS gets a signal and is able to fix the user's location
if (location != null && GPSEvent == GpsStatus.GPS_EVENT_FIRST_FIX) {
userPoint = new GeoPoint(
(int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6)
);
if (trackingUser)
{
toggleTrackingButton.setChecked(true);
mapController.animateTo(userPoint);
mapController.setZoom(20);
}
// add marker
MapOverlay mapOverlay = new MapOverlay();
mapOverlay.setPointToDraw(userPoint);
List<Overlay> listOfOverlays = mapView.getOverlays();
if (markerLoc != -1) // markerLoc == -1 if no location had ever been previously set
{
listOfOverlays.remove(markerLoc);
}
listOfOverlays.add(mapOverlay); //add the marker to the mapView's overlays
markerLoc = listOfOverlays.size()-1; //keep track of where it's stored so we can update it later
//invalidating it forces the map view to re-draw
mapView.invalidate();
LatLng currPoint = new LatLng(location.getLatitude(), location.getLongitude());
// TEST CODE - to see if it could detect that I was inside my house
// This kind of code is the basis of what we could do to detect when the user is in range of a building
// This is more for when they enter a building. In terms of figuring out how far they are from a
// building, I don't think this code will work. LatLngBounds has a .getCenter() function in JavaScript
// which would have been AWESOME to have here. Unfortunately the Android API doesn't have anything like
// that. We could probably calculate our own if we really wanted to...
float minDistance = 1000;
Building minBuilding = null;
for(Building b: AllBuildings)
{
if (b.getBounds().contains(currPoint))
{
if (!currentBuilding.equals(b.getName()))
{
Toast.makeText(getBaseContext(),
- "ENTERED " + HOUSE.getName(),
+ "ENTERED " + b.getName(),
Toast.LENGTH_SHORT).show();
currentBuilding = b.getName();
}
}
else
{
distanceToBuilding = b.getCentreLocation().distanceTo(location);
if(distanceToBuilding < minDistance)
{
minDistance = distanceToBuilding;
minBuilding = b;
}
}
}
- if(minDistance == 70)//tell user they are near a building only once when they get about 70 metres close to it
+ if(minDistance == 70 && minBuilding != null)//tell user they are near a building only once when they get about 70 metres close to it
{ //this prevents multiple alerts as they get closer
AlertDialog.Builder builder1 = new AlertDialog.Builder(activity);
builder1.setMessage("You are near " + minBuilding.getName());
builder1.setCancelable(true);
AlertDialog alert11 = builder1.create();
alert11.show();
}
}
}
/****************
* onProviderDisabled
*
* @param provider - Name of the location provider that has been disabled
*
* We only use this right now to keep all our tracking information consistent when the user
* decides to turn off the GPS
*/
@Override
public void onProviderDisabled(String provider)
{
if (provider.equals(LocationManager.GPS_PROVIDER))
{
trackingUser = false;
toggleTrackingButton.setChecked(false);
}
}
@Override
public void onProviderEnabled(String provider)
{
//Toast.makeText(getBaseContext(), "Provider enabled (" + provider + ")", Toast.LENGTH_LONG).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
//Toast.makeText(getBaseContext(), "Status changed: (" + provider + " - " + status + ")", Toast.LENGTH_LONG).show();
}
/****************
* onGpsStatusChanged
*
* @param event - The integer value of the event that has occurred
*
* Used to update the GPSEvent variable so that we know what's going on with the GPS
*
* Called when the GPS' status has changed
* 1 = GPS_EVENT_STARTED (GPS turned on)
* 2 = GPS_EVENT_STOPPED (GPS turned off)
* 3 = GPS_EVENT_FIRST_FIX (Got fix on GPS satellite after having nothing and searching)
* 4 = GPS_EVENT_SATELLITE_STATUS (Event sent periodically to report GPS satellite status, we don't care about this)
*/
@Override
public void onGpsStatusChanged(int event)
{
//System.out.println("GPS Status: " + event);
if (event != GpsStatus.GPS_EVENT_SATELLITE_STATUS)
{
GPSEvent = event;
}
}
}
private class MapOverlay extends Overlay
{
private GeoPoint pointToDraw;
public void setPointToDraw(GeoPoint point)
{
pointToDraw = point;
}
/*
public GeoPoint getPointToDraw()
{
return pointToDraw;
}
*/
@Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when)
{
super.draw(canvas, mapView, shadow);
// convert point to pixels
Point screenPts = new Point();
mapView.getProjection().toPixels(pointToDraw, screenPts);
// add marker
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 24, null);
return true;
}
}
}
| false | true | public void onLocationChanged(Location location) {
// Run the very first time the GPS gets a signal and is able to fix the user's location
if (location != null && GPSEvent == GpsStatus.GPS_EVENT_FIRST_FIX) {
userPoint = new GeoPoint(
(int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6)
);
if (trackingUser)
{
toggleTrackingButton.setChecked(true);
mapController.animateTo(userPoint);
mapController.setZoom(20);
}
// add marker
MapOverlay mapOverlay = new MapOverlay();
mapOverlay.setPointToDraw(userPoint);
List<Overlay> listOfOverlays = mapView.getOverlays();
if (markerLoc != -1) // markerLoc == -1 if no location had ever been previously set
{
listOfOverlays.remove(markerLoc);
}
listOfOverlays.add(mapOverlay); //add the marker to the mapView's overlays
markerLoc = listOfOverlays.size()-1; //keep track of where it's stored so we can update it later
//invalidating it forces the map view to re-draw
mapView.invalidate();
LatLng currPoint = new LatLng(location.getLatitude(), location.getLongitude());
// TEST CODE - to see if it could detect that I was inside my house
// This kind of code is the basis of what we could do to detect when the user is in range of a building
// This is more for when they enter a building. In terms of figuring out how far they are from a
// building, I don't think this code will work. LatLngBounds has a .getCenter() function in JavaScript
// which would have been AWESOME to have here. Unfortunately the Android API doesn't have anything like
// that. We could probably calculate our own if we really wanted to...
float minDistance = 1000;
Building minBuilding = null;
for(Building b: AllBuildings)
{
if (b.getBounds().contains(currPoint))
{
if (!currentBuilding.equals(b.getName()))
{
Toast.makeText(getBaseContext(),
"ENTERED " + HOUSE.getName(),
Toast.LENGTH_SHORT).show();
currentBuilding = b.getName();
}
}
else
{
distanceToBuilding = b.getCentreLocation().distanceTo(location);
if(distanceToBuilding < minDistance)
{
minDistance = distanceToBuilding;
minBuilding = b;
}
}
}
if(minDistance == 70)//tell user they are near a building only once when they get about 70 metres close to it
{ //this prevents multiple alerts as they get closer
AlertDialog.Builder builder1 = new AlertDialog.Builder(activity);
builder1.setMessage("You are near " + minBuilding.getName());
builder1.setCancelable(true);
AlertDialog alert11 = builder1.create();
alert11.show();
}
}
}
| public void onLocationChanged(Location location) {
// Run the very first time the GPS gets a signal and is able to fix the user's location
if (location != null && GPSEvent == GpsStatus.GPS_EVENT_FIRST_FIX) {
userPoint = new GeoPoint(
(int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6)
);
if (trackingUser)
{
toggleTrackingButton.setChecked(true);
mapController.animateTo(userPoint);
mapController.setZoom(20);
}
// add marker
MapOverlay mapOverlay = new MapOverlay();
mapOverlay.setPointToDraw(userPoint);
List<Overlay> listOfOverlays = mapView.getOverlays();
if (markerLoc != -1) // markerLoc == -1 if no location had ever been previously set
{
listOfOverlays.remove(markerLoc);
}
listOfOverlays.add(mapOverlay); //add the marker to the mapView's overlays
markerLoc = listOfOverlays.size()-1; //keep track of where it's stored so we can update it later
//invalidating it forces the map view to re-draw
mapView.invalidate();
LatLng currPoint = new LatLng(location.getLatitude(), location.getLongitude());
// TEST CODE - to see if it could detect that I was inside my house
// This kind of code is the basis of what we could do to detect when the user is in range of a building
// This is more for when they enter a building. In terms of figuring out how far they are from a
// building, I don't think this code will work. LatLngBounds has a .getCenter() function in JavaScript
// which would have been AWESOME to have here. Unfortunately the Android API doesn't have anything like
// that. We could probably calculate our own if we really wanted to...
float minDistance = 1000;
Building minBuilding = null;
for(Building b: AllBuildings)
{
if (b.getBounds().contains(currPoint))
{
if (!currentBuilding.equals(b.getName()))
{
Toast.makeText(getBaseContext(),
"ENTERED " + b.getName(),
Toast.LENGTH_SHORT).show();
currentBuilding = b.getName();
}
}
else
{
distanceToBuilding = b.getCentreLocation().distanceTo(location);
if(distanceToBuilding < minDistance)
{
minDistance = distanceToBuilding;
minBuilding = b;
}
}
}
if(minDistance == 70 && minBuilding != null)//tell user they are near a building only once when they get about 70 metres close to it
{ //this prevents multiple alerts as they get closer
AlertDialog.Builder builder1 = new AlertDialog.Builder(activity);
builder1.setMessage("You are near " + minBuilding.getName());
builder1.setCancelable(true);
AlertDialog alert11 = builder1.create();
alert11.show();
}
}
}
|
diff --git a/test-unit/org/jivesoftware/smack/util/PacketParserUtilsTest.java b/test-unit/org/jivesoftware/smack/util/PacketParserUtilsTest.java
index d86cee19..abbab296 100644
--- a/test-unit/org/jivesoftware/smack/util/PacketParserUtilsTest.java
+++ b/test-unit/org/jivesoftware/smack/util/PacketParserUtilsTest.java
@@ -1,765 +1,765 @@
/**
* $Revision:$
* $Date:$
*
* Copyright (C) 2007 Jive Software. All rights reserved.
* This software is the proprietary information of Jive Software. Use is subject to license terms.
*/
package org.jivesoftware.smack.util;
import static junit.framework.Assert.*;
import static org.custommonkey.xmlunit.XMLAssert.*;
import java.io.IOException;
import java.io.StringReader;
import java.util.Locale;
import java.util.Properties;
import org.custommonkey.xmlunit.DetailedDiff;
import org.custommonkey.xmlunit.Diff;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.junit.Ignore;
import org.junit.Test;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import com.jamesmurty.utils.XMLBuilder;
/**
*
*/
public class PacketParserUtilsTest {
private static Properties outputProperties = new Properties();
{
outputProperties.put(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes");
}
@Test
public void singleMessageBodyTest() throws Exception {
String defaultLanguage = Packet.getDefaultLanguage();
String otherLanguage = determineNonDefaultLanguage();
String control;
// message has default language, body has no language
control = XMLBuilder.create("message")
.a("from", "[email protected]/orchard")
.a("to", "[email protected]/balcony")
.a("id", "zid615d9")
.a("type", "chat")
.a("xml:lang", defaultLanguage)
.e("body")
.t(defaultLanguage)
.asString(outputProperties);
Message message = (Message) PacketParserUtils
.parseMessage(getParser(control));
assertEquals(defaultLanguage, message.getBody());
assertTrue(message.getBodyLanguages().isEmpty());
assertEquals(defaultLanguage, message.getBody(defaultLanguage));
assertNull(message.getBody(otherLanguage));
assertXMLEqual(control, message.toXML());
// message has non-default language, body has no language
control = XMLBuilder.create("message")
.a("from", "[email protected]/orchard")
.a("to", "[email protected]/balcony")
.a("id", "zid615d9")
.a("type", "chat")
.a("xml:lang", otherLanguage)
.e("body")
.t(otherLanguage)
.asString(outputProperties);
message = (Message) PacketParserUtils.parseMessage(getParser(control));
assertEquals(otherLanguage, message.getBody());
assertTrue(message.getBodyLanguages().isEmpty());
assertEquals(otherLanguage, message.getBody(otherLanguage));
assertNull(message.getBody(defaultLanguage));
assertXMLEqual(control, message.toXML());
// message has no language, body has no language
control = XMLBuilder.create("message")
.a("from", "[email protected]/orchard")
.a("to", "[email protected]/balcony")
.a("id", "zid615d9")
.a("type", "chat")
.e("body")
.t(defaultLanguage)
.asString(outputProperties);
message = (Message) PacketParserUtils.parseMessage(getParser(control));
assertEquals(defaultLanguage, message.getBody());
assertTrue(message.getBodyLanguages().isEmpty());
assertEquals(defaultLanguage, message.getBody(defaultLanguage));
assertNull(message.getBody(otherLanguage));
assertXMLEqual(control, message.toXML());
// message has no language, body has default language
control = XMLBuilder.create("message")
.a("from", "[email protected]/orchard")
.a("to", "[email protected]/balcony")
.a("id", "zid615d9")
.a("type", "chat")
.e("body")
.a("xml:lang", defaultLanguage)
.t(defaultLanguage)
.asString(outputProperties);
message = (Message) PacketParserUtils.parseMessage(getParser(control));
assertEquals(defaultLanguage, message.getBody());
assertTrue(message.getBodyLanguages().isEmpty());
assertEquals(defaultLanguage, message.getBody(defaultLanguage));
assertNull(message.getBody(otherLanguage));
// body attribute xml:lang is unnecessary
assertXMLNotEqual(control, message.toXML());
// message has no language, body has non-default language
control = XMLBuilder.create("message")
.a("from", "[email protected]/orchard")
.a("to", "[email protected]/balcony")
.a("id", "zid615d9")
.a("type", "chat")
.e("body")
.a("xml:lang", otherLanguage)
.t(otherLanguage)
.asString(outputProperties);
message = (Message) PacketParserUtils.parseMessage(getParser(control));
assertNull(message.getBody());
assertFalse(message.getBodyLanguages().isEmpty());
assertTrue(message.getBodyLanguages().contains(otherLanguage));
assertEquals(otherLanguage, message.getBody(otherLanguage));
assertNull(message.getBody(defaultLanguage));
assertXMLEqual(control, message.toXML());
// message has default language, body has non-default language
control = XMLBuilder.create("message")
.a("from", "[email protected]/orchard")
.a("to", "[email protected]/balcony")
.a("id", "zid615d9")
.a("type", "chat")
.a("xml:lang", defaultLanguage)
.e("body")
.a("xml:lang", otherLanguage)
.t(otherLanguage)
.asString(outputProperties);
message = (Message) PacketParserUtils.parseMessage(getParser(control));
assertNull(message.getBody());
assertFalse(message.getBodyLanguages().isEmpty());
assertTrue(message.getBodyLanguages().contains(otherLanguage));
assertEquals(otherLanguage, message.getBody(otherLanguage));
assertNull(message.getBody(defaultLanguage));
assertXMLEqual(control, message.toXML());
// message has non-default language, body has default language
control = XMLBuilder.create("message")
.a("from", "[email protected]/orchard")
.a("to", "[email protected]/balcony")
.a("id", "zid615d9")
.a("type", "chat")
.a("xml:lang", otherLanguage)
.e("body")
.a("xml:lang", defaultLanguage)
.t(defaultLanguage)
.asString(outputProperties);
message = (Message) PacketParserUtils.parseMessage(getParser(control));
assertNull(message.getBody());
assertFalse(message.getBodyLanguages().isEmpty());
assertTrue(message.getBodyLanguages().contains(defaultLanguage));
assertEquals(defaultLanguage, message.getBody(defaultLanguage));
assertNull(message.getBody(otherLanguage));
assertXMLEqual(control, message.toXML());
}
@Test
public void singleMessageSubjectTest() throws Exception {
String defaultLanguage = Packet.getDefaultLanguage();
String otherLanguage = determineNonDefaultLanguage();
String control;
// message has default language, subject has no language
control = XMLBuilder.create("message")
.a("from", "[email protected]/orchard")
.a("to", "[email protected]/balcony")
.a("id", "zid615d9")
.a("type", "chat")
.a("xml:lang", defaultLanguage)
.e("subject")
.t(defaultLanguage)
.asString(outputProperties);
Message message = (Message) PacketParserUtils
.parseMessage(getParser(control));
assertEquals(defaultLanguage, message.getSubject());
assertTrue(message.getSubjectLanguages().isEmpty());
assertEquals(defaultLanguage, message.getSubject(defaultLanguage));
assertNull(message.getSubject(otherLanguage));
assertXMLEqual(control, message.toXML());
// message has non-default language, subject has no language
control = XMLBuilder.create("message")
.a("from", "[email protected]/orchard")
.a("to", "[email protected]/balcony")
.a("id", "zid615d9")
.a("type", "chat")
.a("xml:lang", otherLanguage)
.e("subject")
.t(otherLanguage)
.asString(outputProperties);
message = (Message) PacketParserUtils.parseMessage(getParser(control));
assertEquals(otherLanguage, message.getSubject());
assertTrue(message.getSubjectLanguages().isEmpty());
assertEquals(otherLanguage, message.getSubject(otherLanguage));
assertNull(message.getSubject(defaultLanguage));
assertXMLEqual(control, message.toXML());
// message has no language, subject has no language
control = XMLBuilder.create("message")
.a("from", "[email protected]/orchard")
.a("to", "[email protected]/balcony")
.a("id", "zid615d9")
.a("type", "chat")
.e("subject")
.t(defaultLanguage)
.asString(outputProperties);
message = (Message) PacketParserUtils.parseMessage(getParser(control));
assertEquals(defaultLanguage, message.getSubject());
assertTrue(message.getSubjectLanguages().isEmpty());
assertEquals(defaultLanguage, message.getSubject(defaultLanguage));
assertNull(message.getSubject(otherLanguage));
assertXMLEqual(control, message.toXML());
// message has no language, subject has default language
control = XMLBuilder.create("message")
.a("from", "[email protected]/orchard")
.a("to", "[email protected]/balcony")
.a("id", "zid615d9")
.a("type", "chat")
.e("subject")
.a("xml:lang", defaultLanguage)
.t(defaultLanguage)
.asString(outputProperties);
message = (Message) PacketParserUtils.parseMessage(getParser(control));
assertEquals(defaultLanguage, message.getSubject());
assertTrue(message.getSubjectLanguages().isEmpty());
assertEquals(defaultLanguage, message.getSubject(defaultLanguage));
assertNull(message.getSubject(otherLanguage));
// subject attribute xml:lang is unnecessary
assertXMLNotEqual(control, message.toXML());
// message has no language, subject has non-default language
control = XMLBuilder.create("message")
.a("from", "[email protected]/orchard")
.a("to", "[email protected]/balcony")
.a("id", "zid615d9")
.a("type", "chat")
.e("subject")
.a("xml:lang", otherLanguage)
.t(otherLanguage)
.asString(outputProperties);
message = (Message) PacketParserUtils.parseMessage(getParser(control));
assertNull(message.getSubject());
assertFalse(message.getSubjectLanguages().isEmpty());
assertTrue(message.getSubjectLanguages().contains(otherLanguage));
assertEquals(otherLanguage, message.getSubject(otherLanguage));
assertNull(message.getSubject(defaultLanguage));
assertXMLEqual(control, message.toXML());
// message has default language, subject has non-default language
control = XMLBuilder.create("message")
.a("from", "[email protected]/orchard")
.a("to", "[email protected]/balcony")
.a("id", "zid615d9")
.a("type", "chat")
.a("xml:lang", defaultLanguage)
.e("subject")
.a("xml:lang", otherLanguage)
.t(otherLanguage)
.asString(outputProperties);
message = (Message) PacketParserUtils.parseMessage(getParser(control));
assertNull(message.getSubject());
assertFalse(message.getSubjectLanguages().isEmpty());
assertTrue(message.getSubjectLanguages().contains(otherLanguage));
assertEquals(otherLanguage, message.getSubject(otherLanguage));
assertNull(message.getSubject(defaultLanguage));
assertXMLEqual(control, message.toXML());
// message has non-default language, subject has default language
control = XMLBuilder.create("message")
.a("from", "[email protected]/orchard")
.a("to", "[email protected]/balcony")
.a("id", "zid615d9")
.a("type", "chat")
.a("xml:lang", otherLanguage)
.e("subject")
.a("xml:lang", defaultLanguage)
.t(defaultLanguage)
.asString(outputProperties);
message = (Message) PacketParserUtils.parseMessage(getParser(control));
assertNull(message.getSubject());
assertFalse(message.getSubjectLanguages().isEmpty());
assertTrue(message.getSubjectLanguages().contains(defaultLanguage));
assertEquals(defaultLanguage, message.getSubject(defaultLanguage));
assertNull(message.getSubject(otherLanguage));
assertXMLEqual(control, message.toXML());
}
@Test
public void multipleMessageBodiesTest() throws Exception {
String defaultLanguage = Packet.getDefaultLanguage();
String otherLanguage = determineNonDefaultLanguage();
String control;
Message message;
// message has default language, first body no language, second body other language
control = XMLBuilder.create("message")
.a("from", "[email protected]/orchard")
.a("to", "[email protected]/balcony")
.a("id", "zid615d9")
.a("type", "chat")
.a("xml:lang", defaultLanguage)
.e("body")
.t(defaultLanguage)
.up()
.e("body")
.a("xml:lang", otherLanguage)
.t(otherLanguage)
.asString(outputProperties);
message = (Message) PacketParserUtils
.parseMessage(getParser(control));
assertEquals(defaultLanguage, message.getBody());
assertEquals(otherLanguage, message.getBody(otherLanguage));
assertEquals(2, message.getBodies().size());
assertEquals(1, message.getBodyLanguages().size());
assertTrue(message.getBodyLanguages().contains(otherLanguage));
assertXMLEqual(control, message.toXML());
// message has default language, first body no language, second body default language
control = XMLBuilder.create("message")
.a("from", "[email protected]/orchard")
.a("to", "[email protected]/balcony")
.a("id", "zid615d9")
.a("type", "chat")
.a("xml:lang", defaultLanguage)
.e("body")
.t(defaultLanguage)
.up()
.e("body")
.a("xml:lang", defaultLanguage)
.t(defaultLanguage + "2")
.asString(outputProperties);
message = (Message) PacketParserUtils
.parseMessage(getParser(control));
assertEquals(defaultLanguage, message.getBody());
assertEquals(defaultLanguage, message.getBody(defaultLanguage));
assertEquals(1, message.getBodies().size());
assertEquals(0, message.getBodyLanguages().size());
assertXMLNotEqual(control, message.toXML());
// message has non-default language, first body no language, second body default language
control = XMLBuilder.create("message")
.a("from", "[email protected]/orchard")
.a("to", "[email protected]/balcony")
.a("id", "zid615d9")
.a("type", "chat")
.a("xml:lang", otherLanguage)
.e("body")
.t(otherLanguage)
.up()
.e("body")
.a("xml:lang", defaultLanguage)
.t(defaultLanguage)
.asString(outputProperties);
message = (Message) PacketParserUtils
.parseMessage(getParser(control));
assertEquals(otherLanguage, message.getBody());
assertEquals(defaultLanguage, message.getBody(defaultLanguage));
assertEquals(2, message.getBodies().size());
assertEquals(1, message.getBodyLanguages().size());
assertTrue(message.getBodyLanguages().contains(defaultLanguage));
assertXMLEqual(control, message.toXML());
// message has no language, first body no language, second body default language
control = XMLBuilder.create("message")
.a("from", "[email protected]/orchard")
.a("to", "[email protected]/balcony")
.a("id", "zid615d9")
.a("type", "chat")
.e("body")
.t(defaultLanguage)
.up()
.e("body")
.a("xml:lang", defaultLanguage)
.t(defaultLanguage + "2")
.asString(outputProperties);
message = (Message) PacketParserUtils
.parseMessage(getParser(control));
assertEquals(defaultLanguage, message.getBody());
assertEquals(defaultLanguage, message.getBody(defaultLanguage));
assertEquals(1, message.getBodies().size());
assertEquals(0, message.getBodyLanguages().size());
assertXMLNotEqual(control, message.toXML());
// message has no language, first body no language, second body other language
control = XMLBuilder.create("message")
.a("from", "[email protected]/orchard")
.a("to", "[email protected]/balcony")
.a("id", "zid615d9")
.a("type", "chat")
.e("body")
.t(defaultLanguage)
.up()
.e("body")
.a("xml:lang", otherLanguage)
.t(otherLanguage)
.asString(outputProperties);
message = (Message) PacketParserUtils
.parseMessage(getParser(control));
assertEquals(defaultLanguage, message.getBody());
assertEquals(defaultLanguage, message.getBody(defaultLanguage));
assertEquals(otherLanguage, message.getBody(otherLanguage));
assertEquals(2, message.getBodies().size());
assertEquals(1, message.getBodyLanguages().size());
assertXMLEqual(control, message.toXML());
// message has no language, first body no language, second body no language
control = XMLBuilder.create("message")
.a("from", "[email protected]/orchard")
.a("to", "[email protected]/balcony")
.a("id", "zid615d9")
.a("type", "chat")
.e("body")
.t(defaultLanguage)
.up()
.e("body")
.t(otherLanguage)
.asString(outputProperties);
message = (Message) PacketParserUtils
.parseMessage(getParser(control));
assertEquals(defaultLanguage, message.getBody());
assertEquals(defaultLanguage, message.getBody(defaultLanguage));
assertEquals(1, message.getBodies().size());
assertEquals(0, message.getBodyLanguages().size());
assertXMLNotEqual(control, message.toXML());
}
@Test
public void multipleMessageSubjectsTest() throws Exception {
String defaultLanguage = Packet.getDefaultLanguage();
String otherLanguage = determineNonDefaultLanguage();
String control;
Message message;
// message has default language, first subject no language, second subject other language
control = XMLBuilder.create("message")
.a("from", "[email protected]/orchard")
.a("to", "[email protected]/balcony")
.a("id", "zid615d9")
.a("type", "chat")
.a("xml:lang", defaultLanguage)
.e("subject")
.t(defaultLanguage)
.up()
.e("subject")
.a("xml:lang", otherLanguage)
.t(otherLanguage)
.asString(outputProperties);
message = (Message) PacketParserUtils
.parseMessage(getParser(control));
assertEquals(defaultLanguage, message.getSubject());
assertEquals(otherLanguage, message.getSubject(otherLanguage));
assertEquals(2, message.getSubjects().size());
assertEquals(1, message.getSubjectLanguages().size());
assertTrue(message.getSubjectLanguages().contains(otherLanguage));
assertXMLEqual(control, message.toXML());
// message has default language, first subject no language, second subject default language
control = XMLBuilder.create("message")
.a("from", "[email protected]/orchard")
.a("to", "[email protected]/balcony")
.a("id", "zid615d9")
.a("type", "chat")
.a("xml:lang", defaultLanguage)
.e("subject")
.t(defaultLanguage)
.up()
.e("subject")
.a("xml:lang", defaultLanguage)
.t(defaultLanguage + "2")
.asString(outputProperties);
message = (Message) PacketParserUtils
.parseMessage(getParser(control));
assertEquals(defaultLanguage, message.getSubject());
assertEquals(defaultLanguage, message.getSubject(defaultLanguage));
assertEquals(1, message.getSubjects().size());
assertEquals(0, message.getSubjectLanguages().size());
assertXMLNotEqual(control, message.toXML());
// message has non-default language, first subject no language, second subject default language
control = XMLBuilder.create("message")
.a("from", "[email protected]/orchard")
.a("to", "[email protected]/balcony")
.a("id", "zid615d9")
.a("type", "chat")
.a("xml:lang", otherLanguage)
.e("subject")
.t(otherLanguage)
.up()
.e("subject")
.a("xml:lang", defaultLanguage)
.t(defaultLanguage)
.asString(outputProperties);
message = (Message) PacketParserUtils
.parseMessage(getParser(control));
assertEquals(otherLanguage, message.getSubject());
assertEquals(defaultLanguage, message.getSubject(defaultLanguage));
assertEquals(2, message.getSubjects().size());
assertEquals(1, message.getSubjectLanguages().size());
assertTrue(message.getSubjectLanguages().contains(defaultLanguage));
assertXMLEqual(control, message.toXML());
// message has no language, first subject no language, second subject default language
control = XMLBuilder.create("message")
.a("from", "[email protected]/orchard")
.a("to", "[email protected]/balcony")
.a("id", "zid615d9")
.a("type", "chat")
.e("subject")
.t(defaultLanguage)
.up()
.e("subject")
.a("xml:lang", defaultLanguage)
.t(defaultLanguage + "2")
.asString(outputProperties);
message = (Message) PacketParserUtils
.parseMessage(getParser(control));
assertEquals(defaultLanguage, message.getSubject());
assertEquals(defaultLanguage, message.getSubject(defaultLanguage));
assertEquals(1, message.getSubjects().size());
assertEquals(0, message.getSubjectLanguages().size());
assertXMLNotEqual(control, message.toXML());
// message has no language, first subject no language, second subject other language
control = XMLBuilder.create("message")
.a("from", "[email protected]/orchard")
.a("to", "[email protected]/balcony")
.a("id", "zid615d9")
.a("type", "chat")
.e("subject")
.t(defaultLanguage)
.up()
.e("subject")
.a("xml:lang", otherLanguage)
.t(otherLanguage)
.asString(outputProperties);
message = (Message) PacketParserUtils
.parseMessage(getParser(control));
assertEquals(defaultLanguage, message.getSubject());
assertEquals(defaultLanguage, message.getSubject(defaultLanguage));
assertEquals(otherLanguage, message.getSubject(otherLanguage));
assertEquals(2, message.getSubjects().size());
assertEquals(1, message.getSubjectLanguages().size());
assertXMLEqual(control, message.toXML());
// message has no language, first subject no language, second subject no language
control = XMLBuilder.create("message")
.a("from", "[email protected]/orchard")
.a("to", "[email protected]/balcony")
.a("id", "zid615d9")
.a("type", "chat")
.e("subject")
.t(defaultLanguage)
.up()
.e("subject")
.t(otherLanguage)
.asString(outputProperties);
message = (Message) PacketParserUtils
.parseMessage(getParser(control));
assertEquals(defaultLanguage, message.getSubject());
assertEquals(defaultLanguage, message.getSubject(defaultLanguage));
assertEquals(1, message.getSubjects().size());
assertEquals(0, message.getSubjectLanguages().size());
assertXMLNotEqual(control, message.toXML());
}
@Test
public void invalidMessageBodyContainingTagTest() throws Exception {
String control = XMLBuilder.create("message")
.a("from", "[email protected]/orchard")
.a("to", "[email protected]/balcony")
.a("id", "zid615d9")
.a("type", "chat")
.a("xml:lang", "en")
.e("body")
.a("xmlns", "http://www.w3.org/1999/xhtml")
.e("span")
.a("style", "font-weight: bold;")
- .t("Bad Message Body")
+ .t("Message Body")
.asString(outputProperties);
try {
Message message = (Message) PacketParserUtils.parseMessage(getParser(control));
String body = "<span style=\"font-weight: bold;\">"
- + "Bad Message Body</span>";
+ + "Message Body</span>";
assertEquals(body, message.getBody());
assertXMLNotEqual(control, message.toXML());
DetailedDiff diffs = new DetailedDiff(new Diff(control, message.toXML()));
// body has no namespace URI, span is escaped
assertEquals(4, diffs.getAllDifferences().size());
} catch(XmlPullParserException e) {
fail("No parser exception should be thrown" + e.getMessage());
}
}
@Test
public void invalidXMLInMessageBody() throws Exception {
String validControl = XMLBuilder.create("message")
.a("from", "[email protected]/orchard")
.a("to", "[email protected]/balcony")
.a("id", "zid615d9")
.a("type", "chat")
.a("xml:lang", "en")
.e("body")
.t("Good Message Body")
.asString(outputProperties);
String invalidControl = validControl.replace("Good Message Body", "Bad </span> Body");
try {
PacketParserUtils.parseMessage(getParser(invalidControl));
fail("Exception should be thrown");
} catch(XmlPullParserException e) {
// assertTrue(e.getMessage().contains("end tag name </span>"));
}
invalidControl = validControl.replace("Good Message Body", "Bad </body> Body");
try {
PacketParserUtils.parseMessage(getParser(invalidControl));
fail("Exception should be thrown");
} catch(XmlPullParserException e) {
// assertTrue(e.getMessage().contains("end tag name </body>"));
}
invalidControl = validControl.replace("Good Message Body", "Bad </message> Body");
try {
PacketParserUtils.parseMessage(getParser(invalidControl));
fail("Exception should be thrown");
} catch(XmlPullParserException e) {
// assertTrue(e.getMessage().contains("end tag name </message>"));
}
}
@Ignore
@Test
public void multipleMessageBodiesParsingTest() throws Exception {
String control = XMLBuilder.create("message")
.a("from", "[email protected]/orchard")
.a("to", "[email protected]/balcony")
.a("id", "zid615d9")
.a("type", "chat")
.a("xml:lang", "en")
.e("body")
.t("This is a test of the emergency broadcast system, 1.")
.up()
.e("body")
.a("xml:lang", "ru")
.t("This is a test of the emergency broadcast system, 2.")
.up()
.e("body")
.a("xml:lang", "sp")
.t("This is a test of the emergency broadcast system, 3.")
.asString(outputProperties);
Packet message = PacketParserUtils.parseMessage(getParser(control));
assertXMLEqual(control, message.toXML());
}
private XmlPullParser getParser(String control) throws XmlPullParserException, IOException {
XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser();
parser.setInput(new StringReader(control));
while(true) {
if(parser.next() == XmlPullParser.START_TAG
&& parser.getName().equals("message")) { break; }
}
return parser;
}
private String determineNonDefaultLanguage() {
String otherLanguage = "jp";
Locale[] availableLocales = Locale.getAvailableLocales();
for (int i = 0; i < availableLocales.length; i++) {
if (availableLocales[i] != Locale.getDefault()) {
otherLanguage = availableLocales[i].getLanguage().toLowerCase();
break;
}
}
return otherLanguage;
}
}
| false | false | null | null |
diff --git a/org.emftext.test.atl/src/org/emftext/runtime/ATLTransformationTest.java b/org.emftext.test.atl/src/org/emftext/runtime/ATLTransformationTest.java
index ce99e6984..16336198e 100644
--- a/org.emftext.test.atl/src/org/emftext/runtime/ATLTransformationTest.java
+++ b/org.emftext.test.atl/src/org/emftext/runtime/ATLTransformationTest.java
@@ -1,61 +1,61 @@
package org.emftext.runtime;
import static org.emftext.test.ConcreteSyntaxTestHelper.registerResourceFactories;
import java.io.IOException;
import junit.framework.TestCase;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.emftext.language.ecore.resource.text.mopp.TextEcoreResourceFactory;
import org.emftext.runtime.atl.ATLTransformationPostProcessor;
import org.emftext.sdk.concretesyntax.ConcreteSyntax;
-import org.emftext.sdk.concretesyntax.resource.cs.CsResourceFactory;
+import org.emftext.sdk.concretesyntax.resource.cs.mopp.CsResourceFactory;
import org.junit.Before;
public class ATLTransformationTest extends TestCase {
@Before
public void setUp() {
registerResourceFactories();
Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put(
"ecore", new TextEcoreResourceFactory());
Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put("cs",
new CsResourceFactory());
}
public void testTransformationResult() throws Exception {
String testfile = "platform:/resource/org.emftext.test.atl/model/example.cs";
loadResourceWithProcessor(testfile);
String outfile = "platform:/resource/org.emftext.test.atl/model/example.out.cs";
Resource outResource = loadResource(outfile);
assertEquals(1, outResource.getContents().size());
assertEquals("wasHere", ((ConcreteSyntax) outResource.getContents().get(0) ).getName());
}
private Resource loadResource(String grammar) throws IOException {
URI fileUri = URI.createURI(grammar);
ResourceSet rs = new ResourceSetImpl();
Resource csResource = rs.getResource(fileUri, true);
return csResource;
}
private Resource loadResourceWithProcessor(String grammar) throws IOException {
URI fileUri = URI.createURI(grammar);
ResourceSet rs = new ResourceSetImpl();
ATLTransformationPostProcessor transformationPostProcessor = new TestTransformationPostProcessor();
rs.getLoadOptions().putAll(transformationPostProcessor.getOptions());
Resource csResource = rs.getResource(fileUri, true);
return csResource;
}
}
| true | false | null | null |
diff --git a/eclipse/plugins/net.sf.orcc.cal/src/net/sf/orcc/frontend/FrontendCli.java b/eclipse/plugins/net.sf.orcc.cal/src/net/sf/orcc/frontend/FrontendCli.java
index 06a333e4a..ee605b5aa 100644
--- a/eclipse/plugins/net.sf.orcc.cal/src/net/sf/orcc/frontend/FrontendCli.java
+++ b/eclipse/plugins/net.sf.orcc.cal/src/net/sf/orcc/frontend/FrontendCli.java
@@ -1,374 +1,376 @@
/*
* Copyright (c) 2009-2010, IETR/INSA of Rennes
* 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 IETR/INSA of Rennes nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
* WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
package net.sf.orcc.frontend;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.orcc.OrccException;
import net.sf.orcc.cal.CalStandaloneSetup;
import net.sf.orcc.cal.cal.AstEntity;
import net.sf.orcc.cal.cal.CalPackage;
import net.sf.orcc.cal.cal.Import;
import net.sf.orcc.cal.util.Util;
import net.sf.orcc.util.OrccUtil;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceDescription;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.Resource.Diagnostic;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.eclipse.xtext.diagnostics.Severity;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.util.CancelIndicator;
import org.eclipse.xtext.validation.CheckMode;
import org.eclipse.xtext.validation.IResourceValidator;
import org.eclipse.xtext.validation.Issue;
/**
* This class defines an RVC-CAL command line version of the frontend. It should
* be used with the folowing command-line, when all plugins are loaded by
* eclipse :
*
* <pre>
* eclipse -application net.sf.orcc.cal.cli -data <workspacePath> <projectName>
* </pre>
*
* @author Matthieu Wipliez
* @author Antoine Lorence
*
*/
public class FrontendCli implements IApplication {
private List<IProject> orderedProjects;
private List<IProject> unorderedProjects;
private ResourceSet emfResourceSet;
private IWorkspace workspace;
private boolean isAutoBuildActivated;
public FrontendCli() {
orderedProjects = new ArrayList<IProject>();
unorderedProjects = new ArrayList<IProject>();
workspace = ResourcesPlugin.getWorkspace();
isAutoBuildActivated = false;
CalStandaloneSetup.doSetup();
// Get the resource set used by Frontend
emfResourceSet = Frontend.instance.getResourceSet();
// Register the package to ensure it is available during loading.
emfResourceSet.getPackageRegistry().put(CalPackage.eNS_URI,
CalPackage.eINSTANCE);
}
private void disableAutoBuild() throws CoreException {
IWorkspaceDescription desc = workspace.getDescription();
if (desc.isAutoBuilding()) {
isAutoBuildActivated = true;
desc.setAutoBuilding(false);
workspace.setDescription(desc);
}
}
private void restoreAutoBuild() throws CoreException {
if (isAutoBuildActivated) {
IWorkspaceDescription desc = workspace.getDescription();
desc.setAutoBuilding(true);
workspace.setDescription(desc);
}
}
/**
* Control if resource has errors
*
* @param resource
* to check
* @return true if errors were found in resource
*/
private boolean hasErrors(Resource resource) {
boolean hasErrors = false;
// contains linking errors
List<Diagnostic> errors = resource.getErrors();
if (!errors.isEmpty()) {
for (Diagnostic error : errors) {
System.err.println(error);
}
hasErrors = true;
}
// validates (unique names and CAL validator)
IResourceValidator v = ((XtextResource) resource)
.getResourceServiceProvider().getResourceValidator();
List<Issue> issues = v.validate(resource, CheckMode.ALL,
CancelIndicator.NullImpl);
for (Issue issue : issues) {
if (issue.getSeverity() == Severity.ERROR) {
System.err.println(issue.toString());
hasErrors = true;
} else {
System.out.println(issue.toString());
}
}
return hasErrors;
}
/**
* Get all actors and units files from container (IProject or IFolder) and
* all its subfolders.
*
* @param container
* instance of IProject or IFolder to search in
* @return list of *.cal files from container
* @throws OrccException
*/
private List<IFile> getCalFiles(IContainer container) throws OrccException {
List<IFile> actors = new ArrayList<IFile>();
IResource[] members = null;
try {
members = container.members();
for (IResource resource : members) {
+
if (resource.getType() == IResource.FOLDER) {
actors.addAll(getCalFiles((IFolder) resource));
} else if (resource.getType() == IResource.FILE
+ && resource.getFileExtension() != null
&& resource.getFileExtension().equals("cal")) {
actors.add((IFile) resource);
}
}
} catch (CoreException e) {
throw new OrccException("Unable to get members of IContainer "
+ container.getName());
}
return actors;
}
/**
* Add currentProject dependencies to an orderedList of projects to compile,
* then add currentProject itself. This method should not run in infinite
* loop if projects dependencies are cycling.
*
* @param currentProject
* @throws OrccException
*/
private void storeProjectToCompile(IProject currentProject)
throws OrccException {
unorderedProjects.add(currentProject);
try {
IProject[] refProjects = currentProject.getReferencedProjects();
for (IProject p : refProjects) {
if (!unorderedProjects.contains(p)) {
storeProjectToCompile(p);
}
}
} catch (CoreException e) {
throw new OrccException("Unable to get referenced projects"
+ currentProject.getName());
}
if (!orderedProjects.contains(currentProject)) {
orderedProjects.add(currentProject);
}
}
/**
* Set projectName as current project and store dependencies to compile
* before current project
*
* @param projectName
* @throws OrccException
*/
private void setProject(String projectName)
throws OrccException {
IProject currentProject = workspace.getRoot().getProject(projectName);
if (currentProject != null) {
storeProjectToCompile(currentProject);
} else {
throw new OrccException("Impossible to find project named "
+ projectName);
}
}
/**
* Write IR files of the project p under the default folder
* <project_folder>/bin
*
* @param p
* project to compile
* @throws OrccException
*/
private void writeProjectIR(IProject p) throws OrccException {
Frontend.instance.setOutputFolder(OrccUtil.getOutputFolder(p));
List<IFile> fileList = getCalFiles(p);
Map<String, Resource> resourceList = new HashMap<String, Resource>();
ArrayList<String> orderedUnits = new ArrayList<String>();
System.out.println("-----------------------------");
System.out.println("Building project " + p.getName());
System.out.println("-----------------------------");
// Save list of units qualified names and map of qualified name /
// entities
for (IFile file : fileList) {
URI uri = URI.createPlatformResourceURI(file.getFullPath()
.toString(), true);
Resource resource = emfResourceSet.getResource(uri, true);
AstEntity entity = (AstEntity) resource.getContents().get(0);
String qName = Util.getQualifiedName(entity);
resourceList.put(qName, resource);
if (entity.getUnit() != null) {
orderedUnits.add(qName);
}
}
// Reorder unit list
ArrayList<String> tempUnitList = new ArrayList<String>();
tempUnitList.addAll(orderedUnits);
for (String curUnitQName : tempUnitList) {
EList<Import> imports = ((AstEntity) resourceList.get(curUnitQName)
.getContents().get(0)).getImports();
for (Import i : imports) {
String importedNamespace = i.getImportedNamespace();
String importedQName = importedNamespace.substring(0,
importedNamespace.lastIndexOf('.'));
if (orderedUnits.contains(importedQName)) {
orderedUnits.remove(importedQName);
orderedUnits.add(orderedUnits.indexOf(curUnitQName),
importedQName);
}
}
}
// Build units in right order
for (String unitQName : orderedUnits) {
System.out.println("Unit : " + unitQName);
Resource resource = resourceList.get(unitQName);
if (!hasErrors(resource)) {
Frontend.getEntity((AstEntity) resource.getContents().get(0));
}
resourceList.remove(unitQName);
}
// Build actors
for (String actorQName : resourceList.keySet()) {
System.out.println("Actor : " + actorQName);
Resource resource = resourceList.get(actorQName);
if (!hasErrors(resource)) {
Frontend.getEntity((AstEntity) resource.getContents().get(0));
}
}
}
@Override
public Object start(IApplicationContext context) {
Map<?, ?> map = context.getArguments();
String[] args = (String[]) map
.get(IApplicationContext.APPLICATION_ARGS);
String projectName = "";
if (args.length == 1) {
projectName = args[0];
} else {
- System.err.println("Please pass the project name in argument");
+ System.err.println("Please pass the project name in argument.");
return IApplication.EXIT_RELAUNCH;
}
try {
// IMPORTANT : Disable auto-building, because it requires xtext UI
// plugins to be launched
disableAutoBuild();
System.out.print("Setup " + projectName + " as working project ");
setProject(projectName);
System.out.println("Done");
for (IProject p : orderedProjects) {
writeProjectIR(p);
}
System.out.println("Done");
// If needed, restore autoBuild config state in eclipse config file
restoreAutoBuild();
} catch (OrccException oe) {
System.err.println(oe.getMessage());
} catch (CoreException ce) {
System.err.println(ce.getMessage());
} finally {
try {
restoreAutoBuild();
} catch (CoreException e) {
System.err.println(e.getMessage());
}
}
return IApplication.EXIT_OK;
}
@Override
public void stop() {
}
}
| false | false | null | null |
diff --git a/src.lib/edu/rice/batchsig/splice/OneTree.java b/src.lib/edu/rice/batchsig/splice/OneTree.java
index bfa18e6..bd879f6 100644
--- a/src.lib/edu/rice/batchsig/splice/OneTree.java
+++ b/src.lib/edu/rice/batchsig/splice/OneTree.java
@@ -1,293 +1,294 @@
package edu.rice.batchsig.splice;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import com.google.protobuf.ByteString;
import edu.rice.batchsig.IMessage;
import edu.rice.batchsig.Verifier;
+import edu.rice.batchsig.VerifyHisttreeCommon;
import edu.rice.historytree.HistoryTree;
/** Represent all of the message from one history tree instance */
public class OneTree {
int size = 0;
public int size() {
return size;
}
final private VerifyHisttreeLazily verifier;
/** Map from an integer version number to the message at that version number */
HashMap<Integer,IMessage> bundles = new LinkedHashMap<Integer,IMessage>(1,.75f,false);
/** Cache of root hashes for each unvalidated bundle.
* When we verify a splice, we need to take the predecessor's bundle agg() and compare it to aggV(pred.version).
* Rather than rebuild the pred's pruned tree, or cache the whole thing, just cache the parts we need, the agg().
* */
HashMap<Integer,ByteString> roothashes = new HashMap<Integer,ByteString>();
/** This hashmap finds the message signatures we need to verify to validate a given bundle.
*
* When we find the 'root' node of a dependency tree, that will be an exlempar, but not correspond to a 'real' message. This will.
*
*/
HashMap<Integer,IMessage> validators = new HashMap<Integer,IMessage>();
/**
* Invariant; The dag contains nodes for each message and the version
* numbers of the splicepoints seen for that bundle.
*
* If an edge is in the dag and both bundles have been seen (are in the
* bundles hash), then the splice has been VERIFIED.
*
* If an edge is in the dag, but either the from or to bundles in the
* dag are *NOT* in the bundles hash, then the splice is provisional
* and may not exist. We wait until the peer message arrives, verify the
* splice, and keep the edge if the splice verifies, or remove the edge
* if the splice fails.
*
* */
final private Dag<Integer> dag = new Dag<Integer>();
final private Object author;
final private long treeid;
public Object getAuthor() {
return author;
}
public long getTreeid() {
return treeid;
}
Dag<Integer>.DagNode getNode(IMessage m) {
Integer key = m.getSignatureBlob().getLeaf();
return dag.makeOrGet(key);
}
public OneTree(VerifyHisttreeLazily verifier, Object object, long l) {
this.author = object;
this.treeid = l;
this.verifier = verifier;
}
private void failMessage(IMessage m) {
m.signatureValidity(true);
size--;
}
/*
* Errors: See this messages bundle before with a different hash. Verify immediately.
*
*
*
*
*
*/
/* Each node in the dag corresponds to a set of bundles. All that end in the same epoch. */
void addMessage(IMessage m) {
//System.out.println("\nAdding message "+m);
size++;
Integer key = m.getSignatureBlob().getLeaf();
Integer bundlekey = m.getSignatureBlob().getTree().getVersion();
HistoryTree<byte[],byte[]> tree = VerifyHisttreeLazily.parseHistoryTree(m);
ByteString agg = ByteString.copyFrom(tree.agg());
// First, see if this message is well-formed in the bundle? Yes. It is.
if (!Verifier.checkLeaf(m,tree)) {
System.out.println("Broken proof that doesn't validate message in proof.");
failMessage(m);
return;
}
// First, have we seen this ending bundle before?
if (validators.containsKey(bundlekey)) {
// We got a bundle already. Does it have the same agg?
if (!roothashes.get(bundlekey).equals(agg)) {
// PROBLEM: Have an inconsistent bundle already.
// TODO: Can't handle these at all. Only solution: Verify it immediately.
throw new Error("TODO");
}
//System.out.println("Adding to existing bundle");
}
validators.put(bundlekey,m);
// At this point, we know that any keys in this bundle all have the same ending hash, ergo,
// the same contents. We don't have to worry about inconsistency anymore, and can just store the data, except for validating splices.
// Now, build an edge in the dag from the integer representing the bundle to this message.
Dag<Integer>.DagNode node = dag.makeOrGet(key);
Dag<Integer>.DagNode bundlenode = dag.makeOrGet(bundlekey);
// Add a dependency edge for the bundle.
if (!node.get().equals(bundlenode.get()))
dag.addEdge(bundlenode, node);
// And put the message in.
bundles.put(key,m);
// PART 1: See if we've seen later bundles we might splice into.
// This case should be rare and only occur when bundles arrive out-of-order.
for (Dag<Integer>.DagNode succ : bundlenode.getParents()) {
// For each later message in the dag that provisionally splices this message.
//System.out.println("Looking at later bundles");
Integer succi = succ.get();
IMessage succm = bundles.get(succi);
if (succm == null)
throw new Error("Algorithm bug.");
// Time to verify the splice is OK.
HistoryTree<byte[],byte[]> succtree = VerifyHisttreeLazily.parseHistoryTree(succm);
if (Arrays.equals(succtree.aggV(bundlekey.intValue()),tree.agg())) {
System.out.println("Unusual splice circumstance -- success");
dag.addEdge(succ,bundlenode);
} else {
// Splice fails. Remove the edge.
System.out.println("Unusual splice circumstance -- failure & removal");
}
}
// PART 2: See which prior bundles we splice into.
for (Integer predi : m.getSignatureBlob().getSpliceHintList()) {
ByteString aggv = ByteString.copyFrom(tree.aggV(predi.intValue()));
//System.out.format("Handling splicehint %d with hash %d\n",predi,aggv.hashCode());
// For each splicepoint to prior bundles in this message,
IMessage predm = validators.get(predi);
Dag<Integer>.DagNode prednode = dag.makeOrGet(predi);
// Have we seen the prior message?
if (predm == null) {
//System.out.println("No priors found, but adding edge anyways.");
// Nope. Add the node to the dag. Add an edge to that child; it'll be provisional
dag.addEdge(node,prednode);
} else {
//System.out.format("Agg(%d)=%d of pred\n",predm.getSignatureBlob().getTree().getVersion(),roothashes.get(predi).hashCode());
// We have seen that message. We need to check the splice.
if (aggv.equals(roothashes.get(predi))) {
//System.out.println("Found a prior. Verified the splice!");
dag.addEdge(node,prednode);
} else {
// Splice fails. Remove the edge.
//System.out.println("Found a prior, but splice failed");
prednode = dag.makeOrGet(predi);
}
}
}
//System.out.format("Stored roothash at (%d) of %d of pred\n",bundlekey,agg.hashCode());
roothashes.put(bundlekey,agg);
bundles.put(key, m);
//System.out.println("Finished handling for message");
}
/** Called to remove a real message from all tracking */
private void remove(IMessage m) {
int index = m.getSignatureBlob().getLeaf();
remove(index);
}
/** Called to remove a message index from all tracking */
private void remove(int index) {
if (bundles.remove(index)!= null)
size--;
validators.remove(index);
roothashes.remove(index);
}
/** Force the oldest thing here, return true if somethign was forced */
boolean forceOldest() {
System.out.format("Forcing oldest message (OneTree)\n");
Iterator<Integer> i = bundles.keySet().iterator();
//System.out.format("%d == %d?\n",size,bundles.size());
if (!i.hasNext()) {
if (size != 0)
throw new Error("Size should be zero");
return false;
}
IMessage m = bundles.get(i.next());
m.resetCreationTimeNull();
forceMessage(m);
return true;
}
void forceMessage(IMessage m) {
//System.out.format("\n>>>>> Forcing a message %d to %s\n",m.getSignatureBlob().getLeaf(),getName());
if (!bundles.containsKey(m.getSignatureBlob().getLeaf())) {
System.out.println("Forcing message that doesn't exist:"+m.toString()); // Should trigger occasionally.
throw new Error("WARN");
//return;
}
Dag<Integer>.DagNode node = getNode(m);
// Step one: Find a root.
Dag<Integer>.Path rootPath = dag.rootPath(node);
// Step two, until we find a root whose signature verifies.
while (true) {
//System.out.println("WhileLoop at rootPath ="+rootPath);
Dag<Integer>.DagNode root = rootPath.root();
Integer rooti = root.get();
// An incoming message that nominally validates the root bundle (may be more than one)
IMessage rootm = validators.get(rooti);
//System.out.format("Got root at %d about to see if it verifies %s\n",rooti,rootm);
- HistoryTree<byte[],byte[]> roottree = verifier.parseHistoryTree(rootm);
+ HistoryTree<byte[],byte[]> roottree = VerifyHisttreeCommon.parseHistoryTree(rootm);
// Verify the root's public key signature.
if (verifier.verifyHistoryRoot(rootm,roottree)) {
//System.out.println("Verified the root's signature - SUCCESS. It is valid");
// Success!
// Now traverse *all* descendents and mark them as good.
Collection<Dag<Integer>.DagNode> descendents = dag.getAllChildren(root);
for (Dag<Integer>.DagNode i : descendents) {
//System.out.println("Traversing descendent to mark as valid:"+i.get());
//Integer desci = i.get();
IMessage descm = bundles.get(i.get());
if (descm != null) {
// TODO: Cache the spliced predecessor hashes from this node as being valid?
//System.out.println("... and marking it as good!");
// This message is not provisional. It is valid.
descm.signatureValidity(true);
// Remove the message from further tracking.
remove(descm);
}
// Remove any vestiges of the node.
remove(i.get());
i.remove();
}
//System.out.format("<<<<<< Done with handling force of %d to %s\n",m.getSignatureBlob().getLeaf(),getName());
return;
} else {
System.out.println("Failed the root's signature");
rootm.signatureValidity(false);
remove(rootm);
}
System.out.println("Got a problem, need to try the next root");
// Failure. Try the next root.
rootPath.next();
}
}
public void forceAll() {
//System.out.format("Forcing all bundles in OneTree\n");
while (!bundles.isEmpty()) {
IMessage m = bundles.entrySet().iterator().next().getValue();
m.resetCreationTimeNull();
forceMessage(m);
}
}
public boolean isEmpty() {
return bundles.isEmpty();
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/main/java/com/intalio/bpmn2/impl/Bpmn2JsonUnmarshaller.java b/src/main/java/com/intalio/bpmn2/impl/Bpmn2JsonUnmarshaller.java
index 62068e2d..4a7aeb28 100644
--- a/src/main/java/com/intalio/bpmn2/impl/Bpmn2JsonUnmarshaller.java
+++ b/src/main/java/com/intalio/bpmn2/impl/Bpmn2JsonUnmarshaller.java
@@ -1,3331 +1,3334 @@
/***************************************
* Copyright (c) Intalio, Inc 2010
*
* 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.intalio.bpmn2.impl;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.eclipse.bpmn2.Activity;
import org.eclipse.bpmn2.AdHocOrdering;
import org.eclipse.bpmn2.AdHocSubProcess;
import org.eclipse.bpmn2.Artifact;
import org.eclipse.bpmn2.Assignment;
import org.eclipse.bpmn2.Association;
import org.eclipse.bpmn2.Auditing;
import org.eclipse.bpmn2.BaseElement;
import org.eclipse.bpmn2.BoundaryEvent;
import org.eclipse.bpmn2.Bpmn2Factory;
import org.eclipse.bpmn2.BusinessRuleTask;
import org.eclipse.bpmn2.CallActivity;
import org.eclipse.bpmn2.CatchEvent;
import org.eclipse.bpmn2.Category;
import org.eclipse.bpmn2.CategoryValue;
import org.eclipse.bpmn2.CompensateEventDefinition;
import org.eclipse.bpmn2.ConditionalEventDefinition;
import org.eclipse.bpmn2.DataInput;
import org.eclipse.bpmn2.DataInputAssociation;
import org.eclipse.bpmn2.DataObject;
import org.eclipse.bpmn2.DataOutput;
import org.eclipse.bpmn2.DataOutputAssociation;
import org.eclipse.bpmn2.DataStore;
import org.eclipse.bpmn2.Definitions;
import org.eclipse.bpmn2.Documentation;
import org.eclipse.bpmn2.EndEvent;
import org.eclipse.bpmn2.Error;
import org.eclipse.bpmn2.ErrorEventDefinition;
import org.eclipse.bpmn2.Escalation;
import org.eclipse.bpmn2.EscalationEventDefinition;
import org.eclipse.bpmn2.Event;
import org.eclipse.bpmn2.EventDefinition;
import org.eclipse.bpmn2.ExtensionAttributeValue;
import org.eclipse.bpmn2.FlowElement;
import org.eclipse.bpmn2.FlowElementsContainer;
import org.eclipse.bpmn2.FlowNode;
import org.eclipse.bpmn2.FormalExpression;
import org.eclipse.bpmn2.Gateway;
import org.eclipse.bpmn2.GatewayDirection;
import org.eclipse.bpmn2.GlobalTask;
import org.eclipse.bpmn2.Group;
import org.eclipse.bpmn2.Import;
import org.eclipse.bpmn2.InclusiveGateway;
import org.eclipse.bpmn2.InputOutputSpecification;
import org.eclipse.bpmn2.InputSet;
import org.eclipse.bpmn2.Interface;
import org.eclipse.bpmn2.ItemAwareElement;
import org.eclipse.bpmn2.ItemDefinition;
import org.eclipse.bpmn2.Lane;
import org.eclipse.bpmn2.LaneSet;
import org.eclipse.bpmn2.Message;
import org.eclipse.bpmn2.MessageEventDefinition;
import org.eclipse.bpmn2.Monitoring;
import org.eclipse.bpmn2.MultiInstanceLoopCharacteristics;
import org.eclipse.bpmn2.Operation;
import org.eclipse.bpmn2.OutputSet;
import org.eclipse.bpmn2.PotentialOwner;
import org.eclipse.bpmn2.Process;
import org.eclipse.bpmn2.ProcessType;
import org.eclipse.bpmn2.Property;
import org.eclipse.bpmn2.ReceiveTask;
import org.eclipse.bpmn2.ResourceAssignmentExpression;
import org.eclipse.bpmn2.RootElement;
import org.eclipse.bpmn2.ScriptTask;
import org.eclipse.bpmn2.SendTask;
import org.eclipse.bpmn2.SequenceFlow;
import org.eclipse.bpmn2.ServiceTask;
import org.eclipse.bpmn2.Signal;
import org.eclipse.bpmn2.SignalEventDefinition;
import org.eclipse.bpmn2.StartEvent;
import org.eclipse.bpmn2.SubProcess;
import org.eclipse.bpmn2.Task;
import org.eclipse.bpmn2.TextAnnotation;
import org.eclipse.bpmn2.ThrowEvent;
import org.eclipse.bpmn2.TimerEventDefinition;
import org.eclipse.bpmn2.UserTask;
import org.eclipse.bpmn2.di.BPMNDiagram;
import org.eclipse.bpmn2.di.BPMNEdge;
import org.eclipse.bpmn2.di.BPMNPlane;
import org.eclipse.bpmn2.di.BPMNShape;
import org.eclipse.bpmn2.di.BpmnDiFactory;
import org.eclipse.bpmn2.util.Bpmn2Resource;
import org.eclipse.dd.dc.Bounds;
import org.eclipse.dd.dc.DcFactory;
import org.eclipse.dd.dc.Point;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature.Internal;
import org.eclipse.emf.ecore.impl.EAttributeImpl;
import org.eclipse.emf.ecore.impl.EStructuralFeatureImpl;
import org.eclipse.emf.ecore.impl.EStructuralFeatureImpl.SimpleFeatureMapEntry;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.util.ExtendedMetaData;
import org.eclipse.emf.ecore.util.FeatureMap;
import org.jboss.drools.DroolsFactory;
import org.jboss.drools.DroolsPackage;
import org.jboss.drools.GlobalType;
import org.jboss.drools.ImportType;
import org.jboss.drools.OnEntryScriptType;
import org.jboss.drools.OnExitScriptType;
import org.jboss.drools.impl.DroolsPackageImpl;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleReference;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import com.intalio.bpmn2.BpmnMarshallerHelper;
import com.intalio.bpmn2.resource.JBPMBpmn2ResourceFactoryImpl;
/**
* @author Antoine Toulme
* @author Tihomir Surdilovic
*
* an unmarshaller to transform JSON into BPMN 2.0 elements.
*
*/
public class Bpmn2JsonUnmarshaller {
public static final String defaultBgColor = "#b1c2d6";
// a list of the objects created, kept in memory with their original id for
// fast lookup.
private Map<Object, String> _objMap = new HashMap<Object, String>();
private Map<String, Object> _idMap = new HashMap<String, Object>();
// the collection of outgoing ids.
// we reconnect the edges with the shapes as a last step of the construction
// of our graph from json, as we miss elements before.
private Map<Object, List<String>> _outgoingFlows = new HashMap<Object, List<String>>();
private Set<String> _sequenceFlowTargets = new HashSet<String>();
private Map<String, Bounds> _bounds = new HashMap<String, Bounds>();
private Map<String, List<Point>> _dockers = new HashMap<String, List<Point>>();
private List<Lane> _lanes = new ArrayList<Lane>();
private List<Artifact> _artifacts = new ArrayList<Artifact>();
private Map<String, ItemDefinition> _subprocessItemDefs = new HashMap<String, ItemDefinition>();
private List<BpmnMarshallerHelper> _helpers;
private Bpmn2Resource _currentResource;
public Bpmn2JsonUnmarshaller() {
_helpers = new ArrayList<BpmnMarshallerHelper>();
DroolsPackageImpl.init();
// load the helpers to place them in field
if (getClass().getClassLoader() instanceof BundleReference) {
BundleContext context = ((BundleReference) getClass().getClassLoader()).
getBundle().getBundleContext();
try {
ServiceReference[] refs = context.getAllServiceReferences(
BpmnMarshallerHelper.class.getName(), null);
for (ServiceReference ref : refs) {
BpmnMarshallerHelper helper = (BpmnMarshallerHelper) context.getService(ref);
_helpers.add(helper);
}
} catch (InvalidSyntaxException e) {
}
}
}
public Bpmn2Resource unmarshall(String json, String preProcessingData) throws JsonParseException, IOException {
return unmarshall(new JsonFactory().createJsonParser(json), preProcessingData);
}
public Bpmn2Resource unmarshall(File file, String preProcessingData) throws JsonParseException, IOException {
return unmarshall(new JsonFactory().createJsonParser(file), preProcessingData);
}
/**
* Start unmarshalling using the parser.
* @param parser
* @return the root element of a bpmn2 document.
* @throws JsonParseException
* @throws IOException
*/
private Bpmn2Resource unmarshall(JsonParser parser, String preProcessingData) throws JsonParseException, IOException {
try {
parser.nextToken(); // open the object
ResourceSet rSet = new ResourceSetImpl();
rSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("bpmn2",
new JBPMBpmn2ResourceFactoryImpl());
Bpmn2Resource bpmn2 = (Bpmn2Resource) rSet.createResource(URI.createURI("virtual.bpmn2"));
rSet.getResources().add(bpmn2);
_currentResource = bpmn2;
// do the unmarshalling now:
Definitions def = (Definitions) unmarshallItem(parser, preProcessingData);
revisitServiceTasks(def);
revisitMessages(def);
revisitCatchEvents(def);
revisitThrowEvents(def);
revisitLanes(def);
revisitSubProcessItemDefs(def);
revisitArtifacts(def);
revisitGroups(def);
revisitTaskAssociations(def);
revisitSendReceiveTasks(def);
reconnectFlows();
revisitGateways(def);
revisitCatchEventsConvertToBoundary(def);
revisitDataObjects(def);
createDiagram(def);
updateIDs(def);
// return def;
_currentResource.getContents().add(def);
return _currentResource;
} finally {
parser.close();
_objMap.clear();
_idMap.clear();
_outgoingFlows.clear();
_sequenceFlowTargets.clear();
_bounds.clear();
_currentResource = null;
}
}
public void revisitSubProcessItemDefs(Definitions def) {
Iterator<String> iter = _subprocessItemDefs.keySet().iterator();
while(iter.hasNext()) {
String key = iter.next();
def.getRootElements().add(_subprocessItemDefs.get(key));
}
_subprocessItemDefs.clear();
}
public void updateIDs(Definitions def) {
// data object id update
List<RootElement> rootElements = def.getRootElements();
for(RootElement root : rootElements) {
if(root instanceof Process) {
Process process = (Process) root;
List<FlowElement> flowElements = process.getFlowElements();
for(FlowElement fe : flowElements) {
if(fe instanceof DataObject) {
DataObject da = (DataObject) fe;
if(da.getName() != null) {
da.setId(da.getName());
}
}
}
}
}
}
public void revisitDataObjects(Definitions def) {
List<RootElement> rootElements = def.getRootElements();
List<ItemDefinition> itemDefinitionsToAdd = new ArrayList<ItemDefinition>();
for(RootElement root : rootElements) {
if(root instanceof Process) {
Process process = (Process) root;
List<FlowElement> flowElements = process.getFlowElements();
for(FlowElement fe : flowElements) {
if(fe instanceof DataObject) {
DataObject da = (DataObject) fe;
ItemDefinition itemdef = Bpmn2Factory.eINSTANCE.createItemDefinition();
itemdef.setId("_" + da.getId() + "Item");
Iterator<FeatureMap.Entry> iter = da.getAnyAttribute().iterator();
while(iter.hasNext()) {
FeatureMap.Entry entry = iter.next();
if(entry.getEStructuralFeature().getName().equals("datype")) {
- itemdef.setStructureRef((String) entry.getValue());
+ String typeValue = (String) entry.getValue();
+ if(typeValue != null && !typeValue.equals("None")) {
+ itemdef.setStructureRef((String) entry.getValue());
+ }
}
}
da.setItemSubjectRef(itemdef);
itemDefinitionsToAdd.add(itemdef);
}
}
}
}
for(ItemDefinition itemDef : itemDefinitionsToAdd) {
def.getRootElements().add(itemDef);
}
for(RootElement root : rootElements) {
if(root instanceof Process) {
Process process = (Process) root;
List<Artifact> artifactElements = process.getArtifacts();
for(Artifact af : artifactElements) {
if(af instanceof Association) {
Association as = (Association) af;
if(as.getSourceRef() != null && as.getSourceRef() instanceof DataObject
&& as.getTargetRef() != null && (as.getTargetRef() instanceof Task || as.getTargetRef() instanceof ThrowEvent)) {
DataObject da = (DataObject) as.getSourceRef();
if(as.getTargetRef() instanceof Task) {
Task task = (Task) as.getTargetRef();
if(task.getIoSpecification() == null) {
InputOutputSpecification iospec = Bpmn2Factory.eINSTANCE.createInputOutputSpecification();
task.setIoSpecification(iospec);
}
if(task.getIoSpecification().getInputSets() == null || task.getIoSpecification().getInputSets().size() < 1) {
InputSet inset = Bpmn2Factory.eINSTANCE.createInputSet();
task.getIoSpecification().getInputSets().add(inset);
}
InputSet inSet = task.getIoSpecification().getInputSets().get(0);
boolean foundDataInput = false;
for(DataInput dataInput : inSet.getDataInputRefs()) {
if(dataInput.getId().equals(task.getId() + "_" + da.getId() + "Input")) {
foundDataInput = true;
}
}
if(!foundDataInput) {
DataInput d = Bpmn2Factory.eINSTANCE.createDataInput();
d.setId(task.getId() + "_" + da.getId() + "Input");
d.setName(da.getId() + "Input");
task.getIoSpecification().getDataInputs().add(d);
task.getIoSpecification().getInputSets().get(0).getDataInputRefs().add(d);
DataInputAssociation dia = Bpmn2Factory.eINSTANCE.createDataInputAssociation();
dia.setTargetRef(d);
dia.getSourceRef().add(da);
task.getDataInputAssociations().add(dia);
}
} else if(as.getTargetRef() instanceof ThrowEvent) {
ThrowEvent te = (ThrowEvent) as.getTargetRef();
// update throw event data input and add data input association
boolean foundDataInput = false;
List<DataInput> dataInputs = te.getDataInputs();
for(DataInput din : dataInputs) {
if(din.getId().equals(te.getId() + "_" + da.getId() + "Input")) {
foundDataInput = true;
}
}
if(!foundDataInput) {
DataInput datain = Bpmn2Factory.eINSTANCE.createDataInput();
datain.setId(te.getId() + "_" + da.getId() + "Input");
datain.setName(da.getId() + "Input");
te.getDataInputs().add(datain);
if(te.getInputSet() == null) {
InputSet inset = Bpmn2Factory.eINSTANCE.createInputSet();
te.setInputSet(inset);
}
te.getInputSet().getDataInputRefs().add(datain);
DataInputAssociation dia = Bpmn2Factory.eINSTANCE.createDataInputAssociation();
dia.setTargetRef(datain);
dia.getSourceRef().add(da);
te.getDataInputAssociation().add(dia);
}
}
}
if(as.getTargetRef() != null && as.getTargetRef() instanceof DataObject
&& as.getSourceRef() != null && (as.getSourceRef() instanceof Task || as.getSourceRef() instanceof CatchEvent)) {
DataObject da = (DataObject) as.getTargetRef();
if(as.getSourceRef() instanceof Task) {
Task task = (Task) as.getSourceRef();
if(task.getIoSpecification() == null) {
InputOutputSpecification iospec = Bpmn2Factory.eINSTANCE.createInputOutputSpecification();
task.setIoSpecification(iospec);
}
if(task.getIoSpecification().getOutputSets() == null || task.getIoSpecification().getOutputSets().size() < 1) {
OutputSet outSet = Bpmn2Factory.eINSTANCE.createOutputSet();
task.getIoSpecification().getOutputSets().add(outSet);
}
boolean foundDataOutput = false;
OutputSet outSet = task.getIoSpecification().getOutputSets().get(0);
for(DataOutput dataOut : outSet.getDataOutputRefs()) {
if(dataOut.getId().equals(task.getId() + "_" + da.getId() + "Output")) {
foundDataOutput = true;
}
}
if(!foundDataOutput) {
DataOutput d = Bpmn2Factory.eINSTANCE.createDataOutput();
d.setId(task.getId() + "_" + da.getId() + "Output");
d.setName(da.getId());
task.getIoSpecification().getDataOutputs().add(d);
task.getIoSpecification().getOutputSets().get(0).getDataOutputRefs().add(d);
DataOutputAssociation dia = Bpmn2Factory.eINSTANCE.createDataOutputAssociation();
dia.setTargetRef(da);
dia.getSourceRef().add(d);
task.getDataOutputAssociations().add(dia);
}
} else if(as.getSourceRef() instanceof CatchEvent) {
CatchEvent ce = (CatchEvent) as.getSourceRef();
// update catch event data output and add data output association
boolean foundDataOutput = false;
List<DataOutput> dataOutputs = ce.getDataOutputs();
for(DataOutput dout : dataOutputs) {
if(dout.getId().equals(ce.getId() + "_" + da.getId() + "Output")) {
foundDataOutput = true;
}
}
if(!foundDataOutput) {
DataOutput dataout = Bpmn2Factory.eINSTANCE.createDataOutput();
dataout.setId(ce.getId() + "_" + da.getId() + "Output");
dataout.setName(da.getId() + "Output");
ce.getDataOutputs().add(dataout);
if(ce.getOutputSet() == null) {
OutputSet outset = Bpmn2Factory.eINSTANCE.createOutputSet();
ce.setOutputSet(outset);
}
ce.getOutputSet().getDataOutputRefs().add(dataout);
DataOutputAssociation dia = Bpmn2Factory.eINSTANCE.createDataOutputAssociation();
dia.setTargetRef(da);
dia.getSourceRef().add(dataout);
ce.getDataOutputAssociation().add(dia);
}
}
}
}
}
}
}
}
public void revisitTaskAssociations(Definitions def) {
List<RootElement> rootElements = def.getRootElements();
for(RootElement root : rootElements) {
if(root instanceof Process) {
Process process = (Process) root;
List<FlowElement> flowElements = process.getFlowElements();
for(FlowElement fe : flowElements) {
if(fe instanceof Task) {
Task t = (Task) fe;
if(t.getDataInputAssociations() != null) {
List<DataInputAssociation> inputList = t.getDataInputAssociations();
if(inputList != null) {
for(DataInputAssociation input : inputList) {
List<ItemAwareElement> sourceRef = input.getSourceRef();
if(sourceRef != null) {
for(ItemAwareElement iae : sourceRef) {
String[] iaeParts = iae.getId().split( "\\." );
if(iaeParts.length > 1) {
FormalExpression dataInputTransformationExpression = Bpmn2Factory.eINSTANCE.createFormalExpression();
dataInputTransformationExpression.setBody(iae.getId());
input.setTransformation(dataInputTransformationExpression);
iae.setId(iaeParts[0]);
}
}
}
}
}
}
if(t.getDataOutputAssociations() != null) {
List<DataOutputAssociation> outputList = t.getDataOutputAssociations();
if(outputList != null) {
for(DataOutputAssociation output : outputList) {
ItemAwareElement targetEle = output.getTargetRef();
if(targetEle != null) {
String[] targetEleParts = targetEle.getId().split( "\\." );
if(targetEleParts.length > 1) {
FormalExpression dataOutputTransformationExpression = Bpmn2Factory.eINSTANCE.createFormalExpression();
dataOutputTransformationExpression.setBody(targetEle.getId());
output.setTransformation(dataOutputTransformationExpression);
targetEle.setId(targetEleParts[0]);
}
}
}
}
}
if(t.getIoSpecification() != null) {
InputOutputSpecification ios = t.getIoSpecification();
if(ios.getInputSets() == null || ios.getInputSets().size() < 1) {
InputSet inset = Bpmn2Factory.eINSTANCE.createInputSet();
ios.getInputSets().add(inset);
}
if(ios.getOutputSets() == null) {
if(ios.getOutputSets() == null || ios.getOutputSets().size() < 1) {
OutputSet outset = Bpmn2Factory.eINSTANCE.createOutputSet();
ios.getOutputSets().add(outset);
}
}
}
}
}
}
}
}
public void revisitSendReceiveTasks(Definitions def) {
List<Message> toAddMessages = new ArrayList<Message>();
List<ItemDefinition> toAddItemDefinitions = new ArrayList<ItemDefinition>();
List<RootElement> rootElements = def.getRootElements();
for(RootElement root : rootElements) {
if(root instanceof Process) {
Process process = (Process) root;
List<FlowElement> flowElements = process.getFlowElements();
for(FlowElement fe : flowElements) {
if(fe instanceof ReceiveTask) {
ReceiveTask rt = (ReceiveTask) fe;
ItemDefinition idef = Bpmn2Factory.eINSTANCE.createItemDefinition();
Message msg = Bpmn2Factory.eINSTANCE.createMessage();
Iterator<FeatureMap.Entry> iter = rt.getAnyAttribute().iterator();
while(iter.hasNext()) {
FeatureMap.Entry entry = iter.next();
if(entry.getEStructuralFeature().getName().equals("msgref")) {
msg.setId((String) entry.getValue());
idef.setId((String) entry.getValue() + "Type");
}
}
msg.setItemRef(idef);
rt.setMessageRef(msg);
toAddMessages.add(msg);
toAddItemDefinitions.add(idef);
} else if(fe instanceof SendTask) {
SendTask st = (SendTask) fe;
ItemDefinition idef = Bpmn2Factory.eINSTANCE.createItemDefinition();
Message msg = Bpmn2Factory.eINSTANCE.createMessage();
Iterator<FeatureMap.Entry> iter = st.getAnyAttribute().iterator();
while(iter.hasNext()) {
FeatureMap.Entry entry = iter.next();
if(entry.getEStructuralFeature().getName().equals("msgref")) {
msg.setId((String) entry.getValue());
idef.setId((String) entry.getValue() + "Type");
}
}
msg.setItemRef(idef);
st.setMessageRef(msg);
toAddMessages.add(msg);
toAddItemDefinitions.add(idef);
}
}
}
}
for(ItemDefinition idef : toAddItemDefinitions) {
def.getRootElements().add(idef);
}
for(Message msg : toAddMessages) {
def.getRootElements().add(msg);
}
}
public void revisitLanes(Definitions def) {
List<RootElement> rootElements = def.getRootElements();
for(RootElement root : rootElements) {
if(root instanceof Process) {
Process process = (Process) root;
if((process.getLaneSets() == null || process.getLaneSets().size() < 1) && _lanes.size() > 0) {
LaneSet ls = Bpmn2Factory.eINSTANCE.createLaneSet();
for(Lane lane : _lanes) {
ls.getLanes().add(lane);
List<FlowNode> laneFlowNodes = lane.getFlowNodeRefs();
for(FlowNode fl : laneFlowNodes) {
process.getFlowElements().add(fl);
}
}
process.getLaneSets().add(ls);
}
}
}
}
public void revisitArtifacts(Definitions def) {
List<RootElement> rootElements = def.getRootElements();
for(RootElement root : rootElements) {
if(root instanceof Process) {
Process process = (Process) root;
for(Artifact a : _artifacts) {
process.getArtifacts().add(a);
}
}
}
}
public void revisitGroups(Definitions def) {
List<RootElement> rootElements = def.getRootElements();
Category defaultCat = Bpmn2Factory.eINSTANCE.createCategory();
defaultCat.setName("default");
for(RootElement root : rootElements) {
if(root instanceof Process) {
Process process = (Process) root;
List<Artifact> processArtifacts = process.getArtifacts();
if(processArtifacts != null) {
for(Artifact ar : processArtifacts) {
if(ar instanceof Group) {
Group group = (Group) ar;
Iterator<FeatureMap.Entry> iter = group.getAnyAttribute().iterator();
while(iter.hasNext()) {
FeatureMap.Entry entry = iter.next();
if(entry.getEStructuralFeature().getName().equals("categoryval")) {
CategoryValue catval = Bpmn2Factory.eINSTANCE.createCategoryValue();
catval.setValue((String) entry.getValue());
defaultCat.getCategoryValue().add(catval);
group.setCategoryValueRef(catval);
}
}
}
}
}
}
}
// only add category if it includes at least one categoryvalue
if(defaultCat.getCategoryValue() != null && defaultCat.getCategoryValue().size() > 0) {
rootElements.add(defaultCat);
}
}
/**
* Updates event definitions for all throwing events.
* @param def Definitions
*/
public void revisitThrowEvents(Definitions def) {
List<RootElement> rootElements = def.getRootElements();
List<Signal> toAddSignals = new ArrayList<Signal>();
List<Error> toAddErrors = new ArrayList<Error>();
List<Escalation> toAddEscalations = new ArrayList<Escalation>();
List<Message> toAddMessages = new ArrayList<Message>();
List<ItemDefinition> toAddItemDefinitions = new ArrayList<ItemDefinition>();
for(RootElement root : rootElements) {
if(root instanceof Process) {
Process process = (Process) root;
List<FlowElement> flowElements = process.getFlowElements();
for(FlowElement fe : flowElements) {
if(fe instanceof ThrowEvent) {
if(((ThrowEvent)fe).getEventDefinitions().size() > 0) {
EventDefinition ed = ((ThrowEvent)fe).getEventDefinitions().get(0);
if (ed instanceof SignalEventDefinition) {
Signal signal = Bpmn2Factory.eINSTANCE.createSignal();
Iterator<FeatureMap.Entry> iter = ed.getAnyAttribute().iterator();
while(iter.hasNext()) {
FeatureMap.Entry entry = iter.next();
if(entry.getEStructuralFeature().getName().equals("signalrefname")) {
signal.setName((String) entry.getValue());
}
}
toAddSignals.add(signal);
((SignalEventDefinition) ed).setSignalRef(signal);
} else if(ed instanceof ErrorEventDefinition) {
Error err = Bpmn2Factory.eINSTANCE.createError();
Iterator<FeatureMap.Entry> iter = ed.getAnyAttribute().iterator();
while(iter.hasNext()) {
FeatureMap.Entry entry = iter.next();
if(entry.getEStructuralFeature().getName().equals("erefname")) {
err.setId((String) entry.getValue());
err.setErrorCode((String) entry.getValue());
}
}
toAddErrors.add(err);
((ErrorEventDefinition) ed).setErrorRef(err);
} else if(ed instanceof EscalationEventDefinition) {
Escalation escalation = Bpmn2Factory.eINSTANCE.createEscalation();
Iterator<FeatureMap.Entry> iter = ed.getAnyAttribute().iterator();
while(iter.hasNext()) {
FeatureMap.Entry entry = iter.next();
if(entry.getEStructuralFeature().getName().equals("esccode")) {
escalation.setEscalationCode((String) entry.getValue());
}
}
toAddEscalations.add(escalation);
((EscalationEventDefinition) ed).setEscalationRef(escalation);
} else if(ed instanceof MessageEventDefinition) {
ItemDefinition idef = Bpmn2Factory.eINSTANCE.createItemDefinition();
Message msg = Bpmn2Factory.eINSTANCE.createMessage();
Iterator<FeatureMap.Entry> iter = ed.getAnyAttribute().iterator();
while(iter.hasNext()) {
FeatureMap.Entry entry = iter.next();
if(entry.getEStructuralFeature().getName().equals("msgref")) {
msg.setId((String) entry.getValue());
idef.setId((String) entry.getValue() + "Type");
}
}
msg.setItemRef(idef);
((MessageEventDefinition) ed).setMessageRef(msg);
toAddMessages.add(msg);
toAddItemDefinitions.add(idef);
} else if(ed instanceof CompensateEventDefinition) {
Iterator<FeatureMap.Entry> iter = ed.getAnyAttribute().iterator();
while(iter.hasNext()) {
FeatureMap.Entry entry = iter.next();
if(entry.getEStructuralFeature().getName().equals("actrefname")) {
String activityNameRef = (String) entry.getValue();
// we have to iterate again through all flow elements
// in order to find our activity name
List<RootElement> re = def.getRootElements();
for(RootElement r : re) {
if(r instanceof Process) {
Process p = (Process) root;
List<FlowElement> fes = p.getFlowElements();
for(FlowElement f : fes) {
if(f instanceof Activity && ((Activity) f).getName().equals(activityNameRef)) {
((CompensateEventDefinition) ed).setActivityRef((Activity)f);
}
}
}
}
}
}
}
}
}
}
}
}
for(Signal s : toAddSignals) {
def.getRootElements().add(s);
}
for(Error er : toAddErrors) {
def.getRootElements().add(er);
}
for(Escalation es : toAddEscalations) {
def.getRootElements().add(es);
}
for(ItemDefinition idef : toAddItemDefinitions) {
def.getRootElements().add(idef);
}
for(Message msg : toAddMessages) {
def.getRootElements().add(msg);
}
}
private void revisitCatchEventsConvertToBoundary(Definitions def) {
List<CatchEvent> catchEventsToRemove = new ArrayList<CatchEvent>();
List<BoundaryEvent> boundaryEventsToAdd = new ArrayList<BoundaryEvent>();
List<RootElement> rootElements = def.getRootElements();
for(RootElement root : rootElements) {
if(root instanceof Process) {
Process process = (Process) root;
List<FlowElement> flowElements = process.getFlowElements();
for(FlowElement fe : flowElements) {
if(fe instanceof CatchEvent) {
CatchEvent ce = (CatchEvent) fe;
// check if we have an outgoing connection to this catch event from an activity
for (Entry<Object, List<String>> entry : _outgoingFlows.entrySet()) {
for (String flowId : entry.getValue()) {
if (entry.getKey() instanceof Activity && flowId.equals(ce.getId())) {
BoundaryEvent be = Bpmn2Factory.eINSTANCE.createBoundaryEvent();
if(ce.getDataOutputs() != null) {
be.getDataOutputs().addAll(ce.getDataOutputs());
}
if(ce.getDataOutputAssociation() != null) {
be.getDataOutputAssociation().addAll(ce.getDataOutputAssociation());
}
if(ce.getOutputSet() != null) {
be.setOutputSet(ce.getOutputSet());
}
if(ce.getEventDefinitions() != null) {
be.getEventDefinitions().addAll(ce.getEventDefinitions());
}
if(ce.getEventDefinitionRefs() != null) {
be.getEventDefinitionRefs().addAll(ce.getEventDefinitionRefs());
}
if(ce.getProperties() != null) {
be.getProperties().addAll(ce.getProperties());
}
if(ce.getAnyAttribute() != null) {
be.getAnyAttribute().addAll(ce.getAnyAttribute());
}
if(ce.getOutgoing() != null) {
be.getOutgoing().addAll(ce.getOutgoing());
}
if(ce.getIncoming() != null) {
be.getIncoming().addAll(ce.getIncoming());
}
if(ce.getProperties() != null) {
be.getProperties().addAll(ce.getProperties());
}
be.setName(ce.getName());
be.setId(ce.getId());
be.setAttachedToRef(((Activity)entry.getKey()));
((Activity)entry.getKey()).getBoundaryEventRefs().add(be);
catchEventsToRemove.add(ce);
boundaryEventsToAdd.add(be);
}
}
}
}
}
if(boundaryEventsToAdd.size() > 0) {
for(BoundaryEvent be : boundaryEventsToAdd) {
process.getFlowElements().add(be);
}
}
if(catchEventsToRemove.size() > 0) {
for(CatchEvent ce : catchEventsToRemove) {
process.getFlowElements().remove(ce);
}
}
}
}
}
/**
* Updates event definitions for all catch events.
* @param def Definitions
*/
public void revisitCatchEvents(Definitions def) {
List<RootElement> rootElements = def.getRootElements();
List<Signal> toAddSignals = new ArrayList<Signal>();
List<Error> toAddErrors = new ArrayList<Error>();
List<Escalation> toAddEscalations = new ArrayList<Escalation>();
List<Message> toAddMessages = new ArrayList<Message>();
List<ItemDefinition> toAddItemDefinitions = new ArrayList<ItemDefinition>();
for(RootElement root : rootElements) {
if(root instanceof Process) {
Process process = (Process) root;
List<FlowElement> flowElements = process.getFlowElements();
for(FlowElement fe : flowElements) {
if(fe instanceof CatchEvent) {
if(((CatchEvent)fe).getEventDefinitions().size() > 0) {
EventDefinition ed = ((CatchEvent)fe).getEventDefinitions().get(0);
if (ed instanceof SignalEventDefinition) {
Signal signal = Bpmn2Factory.eINSTANCE.createSignal();
Iterator<FeatureMap.Entry> iter = ed.getAnyAttribute().iterator();
while(iter.hasNext()) {
FeatureMap.Entry entry = iter.next();
if(entry.getEStructuralFeature().getName().equals("signalrefname")) {
signal.setName((String) entry.getValue());
}
}
toAddSignals.add(signal);
((SignalEventDefinition) ed).setSignalRef(signal);
} else if(ed instanceof ErrorEventDefinition) {
Error err = Bpmn2Factory.eINSTANCE.createError();
Iterator<FeatureMap.Entry> iter = ed.getAnyAttribute().iterator();
while(iter.hasNext()) {
FeatureMap.Entry entry = iter.next();
if(entry.getEStructuralFeature().getName().equals("erefname")) {
err.setId((String) entry.getValue());
err.setErrorCode((String) entry.getValue());
}
}
toAddErrors.add(err);
((ErrorEventDefinition) ed).setErrorRef(err);
} else if(ed instanceof EscalationEventDefinition) {
Escalation escalation = Bpmn2Factory.eINSTANCE.createEscalation();
Iterator<FeatureMap.Entry> iter = ed.getAnyAttribute().iterator();
while(iter.hasNext()) {
FeatureMap.Entry entry = iter.next();
if(entry.getEStructuralFeature().getName().equals("esccode")) {
escalation.setEscalationCode((String) entry.getValue());
}
}
toAddEscalations.add(escalation);
((EscalationEventDefinition) ed).setEscalationRef(escalation);
} else if(ed instanceof MessageEventDefinition) {
ItemDefinition idef = Bpmn2Factory.eINSTANCE.createItemDefinition();
Message msg = Bpmn2Factory.eINSTANCE.createMessage();
Iterator<FeatureMap.Entry> iter = ed.getAnyAttribute().iterator();
while(iter.hasNext()) {
FeatureMap.Entry entry = iter.next();
if(entry.getEStructuralFeature().getName().equals("msgref")) {
msg.setId((String) entry.getValue());
idef.setId((String) entry.getValue() + "Type");
}
}
msg.setItemRef(idef);
((MessageEventDefinition) ed).setMessageRef(msg);
toAddMessages.add(msg);
toAddItemDefinitions.add(idef);
} else if(ed instanceof CompensateEventDefinition) {
Iterator<FeatureMap.Entry> iter = ed.getAnyAttribute().iterator();
while(iter.hasNext()) {
FeatureMap.Entry entry = iter.next();
if(entry.getEStructuralFeature().getName().equals("actrefname")) {
String activityNameRef = (String) entry.getValue();
// we have to iterate again through all flow elements
// in order to find our activity name
List<RootElement> re = def.getRootElements();
for(RootElement r : re) {
if(r instanceof Process) {
Process p = (Process) root;
List<FlowElement> fes = p.getFlowElements();
for(FlowElement f : fes) {
if(f instanceof Activity && ((Activity) f).getName().equals(activityNameRef)) {
((CompensateEventDefinition) ed).setActivityRef((Activity)f);
}
}
}
}
}
}
}
}
}
}
}
}
for(Signal s : toAddSignals) {
def.getRootElements().add(s);
}
for(Error er : toAddErrors) {
def.getRootElements().add(er);
}
for(Escalation es : toAddEscalations) {
def.getRootElements().add(es);
}
for(ItemDefinition idef : toAddItemDefinitions) {
def.getRootElements().add(idef);
}
for(Message msg : toAddMessages) {
def.getRootElements().add(msg);
}
}
/**
* Updates the gatewayDirection attributes of all gateways.
* @param def
*/
private void revisitGateways(Definitions def) {
List<RootElement> rootElements = def.getRootElements();
for(RootElement root : rootElements) {
if(root instanceof Process) {
setGatewayDirection((Process) root);
}
}
}
private void setGatewayDirection(FlowElementsContainer container) {
List<FlowElement> flowElements = container.getFlowElements();
for(FlowElement fe : flowElements) {
if(fe instanceof Gateway) {
Gateway gateway = (Gateway) fe;
int incoming = gateway.getIncoming() == null ? 0 : gateway.getIncoming().size();
int outgoing = gateway.getOutgoing() == null ? 0 : gateway.getOutgoing().size();
if (incoming <= 1 && outgoing > 1) {
gateway.setGatewayDirection(GatewayDirection.DIVERGING);
} else if (incoming > 1 && outgoing <= 1) {
gateway.setGatewayDirection(GatewayDirection.CONVERGING);
} else if (incoming > 1 && outgoing > 1) {
gateway.setGatewayDirection(GatewayDirection.MIXED);
} else if (incoming == 1 && outgoing == 1) {
// this handles the 1:1 case of the diverging gateways
gateway.setGatewayDirection(GatewayDirection.DIVERGING);
} else {
gateway.setGatewayDirection(GatewayDirection.UNSPECIFIED);
}
}
if(fe instanceof InclusiveGateway) {
Iterator<FeatureMap.Entry> iter = fe.getAnyAttribute().iterator();
while(iter.hasNext()) {
FeatureMap.Entry entry = iter.next();
if(entry.getEStructuralFeature().getName().equals("dg")) {
for(FlowElement feg : flowElements) {
if(feg instanceof SequenceFlow && feg.getId().equals((String) entry.getValue())) {
((InclusiveGateway) fe).setDefault((SequenceFlow) feg);
}
}
}
}
}
if(fe instanceof FlowElementsContainer) {
setGatewayDirection((FlowElementsContainer) fe);
}
}
}
private void revisitServiceTasks(Definitions def) {
List<RootElement> rootElements = def.getRootElements();
List<Interface> toAddInterfaces = new ArrayList<Interface>();
List<Message> toAddMessages = new ArrayList<Message>();
List<ItemDefinition> toAddDefinitions = new ArrayList<ItemDefinition>();
for(RootElement root : rootElements) {
if(root instanceof Process) {
Process process = (Process) root;
List<FlowElement> flowElements = process.getFlowElements();
for(FlowElement fe : flowElements) {
if(fe instanceof ServiceTask) {
Iterator<FeatureMap.Entry> iter = fe.getAnyAttribute().iterator();
String serviceInterface = null;
String serviceOperation = null;
while(iter.hasNext()) {
FeatureMap.Entry entry = iter.next();
if(entry.getEStructuralFeature().getName().equals("servicetaskinterface")) {
serviceInterface = (String) entry.getValue();
}
if(entry.getEStructuralFeature().getName().equals("servicetaskoperation")) {
serviceOperation = (String) entry.getValue();
}
}
Interface newInterface = Bpmn2Factory.eINSTANCE.createInterface();
if(serviceInterface != null) {
newInterface.setName(serviceInterface);
newInterface.setId(fe.getId() + "_ServiceInterface");
}
if(serviceOperation != null) {
Operation oper = Bpmn2Factory.eINSTANCE.createOperation();
oper.setId(fe.getId() + "_ServiceOperation");
oper.setName(serviceOperation);
Message message = Bpmn2Factory.eINSTANCE.createMessage();
message.setId(fe.getId() + "_InMessage");
ItemDefinition itemdef = Bpmn2Factory.eINSTANCE.createItemDefinition();
itemdef.setId(message.getId() + "Type");
message.setItemRef(itemdef);
toAddDefinitions.add(itemdef);
toAddMessages.add(message);
oper.setInMessageRef(message);
newInterface.getOperations().add(oper);
((ServiceTask) fe).setOperationRef(oper);
}
toAddInterfaces.add(newInterface);
}
}
}
}
for(ItemDefinition id : toAddDefinitions) {
def.getRootElements().add(id);
}
for(Message m : toAddMessages) {
def.getRootElements().add(m);
}
for(Interface i : toAddInterfaces) {
def.getRootElements().add(i);
}
}
/**
* Revisit message to set their item ref to a item definition
* @param def Definitions
*/
private void revisitMessages(Definitions def) {
List<RootElement> rootElements = def.getRootElements();
List<ItemDefinition> toAddDefinitions = new ArrayList<ItemDefinition>();
for(RootElement root : rootElements) {
if(root instanceof Message) {
if(!existsMessageItemDefinition(rootElements, root.getId())) {
ItemDefinition itemdef = Bpmn2Factory.eINSTANCE.createItemDefinition();
itemdef.setId(root.getId() + "Type");
toAddDefinitions.add(itemdef);
((Message) root).setItemRef(itemdef);
}
}
}
for(ItemDefinition id : toAddDefinitions) {
def.getRootElements().add(id);
}
}
private boolean existsMessageItemDefinition(List<RootElement> rootElements, String id) {
for(RootElement root : rootElements) {
if(root instanceof ItemDefinition && root.getId().equals(id + "Type")) {
return true;
}
}
return false;
}
/**
* Reconnect the sequence flows and the flow nodes.
* Done after the initial pass so that we have all the target information.
*/
private void reconnectFlows() {
// create the reverse id map:
for (Entry<Object, List<String>> entry : _outgoingFlows.entrySet()) {
for (String flowId : entry.getValue()) {
if (entry.getKey() instanceof SequenceFlow) { // if it is a sequence flow, we can tell its targets
((SequenceFlow) entry.getKey()).setTargetRef((FlowNode) _idMap.get(flowId));
} else if (entry.getKey() instanceof Association) {
((Association) entry.getKey()).setTargetRef((BaseElement) _idMap.get(flowId));
} else { // if it is a node, we can map it to its outgoing sequence flows
if (_idMap.get(flowId) instanceof SequenceFlow) {
((FlowNode) entry.getKey()).getOutgoing().add((SequenceFlow) _idMap.get(flowId));
} else if (_idMap.get(flowId) instanceof Association) {
((Association) _idMap.get(flowId)).setSourceRef((BaseElement) entry.getKey());
}
}
}
}
}
private void createSubProcessDiagram(BPMNPlane plane, FlowElement flowElement, BpmnDiFactory factory) {
SubProcess sp = (SubProcess) flowElement;
for(FlowElement subProcessFlowElement : sp.getFlowElements()) {
if(subProcessFlowElement instanceof SubProcess) {
Bounds spb = _bounds.get(subProcessFlowElement.getId());
if (spb != null) {
BPMNShape shape = factory.createBPMNShape();
shape.setBpmnElement(subProcessFlowElement);
shape.setBounds(spb);
plane.getPlaneElement().add(shape);
}
createSubProcessDiagram(plane, subProcessFlowElement, factory);
} else if (subProcessFlowElement instanceof FlowNode) {
Bounds spb = _bounds.get(subProcessFlowElement.getId());
if (spb != null) {
BPMNShape shape = factory.createBPMNShape();
shape.setBpmnElement(subProcessFlowElement);
shape.setBounds(spb);
plane.getPlaneElement().add(shape);
}
} else if (subProcessFlowElement instanceof SequenceFlow) {
SequenceFlow sequenceFlow = (SequenceFlow) subProcessFlowElement;
BPMNEdge edge = factory.createBPMNEdge();
edge.setBpmnElement(subProcessFlowElement);
DcFactory dcFactory = DcFactory.eINSTANCE;
Point point = dcFactory.createPoint();
if(sequenceFlow.getSourceRef() != null) {
Bounds sourceBounds = _bounds.get(sequenceFlow.getSourceRef().getId());
point.setX(sourceBounds.getX() + (sourceBounds.getWidth()/2));
point.setY(sourceBounds.getY() + (sourceBounds.getHeight()/2));
}
edge.getWaypoint().add(point);
List<Point> dockers = _dockers.get(sequenceFlow.getId());
for (int i = 1; i < dockers.size() - 1; i++) {
edge.getWaypoint().add(dockers.get(i));
}
point = dcFactory.createPoint();
if(sequenceFlow.getTargetRef() != null) {
Bounds targetBounds = _bounds.get(sequenceFlow.getTargetRef().getId());
point.setX(targetBounds.getX() + (targetBounds.getWidth()/2));
point.setY(targetBounds.getY() + (targetBounds.getHeight()/2));
}
edge.getWaypoint().add(point);
plane.getPlaneElement().add(edge);
}
}
for (Artifact artifact : sp.getArtifacts()) {
if (artifact instanceof TextAnnotation || artifact instanceof Group) {
Bounds ba = _bounds.get(artifact.getId());
if (ba != null) {
BPMNShape shape = factory.createBPMNShape();
shape.setBpmnElement(artifact);
shape.setBounds(ba);
plane.getPlaneElement().add(shape);
}
}
if (artifact instanceof Association){
Association association = (Association)artifact;
BPMNEdge edge = factory.createBPMNEdge();
edge.setBpmnElement(association);
DcFactory dcFactory = DcFactory.eINSTANCE;
Point point = dcFactory.createPoint();
Bounds sourceBounds = _bounds.get(association.getSourceRef().getId());
point.setX(sourceBounds.getX() + (sourceBounds.getWidth()/2));
point.setY(sourceBounds.getY() + (sourceBounds.getHeight()/2));
edge.getWaypoint().add(point);
List<Point> dockers = _dockers.get(association.getId());
for (int i = 1; i < dockers.size() - 1; i++) {
edge.getWaypoint().add(dockers.get(i));
}
point = dcFactory.createPoint();
Bounds targetBounds = _bounds.get(association.getTargetRef().getId());
point.setX(targetBounds.getX() + (targetBounds.getWidth()/2));
point.setY(targetBounds.getY() + (targetBounds.getHeight()/2));
edge.getWaypoint().add(point);
plane.getPlaneElement().add(edge);
}
}
}
private void createDiagram(Definitions def) {
for (RootElement rootElement: def.getRootElements()) {
if (rootElement instanceof Process) {
Process process = (Process) rootElement;
BpmnDiFactory factory = BpmnDiFactory.eINSTANCE;
BPMNDiagram diagram = factory.createBPMNDiagram();
BPMNPlane plane = factory.createBPMNPlane();
plane.setBpmnElement(process);
diagram.setPlane(plane);
// first process flowNodes
for (FlowElement flowElement: process.getFlowElements()) {
if (flowElement instanceof FlowNode) {
Bounds b = _bounds.get(flowElement.getId());
if (b != null) {
BPMNShape shape = factory.createBPMNShape();
shape.setBpmnElement(flowElement);
shape.setBounds(b);
plane.getPlaneElement().add(shape);
if(flowElement instanceof BoundaryEvent) {
BPMNEdge edge = factory.createBPMNEdge();
edge.setBpmnElement(flowElement);
List<Point> dockers = _dockers.get(flowElement.getId());
for (int i = 0; i < dockers.size(); i++) {
edge.getWaypoint().add(dockers.get(i));
}
plane.getPlaneElement().add(edge);
}
}
// check if its a subprocess
if(flowElement instanceof SubProcess) {
createSubProcessDiagram(plane, flowElement, factory);
}
} else if(flowElement instanceof DataObject) {
Bounds b = _bounds.get(flowElement.getId());
if (b != null) {
BPMNShape shape = factory.createBPMNShape();
shape.setBpmnElement(flowElement);
shape.setBounds(b);
plane.getPlaneElement().add(shape);
}
}
else if (flowElement instanceof SequenceFlow) {
SequenceFlow sequenceFlow = (SequenceFlow) flowElement;
BPMNEdge edge = factory.createBPMNEdge();
edge.setBpmnElement(flowElement);
DcFactory dcFactory = DcFactory.eINSTANCE;
Point point = dcFactory.createPoint();
if(sequenceFlow.getSourceRef() != null) {
Bounds sourceBounds = _bounds.get(sequenceFlow.getSourceRef().getId());
point.setX(sourceBounds.getX() + (sourceBounds.getWidth()/2));
point.setY(sourceBounds.getY() + (sourceBounds.getHeight()/2));
}
edge.getWaypoint().add(point);
List<Point> dockers = _dockers.get(sequenceFlow.getId());
for (int i = 1; i < dockers.size() - 1; i++) {
edge.getWaypoint().add(dockers.get(i));
}
point = dcFactory.createPoint();
if(sequenceFlow.getTargetRef() != null) {
Bounds targetBounds = _bounds.get(sequenceFlow.getTargetRef().getId());
point.setX(targetBounds.getX() + (targetBounds.getWidth()/2));
point.setY(targetBounds.getY() + (targetBounds.getHeight()/2));
}
edge.getWaypoint().add(point);
plane.getPlaneElement().add(edge);
}
}
// artifacts
if (process.getArtifacts() != null){
for (Artifact artifact : process.getArtifacts()) {
if (artifact instanceof TextAnnotation || artifact instanceof Group) {
Bounds b = _bounds.get(artifact.getId());
if (b != null) {
BPMNShape shape = factory.createBPMNShape();
shape.setBpmnElement(artifact);
shape.setBounds(b);
plane.getPlaneElement().add(shape);
}
}
if (artifact instanceof Association){
Association association = (Association)artifact;
BPMNEdge edge = factory.createBPMNEdge();
edge.setBpmnElement(association);
DcFactory dcFactory = DcFactory.eINSTANCE;
Point point = dcFactory.createPoint();
Bounds sourceBounds = _bounds.get(association.getSourceRef().getId());
point.setX(sourceBounds.getX() + (sourceBounds.getWidth()/2));
point.setY(sourceBounds.getY() + (sourceBounds.getHeight()/2));
edge.getWaypoint().add(point);
List<Point> dockers = _dockers.get(association.getId());
for (int i = 1; i < dockers.size() - 1; i++) {
edge.getWaypoint().add(dockers.get(i));
}
point = dcFactory.createPoint();
Bounds targetBounds = _bounds.get(association.getTargetRef().getId());
point.setX(targetBounds.getX() + (targetBounds.getWidth()/2));
point.setY(targetBounds.getY() + (targetBounds.getHeight()/2));
edge.getWaypoint().add(point);
plane.getPlaneElement().add(edge);
}
}
}
// lanes
if(process.getLaneSets() != null && process.getLaneSets().size() > 0) {
for(LaneSet ls : process.getLaneSets()) {
for(Lane lane : ls.getLanes()) {
Bounds b = _bounds.get(lane.getId());
if (b != null) {
BPMNShape shape = factory.createBPMNShape();
shape.setBpmnElement(lane);
shape.setBounds(b);
plane.getPlaneElement().add(shape);
}
}
}
}
def.getDiagrams().add(diagram);
}
}
}
private BaseElement unmarshallItem(JsonParser parser, String preProcessingData) throws JsonParseException, IOException {
String resourceId = null;
Map<String, String> properties = null;
String stencil = null;
List<BaseElement> childElements = new ArrayList<BaseElement>();
List<String> outgoing = new ArrayList<String>();
while (parser.nextToken() != JsonToken.END_OBJECT) {
String fieldname = parser.getCurrentName();
parser.nextToken();
if ("resourceId".equals(fieldname)) {
resourceId = parser.getText();
} else if ("properties".equals(fieldname)) {
properties = unmarshallProperties(parser);
} else if ("stencil".equals(fieldname)) {
// "stencil":{"id":"Task"},
parser.nextToken();
parser.nextToken();
stencil = parser.getText();
parser.nextToken();
} else if ("childShapes".equals(fieldname)) {
while (parser.nextToken() != JsonToken.END_ARRAY) { // open the
// object
// the childShapes element is a json array. We opened the
// array.
childElements.add(unmarshallItem(parser, preProcessingData));
}
} else if ("bounds".equals(fieldname)) {
// bounds: {"lowerRight":{"x":484.0,"y":198.0},"upperLeft":{"x":454.0,"y":168.0}}
parser.nextToken();
parser.nextToken();
parser.nextToken();
parser.nextToken();
Integer x2 = parser.getIntValue();
parser.nextToken();
parser.nextToken();
Integer y2 = parser.getIntValue();
parser.nextToken();
parser.nextToken();
parser.nextToken();
parser.nextToken();
parser.nextToken();
Integer x1 = parser.getIntValue();
parser.nextToken();
parser.nextToken();
Integer y1 = parser.getIntValue();
parser.nextToken();
parser.nextToken();
Bounds b = DcFactory.eINSTANCE.createBounds();
b.setX(x1);
b.setY(y1);
b.setWidth(x2 - x1);
b.setHeight(y2 - y1);
this._bounds.put(resourceId, b);
} else if ("dockers".equals(fieldname)) {
// "dockers":[{"x":50,"y":40},{"x":353.5,"y":115},{"x":353.5,"y":152},{"x":50,"y":40}],
List<Point> dockers = new ArrayList<Point>();
JsonToken nextToken = parser.nextToken();
boolean end = JsonToken.END_ARRAY.equals(nextToken);
while (!end) {
nextToken = parser.nextToken();
nextToken = parser.nextToken();
Integer x = parser.getIntValue();
parser.nextToken();
parser.nextToken();
Integer y = parser.getIntValue();
Point point = DcFactory.eINSTANCE.createPoint();
point.setX(x);
point.setY(y);
dockers.add(point);
parser.nextToken();
nextToken = parser.nextToken();
end = JsonToken.END_ARRAY.equals(nextToken);
}
this._dockers.put(resourceId, dockers);
} else if ("outgoing".equals(fieldname)) {
while (parser.nextToken() != JsonToken.END_ARRAY) {
// {resourceId: oryx_1AAA8C9A-39A5-42FC-8ED1-507A7F3728EA}
parser.nextToken();
parser.nextToken();
outgoing.add(parser.getText());
parser.nextToken();
}
// pass on the array
parser.skipChildren();
} else if ("target".equals(fieldname)) {
// we already collected that info with the outgoing field.
parser.skipChildren();
// "target": {
// "resourceId": "oryx_A75E7546-DF71-48EA-84D3-2A8FD4A47568"
// }
// add to the map:
// parser.nextToken(); // resourceId:
// parser.nextToken(); // the value we want to save
// targetId = parser.getText();
// parser.nextToken(); // }, closing the object
}
}
properties.put("resourceId", resourceId);
boolean customElement = isCustomElement(properties.get("tasktype"), preProcessingData);
BaseElement baseElt = Bpmn20Stencil.createElement(stencil, properties.get("tasktype"), customElement);
// register the sequence flow targets.
if(baseElt instanceof SequenceFlow) {
_sequenceFlowTargets.addAll(outgoing);
}
_outgoingFlows.put(baseElt, outgoing);
_objMap.put(baseElt, resourceId); // keep the object around to do connections
_idMap.put(resourceId, baseElt);
// baseElt.setId(resourceId); commented out as bpmn2 seems to create
// duplicate ids right now.
applyProperties(baseElt, properties);
if (baseElt instanceof Definitions) {
Process rootLevelProcess = null;
for (BaseElement child : childElements) {
// tasks are only permitted under processes.
// a process should be created implicitly for tasks at the root
// level.
// process designer doesn't make a difference between tasks and
// global tasks.
// if a task has sequence edges it is considered a task,
// otherwise it is considered a global task.
// if (child instanceof Task && _outgoingFlows.get(child).isEmpty() && !_sequenceFlowTargets.contains(_objMap.get(child))) {
// // no edges on a task at the top level! We replace it with a
// // global task.
// GlobalTask task = null;
// if (child instanceof ScriptTask) {
// task = Bpmn2Factory.eINSTANCE.createGlobalScriptTask();
// ((GlobalScriptTask) task).setScript(((ScriptTask) child).getScript());
// ((GlobalScriptTask) task).setScriptLanguage(((ScriptTask) child).getScriptFormat());
// // TODO scriptLanguage missing on scriptTask
// } else if (child instanceof UserTask) {
// task = Bpmn2Factory.eINSTANCE.createGlobalUserTask();
// } else if (child instanceof ServiceTask) {
// // we don't have a global service task! Fallback on a
// // normal global task
// task = Bpmn2Factory.eINSTANCE.createGlobalTask();
// } else if (child instanceof BusinessRuleTask) {
// task = Bpmn2Factory.eINSTANCE.createGlobalBusinessRuleTask();
// } else if (child instanceof ManualTask) {
// task = Bpmn2Factory.eINSTANCE.createGlobalManualTask();
// } else {
// task = Bpmn2Factory.eINSTANCE.createGlobalTask();
// }
//
// task.setName(((Task) child).getName());
// task.setIoSpecification(((Task) child).getIoSpecification());
// task.getDocumentation().addAll(((Task) child).getDocumentation());
// ((Definitions) baseElt).getRootElements().add(task);
// continue;
// } else {
if (child instanceof SequenceFlow) {
// for some reason sequence flows are placed as root elements.
// find if the target has a container, and if we can use it:
List<String> ids = _outgoingFlows.get(child);
FlowElementsContainer container = null;
for (String id : ids) { // yes, we iterate, but we'll take the first in the list that will work.
Object obj = _idMap.get(id);
if (obj instanceof EObject && ((EObject) obj).eContainer() instanceof FlowElementsContainer) {
container = (FlowElementsContainer) ((EObject) obj).eContainer();
break;
}
}
if (container != null) {
container.getFlowElements().add((SequenceFlow) child);
continue;
}
}
if (child instanceof Task || child instanceof SequenceFlow
|| child instanceof Gateway || child instanceof Event
|| child instanceof Artifact || child instanceof DataObject || child instanceof SubProcess
|| child instanceof Lane || child instanceof CallActivity) {
if (rootLevelProcess == null) {
rootLevelProcess = Bpmn2Factory.eINSTANCE.createProcess();
// set the properties and item definitions first
if(properties.get("vardefs") != null && properties.get("vardefs").length() > 0) {
String[] vardefs = properties.get("vardefs").split( ",\\s*" );
for(String vardef : vardefs) {
Property prop = Bpmn2Factory.eINSTANCE.createProperty();
ItemDefinition itemdef = Bpmn2Factory.eINSTANCE.createItemDefinition();
// check if we define a structure ref in the definition
if(vardef.contains(":")) {
String[] vardefParts = vardef.split( ":\\s*" );
prop.setId(vardefParts[0]);
itemdef.setId("_" + prop.getId() + "Item");
itemdef.setStructureRef(vardefParts[1]);
} else {
prop.setId(vardef);
itemdef.setId("_" + prop.getId() + "Item");
}
prop.setItemSubjectRef(itemdef);
rootLevelProcess.getProperties().add(prop);
((Definitions) baseElt).getRootElements().add(itemdef);
}
}
rootLevelProcess.setId(properties.get("id"));
applyProcessProperties(rootLevelProcess, properties);
((Definitions) baseElt).getRootElements().add(rootLevelProcess);
}
}
if (child instanceof Task) {
rootLevelProcess.getFlowElements().add((Task) child);
} else if (child instanceof CallActivity) {
rootLevelProcess.getFlowElements().add((CallActivity) child);
} else if (child instanceof RootElement) {
((Definitions) baseElt).getRootElements().add((RootElement) child);
} else if (child instanceof SequenceFlow) {
rootLevelProcess.getFlowElements().add((SequenceFlow) child);
} else if (child instanceof Gateway) {
rootLevelProcess.getFlowElements().add((Gateway) child);
} else if (child instanceof Event) {
rootLevelProcess.getFlowElements().add((Event) child);
} else if (child instanceof Artifact) {
rootLevelProcess.getArtifacts().add((Artifact) child);
} else if (child instanceof DataObject) {
rootLevelProcess.getFlowElements().add((DataObject) child);
// ItemDefinition def = ((DataObject) child).getItemSubjectRef();
// if (def != null) {
// if (def.eResource() == null) {
// ((Definitions) rootLevelProcess.eContainer()).getRootElements().add(0, def);
// }
// Import imported = def.getImport();
// if (imported != null && imported.eResource() == null) {
// ((Definitions) rootLevelProcess.eContainer()).getImports().add(0, imported);
// }
// }
} else if(child instanceof SubProcess) {
rootLevelProcess.getFlowElements().add((SubProcess) child);
} else if(child instanceof Lane) {
// lanes handled later
} else {
throw new IllegalArgumentException("Don't know what to do of " + child);
}
// }
}
} else if (baseElt instanceof Process) {
for (BaseElement child : childElements) {
if (child instanceof Lane) {
if (((Process) baseElt).getLaneSets().isEmpty()) {
((Process) baseElt).getLaneSets().add(Bpmn2Factory.eINSTANCE.createLaneSet());
}
((Process) baseElt).getLaneSets().get(0).getLanes().add((Lane) child);
addLaneFlowNodes((Process) baseElt, (Lane) child);
} else if (child instanceof Artifact) {
((Process) baseElt).getArtifacts().add((Artifact) child);
} else {
throw new IllegalArgumentException("Don't know what to do of " + child);
}
}
} else if (baseElt instanceof SubProcess) {
for (BaseElement child : childElements) {
if (child instanceof FlowElement) {
((SubProcess) baseElt).getFlowElements().add((FlowElement) child);
} else if(child instanceof Artifact) {
((SubProcess) baseElt).getArtifacts().add((Artifact) child);
} else {
throw new IllegalArgumentException("Subprocess - don't know what to do of " + child);
}
}
} else if (baseElt instanceof Message) {
// we do not support base-element messages from the json. They are created dynamically for events that use them.
} else if (baseElt instanceof Lane) {
((Lane) baseElt).setName(properties.get("name"));
for (BaseElement child : childElements) {
if (child instanceof FlowNode) {
((Lane) baseElt).getFlowNodeRefs().add((FlowNode) child);
}
// no support for child-lanes at this point
// else if (child instanceof Lane) {
// if (((Lane) baseElt).getChildLaneSet() == null) {
// ((Lane) baseElt).setChildLaneSet(Bpmn2Factory.eINSTANCE.createLaneSet());
// }
// ((Lane) baseElt).getChildLaneSet().getLanes().add((Lane) child);
// }
else if(child instanceof Artifact){
_artifacts.add((Artifact) child);
} else {
throw new IllegalArgumentException("Don't know what to do of " + childElements);
}
}
_lanes.add((Lane) baseElt);
} else {
if (!childElements.isEmpty()) {
throw new IllegalArgumentException("Don't know what to do of " + childElements + " with " + baseElt);
}
}
return baseElt;
}
private void addLaneFlowNodes(Process process, Lane lane) {
process.getFlowElements().addAll(lane.getFlowNodeRefs());
// for (FlowNode node : lane.getFlowNodeRefs()) {
// if (node instanceof DataObject) {
// ItemDefinition def = ((DataObject) node).getItemSubjectRef();
// if (def != null) {
// if (def.eResource() == null) {
// ((Definitions) process.eContainer()).getRootElements().add(0, ((DataObject) node).getItemSubjectRef());
// }
// Import imported = def.getImport();
// if (imported != null && imported.eResource() == null) {
// ((Definitions) process.eContainer()).getImports().add(0, ((DataObject) node).getItemSubjectRef().getImport());
// }
// }
// }
// }
if (lane.getChildLaneSet() != null) {
for (Lane l : lane.getChildLaneSet().getLanes()) {
addLaneFlowNodes(process, l);
}
}
}
private void applyProperties(BaseElement baseElement, Map<String, String> properties) {
applyBaseElementProperties((BaseElement) baseElement, properties);
if (baseElement instanceof SubProcess) {
applySubProcessProperties((SubProcess) baseElement, properties);
}
if (baseElement instanceof AdHocSubProcess) {
applyAdHocSubProcessProperties((AdHocSubProcess) baseElement, properties);
}
if (baseElement instanceof CallActivity) {
applyCallActivityProperties((CallActivity) baseElement, properties);
}
if (baseElement instanceof GlobalTask) {
applyGlobalTaskProperties((GlobalTask) baseElement, properties);
}
if (baseElement instanceof Definitions) {
applyDefinitionProperties((Definitions) baseElement, properties);
}
if (baseElement instanceof Process) {
applyProcessProperties((Process) baseElement, properties);
}
if (baseElement instanceof Lane) {
applyLaneProperties((Lane) baseElement, properties);
}
if (baseElement instanceof SequenceFlow) {
applySequenceFlowProperties((SequenceFlow) baseElement, properties);
}
if (baseElement instanceof Task) {
applyTaskProperties((Task) baseElement, properties);
}
if (baseElement instanceof UserTask) {
applyUserTaskProperties((UserTask) baseElement, properties);
}
if (baseElement instanceof BusinessRuleTask) {
applyBusinessRuleTaskProperties((BusinessRuleTask) baseElement, properties);
}
if (baseElement instanceof ScriptTask) {
applyScriptTaskProperties((ScriptTask) baseElement, properties);
}
if (baseElement instanceof ServiceTask) {
applyServiceTaskProperties((ServiceTask) baseElement, properties);
}
if(baseElement instanceof ReceiveTask) {
applyReceiveTaskProperties((ReceiveTask) baseElement, properties);
}
if(baseElement instanceof SendTask) {
applySendTaskProperties((SendTask) baseElement, properties);
}
if (baseElement instanceof Gateway) {
applyGatewayProperties((Gateway) baseElement, properties);
}
if (baseElement instanceof Event) {
applyEventProperties((Event) baseElement, properties);
}
if (baseElement instanceof CatchEvent) {
applyCatchEventProperties((CatchEvent) baseElement, properties);
}
if (baseElement instanceof ThrowEvent) {
applyThrowEventProperties((ThrowEvent) baseElement, properties);
}
if (baseElement instanceof TextAnnotation) {
applyTextAnnotationProperties((TextAnnotation) baseElement, properties);
}
if (baseElement instanceof Group) {
applyGroupProperties((Group) baseElement, properties);
}
if (baseElement instanceof DataObject) {
applyDataObjectProperties((DataObject) baseElement, properties);
}
if (baseElement instanceof DataStore) {
applyDataStoreProperties((DataStore) baseElement, properties);
}
if (baseElement instanceof Message) {
applyMessageProperties((Message) baseElement, properties);
}
if (baseElement instanceof StartEvent) {
applyStartEventProperties((StartEvent) baseElement, properties);
}
if (baseElement instanceof EndEvent) {
applyEndEventProperties((EndEvent) baseElement, properties);
}
if(baseElement instanceof Association) {
applyAssociationProperties((Association) baseElement, properties);
}
// finally, apply properties from helpers:
for (BpmnMarshallerHelper helper : _helpers) {
helper.applyProperties(baseElement, properties);
}
}
private void applySubProcessProperties(SubProcess sp, Map<String, String> properties) {
if(properties.get("name") != null) {
sp.setName(properties.get("name"));
} else {
sp.setName("");
}
// process on-entry and on-exit actions as custom elements
if(properties.get("onentryactions") != null && properties.get("onentryactions").length() > 0) {
String[] allActions = properties.get("onentryactions").split( "\\|\\s*" );
for(String action : allActions) {
OnEntryScriptType onEntryScript = DroolsFactory.eINSTANCE.createOnEntryScriptType();
onEntryScript.setScript(action);
String scriptLanguage = "";
if(properties.get("script_language").equals("java")) {
scriptLanguage = "http://www.java.com/java";
} else if(properties.get("script_language").equals("mvel")) {
scriptLanguage = "http://www.mvel.org/2.0";
} else {
// default to java
scriptLanguage = "http://www.java.com/java";
}
onEntryScript.setScriptFormat(scriptLanguage);
if(sp.getExtensionValues() == null || sp.getExtensionValues().size() < 1) {
ExtensionAttributeValue extensionElement = Bpmn2Factory.eINSTANCE.createExtensionAttributeValue();
sp.getExtensionValues().add(extensionElement);
}
FeatureMap.Entry extensionElementEntry = new SimpleFeatureMapEntry(
(Internal) DroolsPackage.Literals.DOCUMENT_ROOT__ON_ENTRY_SCRIPT, onEntryScript);
sp.getExtensionValues().get(0).getValue().add(extensionElementEntry);
}
}
if(properties.get("onexitactions") != null && properties.get("onexitactions").length() > 0) {
String[] allActions = properties.get("onexitactions").split( "\\|\\s*" );
for(String action : allActions) {
OnExitScriptType onExitScript = DroolsFactory.eINSTANCE.createOnExitScriptType();
onExitScript.setScript(action);
String scriptLanguage = "";
if(properties.get("script_language").equals("java")) {
scriptLanguage = "http://www.java.com/java";
} else if(properties.get("script_language").equals("mvel")) {
scriptLanguage = "http://www.mvel.org/2.0";
} else {
// default to java
scriptLanguage = "http://www.java.com/java";
}
onExitScript.setScriptFormat(scriptLanguage);
if(sp.getExtensionValues() == null || sp.getExtensionValues().size() < 1) {
ExtensionAttributeValue extensionElement = Bpmn2Factory.eINSTANCE.createExtensionAttributeValue();
sp.getExtensionValues().add(extensionElement);
}
FeatureMap.Entry extensionElementEntry = new SimpleFeatureMapEntry(
(Internal) DroolsPackage.Literals.DOCUMENT_ROOT__ON_EXIT_SCRIPT, onExitScript);
sp.getExtensionValues().get(0).getValue().add(extensionElementEntry);
}
}
// data input set
if(properties.get("datainputset") != null && properties.get("datainputset").length() > 0) {
String[] allDataInputs = properties.get("datainputset").split( ",\\s*" );
if(sp.getIoSpecification() == null) {
InputOutputSpecification iospec = Bpmn2Factory.eINSTANCE.createInputOutputSpecification();
sp.setIoSpecification(iospec);
}
InputSet inset = Bpmn2Factory.eINSTANCE.createInputSet();
for(String dataInput : allDataInputs) {
DataInput nextInput = Bpmn2Factory.eINSTANCE.createDataInput();
nextInput.setId(sp.getId() + "_" + dataInput + "Input");
nextInput.setName(dataInput);
sp.getIoSpecification().getDataInputs().add(nextInput);
inset.getDataInputRefs().add(nextInput);
}
sp.getIoSpecification().getInputSets().add(inset);
} else {
if(sp.getIoSpecification() != null) {
sp.getIoSpecification().getInputSets().add(Bpmn2Factory.eINSTANCE.createInputSet());
}
}
// data output set
if(properties.get("dataoutputset") != null && properties.get("dataoutputset").length() > 0) {
String[] allDataOutputs = properties.get("dataoutputset").split( ",\\s*" );
if(sp.getIoSpecification() == null) {
InputOutputSpecification iospec = Bpmn2Factory.eINSTANCE.createInputOutputSpecification();
sp.setIoSpecification(iospec);
}
OutputSet outset = Bpmn2Factory.eINSTANCE.createOutputSet();
for(String dataOutput : allDataOutputs) {
DataOutput nextOut = Bpmn2Factory.eINSTANCE.createDataOutput();
nextOut.setId(sp.getId() + "_" + dataOutput + "Output");
nextOut.setName(dataOutput);
sp.getIoSpecification().getDataOutputs().add(nextOut);
outset.getDataOutputRefs().add(nextOut);
}
sp.getIoSpecification().getOutputSets().add(outset);
} else {
if(sp.getIoSpecification() != null) {
sp.getIoSpecification().getOutputSets().add(Bpmn2Factory.eINSTANCE.createOutputSet());
}
}
// assignments
if(properties.get("assignments") != null && properties.get("assignments").length() > 0 && sp.getIoSpecification() != null) {
String[] allAssignments = properties.get("assignments").split( ",\\s*" );
for(String assignment : allAssignments) {
if(assignment.contains("=")) {
String[] assignmentParts = assignment.split( "=\\s*" );
DataInputAssociation dia = Bpmn2Factory.eINSTANCE.createDataInputAssociation();
boolean foundTaskName = false;
if(sp.getIoSpecification() != null && sp.getIoSpecification().getDataOutputs() != null) {
List<DataInput> dataInputs = sp.getIoSpecification().getDataInputs();
for(DataInput di : dataInputs) {
if(di.getId().equals(sp.getId() + "_" + assignmentParts[0] + "Input")) {
dia.setTargetRef(di);
if(di.getName().equals("TaskName")) {
foundTaskName = true;
break;
}
}
}
}
Assignment a = Bpmn2Factory.eINSTANCE.createAssignment();
FormalExpression fromExpression = Bpmn2Factory.eINSTANCE.createFormalExpression();
if(assignmentParts.length > 1) {
fromExpression.setBody(assignmentParts[1]);
} else {
fromExpression.setBody("");
}
FormalExpression toExpression = Bpmn2Factory.eINSTANCE.createFormalExpression();
toExpression.setBody(dia.getTargetRef().getId());
a.setFrom(fromExpression);
a.setTo(toExpression);
dia.getAssignment().add(a);
sp.getDataInputAssociations().add(dia);
} else if(assignment.contains("<->")) {
String[] assignmentParts = assignment.split( "<->\\s*" );
DataInputAssociation dia = Bpmn2Factory.eINSTANCE.createDataInputAssociation();
DataOutputAssociation doa = Bpmn2Factory.eINSTANCE.createDataOutputAssociation();
ItemAwareElement ie = Bpmn2Factory.eINSTANCE.createItemAwareElement();
ie.setId(assignmentParts[0]);
dia.getSourceRef().add(ie);
doa.setTargetRef(ie);
List<DataInput> dataInputs = sp.getIoSpecification().getDataInputs();
for(DataInput di : dataInputs) {
if(di.getId().equals(sp.getId() + "_" + assignmentParts[1] + "Input")) {
dia.setTargetRef(di);
break;
}
}
List<DataOutput> dataOutputs = sp.getIoSpecification().getDataOutputs();
for(DataOutput dout : dataOutputs) {
if(dout.getId().equals(sp.getId() + "_" + assignmentParts[1] + "Output")) {
doa.getSourceRef().add(dout);
break;
}
}
sp.getDataInputAssociations().add(dia);
sp.getDataOutputAssociations().add(doa);
} else if(assignment.contains("->")) {
String[] assignmentParts = assignment.split( "->\\s*" );
// we need to check if this is an data input or data output assignment
boolean leftHandAssignMentIsDO = false;
List<DataOutput> dataOutputs = sp.getIoSpecification().getDataOutputs();
for(DataOutput dout : dataOutputs) {
if(dout.getId().equals(sp.getId() + "_" + assignmentParts[0] + "Output")) {
leftHandAssignMentIsDO = true;
break;
}
}
if(leftHandAssignMentIsDO) {
// doing data output
DataOutputAssociation doa = Bpmn2Factory.eINSTANCE.createDataOutputAssociation();
for(DataOutput dout : dataOutputs) {
if(dout.getId().equals(sp.getId() + "_" + assignmentParts[0] + "Output")) {
doa.getSourceRef().add(dout);
break;
}
}
ItemAwareElement ie = Bpmn2Factory.eINSTANCE.createItemAwareElement();
ie.setId(assignmentParts[1]);
doa.setTargetRef(ie);
sp.getDataOutputAssociations().add(doa);
} else {
// doing data input
DataInputAssociation dia = Bpmn2Factory.eINSTANCE.createDataInputAssociation();
// association from process var to dataInput var
ItemAwareElement ie = Bpmn2Factory.eINSTANCE.createItemAwareElement();
ie.setId(assignmentParts[0]);
dia.getSourceRef().add(ie);
List<DataInput> dataInputs = sp.getIoSpecification().getDataInputs();
for(DataInput di : dataInputs) {
if(di.getId().equals(sp.getId() + "_" + assignmentParts[1] + "Input")) {
dia.setTargetRef(di);
break;
}
}
sp.getDataInputAssociations().add(dia);
}
} else {
// TODO throw exception here?
}
}
}
// loop characteristics
if(properties.get("collectionexpression") != null && properties.get("collectionexpression").length() > 0
&& properties.get("variablename") != null && properties.get("variablename").length() > 0) {
if(sp.getIoSpecification() == null) {
InputOutputSpecification iospec = Bpmn2Factory.eINSTANCE.createInputOutputSpecification();
sp.setIoSpecification(iospec);
} else {
sp.getIoSpecification().getDataInputs().clear();
sp.getIoSpecification().getDataOutputs().clear();
sp.getIoSpecification().getInputSets().clear();
sp.getIoSpecification().getOutputSets().clear();
sp.getDataInputAssociations().clear();
sp.getDataOutputAssociations().clear();
}
InputSet inset = Bpmn2Factory.eINSTANCE.createInputSet();
DataInput multiInput = Bpmn2Factory.eINSTANCE.createDataInput();
multiInput.setId(sp.getId() + "_" + "input");
multiInput.setName("MultiInstanceInput");
sp.getIoSpecification().getDataInputs().add(multiInput);
inset.getDataInputRefs().add(multiInput);
sp.getIoSpecification().getInputSets().add(inset);
sp.getIoSpecification().getOutputSets().add(Bpmn2Factory.eINSTANCE.createOutputSet());
DataInputAssociation dia = Bpmn2Factory.eINSTANCE.createDataInputAssociation();
ItemAwareElement ie = Bpmn2Factory.eINSTANCE.createItemAwareElement();
ie.setId(properties.get("collectionexpression"));
dia.getSourceRef().add(ie);
dia.setTargetRef(multiInput);
sp.getDataInputAssociations().add(dia);
MultiInstanceLoopCharacteristics loopCharacteristics = Bpmn2Factory.eINSTANCE.createMultiInstanceLoopCharacteristics();
loopCharacteristics.setLoopDataInputRef(multiInput);
DataInput din = Bpmn2Factory.eINSTANCE.createDataInput();
din.setId(properties.get("variablename"));
ItemDefinition itemDef = Bpmn2Factory.eINSTANCE.createItemDefinition();
itemDef.setId(sp.getId() + "_" + "multiInstanceItemType");
din.setItemSubjectRef(itemDef);
_subprocessItemDefs.put(itemDef.getId(), itemDef);
loopCharacteristics.setInputDataItem(din);
sp.setLoopCharacteristics(loopCharacteristics);
}
// properties
if(properties.get("vardefs") != null && properties.get("vardefs").length() > 0) {
String[] vardefs = properties.get("vardefs").split( ",\\s*" );
for(String vardef : vardefs) {
Property prop = Bpmn2Factory.eINSTANCE.createProperty();
ItemDefinition itemdef = Bpmn2Factory.eINSTANCE.createItemDefinition();
// check if we define a structure ref in the definition
if(vardef.contains(":")) {
String[] vardefParts = vardef.split( ":\\s*" );
prop.setId(vardefParts[0]);
itemdef.setId("_" + prop.getId() + "Item");
itemdef.setStructureRef(vardefParts[1]);
} else {
prop.setId(vardef);
itemdef.setId("_" + prop.getId() + "Item");
}
prop.setItemSubjectRef(itemdef);
sp.getProperties().add(prop);
_subprocessItemDefs.put(itemdef.getId(), itemdef);
}
}
}
private void applyAdHocSubProcessProperties(AdHocSubProcess ahsp, Map<String, String> properties) {
if(properties.get("adhocordering") != null) {
if(properties.get("adhocordering") == null || properties.get("adhocordering").equals("Parallel")) {
ahsp.setOrdering(AdHocOrdering.PARALLEL);
} else {
ahsp.setOrdering(AdHocOrdering.SEQUENTIAL);
}
}
}
private void applyEndEventProperties(EndEvent ee, Map<String, String> properties) {
ee.setId(properties.get("resourceId"));
if(properties.get("name") != null) {
ee.setName(properties.get("name"));
} else {
ee.setName("");
}
}
private void applyAssociationProperties(Association association, Map<String, String> properties) {
if(properties.get("type") != null) {
ExtendedMetaData metadata = ExtendedMetaData.INSTANCE;
EAttributeImpl extensionAttribute = (EAttributeImpl) metadata.demandFeature(
"http://www.jboss.org/drools", "type", false, false);
EStructuralFeatureImpl.SimpleFeatureMapEntry extensionEntry = new EStructuralFeatureImpl.SimpleFeatureMapEntry(extensionAttribute,
properties.get("type"));
association.getAnyAttribute().add(extensionEntry);
}
}
private void applyStartEventProperties(StartEvent se, Map<String, String> properties) {
if(properties.get("name") != null) {
se.setName(properties.get("name"));
} else {
se.setName("");
}
}
private void applyMessageProperties(Message msg, Map<String, String> properties) {
if(properties.get("name") != null) {
msg.setName(properties.get("name"));
msg.setId(properties.get("name") + "Message");
} else {
msg.setName("");
msg.setId("Message");
}
}
private void applyDataStoreProperties(DataStore da, Map<String, String> properties) {
if(properties.get("name") != null) {
da.setName(properties.get("name"));
} else {
da.setName("");
}
}
private void applyDataObjectProperties(DataObject da, Map<String, String> properties) {
if(properties.get("name") != null) {
da.setName(properties.get("name"));
} else {
da.setName("");
}
if(properties.get("type") != null && properties.get("type").length() > 0) {
ExtendedMetaData metadata = ExtendedMetaData.INSTANCE;
EAttributeImpl extensionAttribute = (EAttributeImpl) metadata.demandFeature(
"http://www.jboss.org/drools", "datype", false, false);
EStructuralFeatureImpl.SimpleFeatureMapEntry extensionEntry = new EStructuralFeatureImpl.SimpleFeatureMapEntry(extensionAttribute,
properties.get("type"));
da.getAnyAttribute().add(extensionEntry);
}
}
private void applyTextAnnotationProperties(TextAnnotation ta, Map<String, String> properties) {
if(properties.get("text") != null) {
ta.setText(properties.get("text"));
} else {
ta.setText("");
}
// default
ta.setTextFormat("text/plain");
}
private void applyGroupProperties(Group group, Map<String, String> properties) {
if(properties.get("name") != null) {
ExtendedMetaData metadata = ExtendedMetaData.INSTANCE;
EAttributeImpl extensionAttribute = (EAttributeImpl) metadata.demandFeature(
"http://www.jboss.org/drools", "categoryval", false, false);
EStructuralFeatureImpl.SimpleFeatureMapEntry extensionEntry = new EStructuralFeatureImpl.SimpleFeatureMapEntry(extensionAttribute,
properties.get("name"));
group.getAnyAttribute().add(extensionEntry);
}
}
private void applyEventProperties(Event event, Map<String, String> properties) {
if(properties.get("name") != null) {
event.setName(properties.get("name"));
} else {
event.setName("");
}
if (properties.get("auditing") != null && !"".equals(properties.get("auditing"))) {
Auditing audit = Bpmn2Factory.eINSTANCE.createAuditing();
audit.getDocumentation().add(createDocumentation(properties.get("auditing")));
event.setAuditing(audit);
}
if (properties.get("monitoring") != null && !"".equals(properties.get("monitoring"))) {
Monitoring monitoring = Bpmn2Factory.eINSTANCE.createMonitoring();
monitoring.getDocumentation().add(createDocumentation(properties.get("monitoring")));
event.setMonitoring(monitoring);
}
}
private void applyCatchEventProperties(CatchEvent event, Map<String, String> properties) {
if (properties.get("dataoutput") != null && !"".equals(properties.get("dataoutput"))) {
String[] allDataOutputs = properties.get("dataoutput").split( ",\\s*" );
OutputSet outSet = Bpmn2Factory.eINSTANCE.createOutputSet();
for(String dataOutput : allDataOutputs) {
DataOutput dataout = Bpmn2Factory.eINSTANCE.createDataOutput();
// we follow jbpm here to set the id
dataout.setId(event.getId() + "_" + dataOutput);
dataout.setName(dataOutput);
event.getDataOutputs().add(dataout);
// add to output set as well
outSet.getDataOutputRefs().add(dataout);
}
event.setOutputSet(outSet);
}
// data output associations
if (properties.get("dataoutputassociations") != null && !"".equals(properties.get("dataoutputassociations"))) {
String[] allAssociations = properties.get("dataoutputassociations").split( ",\\s*" );
for(String association : allAssociations) {
// data outputs are uni-directional
String[] associationParts = association.split( "->\\s*" );
DataOutputAssociation doa = Bpmn2Factory.eINSTANCE.createDataOutputAssociation();
// for source refs we loop through already defined data outputs
List<DataOutput> dataOutputs = event.getDataOutputs();
if(dataOutputs != null) {
for(DataOutput ddo : dataOutputs) {
if(ddo.getId().equals(event.getId() + "_" + associationParts[0])) {
doa.getSourceRef().add(ddo);
}
}
}
// since we dont have the process vars defined yet..need to improvise
ItemAwareElement e = Bpmn2Factory.eINSTANCE.createItemAwareElement();
e.setId(associationParts[1]);
doa.setTargetRef(e);
event.getDataOutputAssociation().add(doa);
}
}
try {
EventDefinition ed = event.getEventDefinitions().get(0);
if(ed instanceof TimerEventDefinition) {
if(properties.get("timedate") != null && !"".equals(properties.get("timedate"))) {
FormalExpression timeDateExpression = Bpmn2Factory.eINSTANCE.createFormalExpression();
timeDateExpression.setBody(properties.get("timedate"));
((TimerEventDefinition) event.getEventDefinitions().get(0)).setTimeDate(timeDateExpression);
}
if(properties.get("timeduration") != null && !"".equals(properties.get("timeduration"))) {
FormalExpression timeDurationExpression = Bpmn2Factory.eINSTANCE.createFormalExpression();
timeDurationExpression.setBody(properties.get("timeduration"));
((TimerEventDefinition) event.getEventDefinitions().get(0)).setTimeDuration(timeDurationExpression);
}
if(properties.get("timecycle") != null && !"".equals(properties.get("timecycle"))) {
FormalExpression timeCycleExpression = Bpmn2Factory.eINSTANCE.createFormalExpression();
timeCycleExpression.setBody(properties.get("timecycle"));
if(properties.get("timecyclelanguage") != null && properties.get("timecyclelanguage").length() > 0) {
timeCycleExpression.setLanguage(properties.get("timecyclelanguage"));
}
((TimerEventDefinition) event.getEventDefinitions().get(0)).setTimeCycle(timeCycleExpression);
}
} else if (ed instanceof SignalEventDefinition) {
if(properties.get("signalref") != null && !"".equals(properties.get("signalref"))) {
ExtendedMetaData metadata = ExtendedMetaData.INSTANCE;
EAttributeImpl extensionAttribute = (EAttributeImpl) metadata.demandFeature(
"http://www.jboss.org/drools", "signalrefname", false, false);
EStructuralFeatureImpl.SimpleFeatureMapEntry extensionEntry = new EStructuralFeatureImpl.SimpleFeatureMapEntry(extensionAttribute,
properties.get("signalref"));
((SignalEventDefinition) event.getEventDefinitions().get(0)).getAnyAttribute().add(extensionEntry);
}
} else if(ed instanceof ErrorEventDefinition) {
if(properties.get("errorref") != null && !"".equals(properties.get("errorref"))) {
ExtendedMetaData metadata = ExtendedMetaData.INSTANCE;
EAttributeImpl extensionAttribute = (EAttributeImpl) metadata.demandFeature(
"http://www.jboss.org/drools", "erefname", false, false);
EStructuralFeatureImpl.SimpleFeatureMapEntry extensionEntry = new EStructuralFeatureImpl.SimpleFeatureMapEntry(extensionAttribute,
properties.get("errorref"));
((ErrorEventDefinition) event.getEventDefinitions().get(0)).getAnyAttribute().add(extensionEntry);
}
} else if(ed instanceof ConditionalEventDefinition) {
FormalExpression conditionExpression = Bpmn2Factory.eINSTANCE.createFormalExpression();
if(properties.get("conditionlanguage") != null && !"".equals(properties.get("conditionlanguage"))) {
// currently supporting drools and mvel
String languageStr;
if(properties.get("conditionlanguage").equals("drools")) {
languageStr = "http://www.jboss.org/drools/rule";
} else if(properties.get("conditionlanguage").equals("mvel")) {
languageStr = "http://www.mvel.org/2.0";
} else {
// default to drools
languageStr = "http://www.jboss.org/drools/rule";
}
conditionExpression.setLanguage(languageStr);
}
if(properties.get("conditionexpression") != null && !"".equals(properties.get("conditionexpression"))) {
conditionExpression.setBody(properties.get("conditionexpression"));
}
((ConditionalEventDefinition) event.getEventDefinitions().get(0)).setCondition(conditionExpression);
} else if(ed instanceof EscalationEventDefinition) {
if(properties.get("escalationcode") != null && !"".equals(properties.get("escalationcode"))) {
ExtendedMetaData metadata = ExtendedMetaData.INSTANCE;
EAttributeImpl extensionAttribute = (EAttributeImpl) metadata.demandFeature(
"http://www.jboss.org/drools", "esccode", false, false);
EStructuralFeatureImpl.SimpleFeatureMapEntry extensionEntry = new EStructuralFeatureImpl.SimpleFeatureMapEntry(extensionAttribute,
properties.get("escalationcode"));
((EscalationEventDefinition) event.getEventDefinitions().get(0)).getAnyAttribute().add(extensionEntry);
}
} else if(ed instanceof MessageEventDefinition) {
if(properties.get("messageref") != null && !"".equals(properties.get("messageref"))) {
ExtendedMetaData metadata = ExtendedMetaData.INSTANCE;
EAttributeImpl extensionAttribute = (EAttributeImpl) metadata.demandFeature(
"http://www.jboss.org/drools", "msgref", false, false);
EStructuralFeatureImpl.SimpleFeatureMapEntry extensionEntry = new EStructuralFeatureImpl.SimpleFeatureMapEntry(extensionAttribute,
properties.get("messageref"));
((MessageEventDefinition) event.getEventDefinitions().get(0)).getAnyAttribute().add(extensionEntry);
}
} else if(ed instanceof CompensateEventDefinition) {
if(properties.get("activityref") != null && !"".equals(properties.get("activityref"))) {
ExtendedMetaData metadata = ExtendedMetaData.INSTANCE;
EAttributeImpl extensionAttribute = (EAttributeImpl) metadata.demandFeature(
"http://www.jboss.org/drools", "actrefname", false, false);
EStructuralFeatureImpl.SimpleFeatureMapEntry extensionEntry = new EStructuralFeatureImpl.SimpleFeatureMapEntry(extensionAttribute,
properties.get("activityref"));
((CompensateEventDefinition) event.getEventDefinitions().get(0)).getAnyAttribute().add(extensionEntry);
}
}
} catch (IndexOutOfBoundsException e) {
// TODO we dont want to barf here as test for example do not define event definitions in the bpmn2....
}
}
private void applyThrowEventProperties(ThrowEvent event, Map<String, String> properties) {
if (properties.get("datainput") != null && !"".equals(properties.get("datainput"))) {
String[] allDataInputs = properties.get("datainput").split( ",\\s*" );
InputSet inset = Bpmn2Factory.eINSTANCE.createInputSet();
for(String dataInput : allDataInputs) {
DataInput datain = Bpmn2Factory.eINSTANCE.createDataInput();
// we follow jbpm here to set the id
datain.setId(event.getId() + "_" + dataInput);
datain.setName(dataInput);
event.getDataInputs().add(datain);
// add to input set as well
inset.getDataInputRefs().add(datain);
}
event.setInputSet(inset);
}
// data input associations
if (properties.get("datainputassociations") != null && !"".equals(properties.get("datainputassociations"))) {
String[] allAssociations = properties.get("datainputassociations").split( ",\\s*" );
for(String association : allAssociations) {
// data inputs are uni-directional
String[] associationParts = association.split( "->\\s*" );
DataInputAssociation dia = Bpmn2Factory.eINSTANCE.createDataInputAssociation();
// since we dont have the process vars defined yet..need to improvise
ItemAwareElement e = Bpmn2Factory.eINSTANCE.createItemAwareElement();
e.setId(associationParts[0]);
dia.getSourceRef().add(e);
// for target ref we loop through already defined data inputs
List<DataInput> dataInputs = event.getDataInputs();
if(dataInputs != null) {
for(DataInput di : dataInputs) {
if(di.getId().equals(event.getId() + "_" + associationParts[1])) {
dia.setTargetRef(di);
break;
}
}
}
event.getDataInputAssociation().add(dia);
}
}
try {
EventDefinition ed = event.getEventDefinitions().get(0);
if(ed instanceof TimerEventDefinition) {
if(properties.get("timedate") != null && !"".equals(properties.get("timedate"))) {
FormalExpression timeDateExpression = Bpmn2Factory.eINSTANCE.createFormalExpression();
timeDateExpression.setBody(properties.get("timedate"));
((TimerEventDefinition) event.getEventDefinitions().get(0)).setTimeDate(timeDateExpression);
}
if(properties.get("timeduration") != null && !"".equals(properties.get("timeduration"))) {
FormalExpression timeDurationExpression = Bpmn2Factory.eINSTANCE.createFormalExpression();
timeDurationExpression.setBody(properties.get("timeduration"));
((TimerEventDefinition) event.getEventDefinitions().get(0)).setTimeDuration(timeDurationExpression);
}
if(properties.get("timecycle") != null && !"".equals(properties.get("timecycle"))) {
FormalExpression timeCycleExpression = Bpmn2Factory.eINSTANCE.createFormalExpression();
timeCycleExpression.setBody(properties.get("timecycle"));
if(properties.get("timecyclelanguage") != null && properties.get("timecyclelanguage").length() > 0) {
timeCycleExpression.setLanguage(properties.get("timecyclelanguage"));
}
((TimerEventDefinition) event.getEventDefinitions().get(0)).setTimeCycle(timeCycleExpression);
}
} else if (ed instanceof SignalEventDefinition) {
if(properties.get("signalref") != null && !"".equals(properties.get("signalref"))) {
ExtendedMetaData metadata = ExtendedMetaData.INSTANCE;
EAttributeImpl extensionAttribute = (EAttributeImpl) metadata.demandFeature(
"http://www.jboss.org/drools", "signalrefname", false, false);
EStructuralFeatureImpl.SimpleFeatureMapEntry extensionEntry = new EStructuralFeatureImpl.SimpleFeatureMapEntry(extensionAttribute,
properties.get("signalref"));
((SignalEventDefinition) event.getEventDefinitions().get(0)).getAnyAttribute().add(extensionEntry);
}
} else if(ed instanceof ErrorEventDefinition) {
if(properties.get("errorref") != null && !"".equals(properties.get("errorref"))) {
ExtendedMetaData metadata = ExtendedMetaData.INSTANCE;
EAttributeImpl extensionAttribute = (EAttributeImpl) metadata.demandFeature(
"http://www.jboss.org/drools", "erefname", false, false);
EStructuralFeatureImpl.SimpleFeatureMapEntry extensionEntry = new EStructuralFeatureImpl.SimpleFeatureMapEntry(extensionAttribute,
properties.get("errorref"));
((ErrorEventDefinition) event.getEventDefinitions().get(0)).getAnyAttribute().add(extensionEntry);
}
} else if(ed instanceof ConditionalEventDefinition) {
FormalExpression conditionExpression = Bpmn2Factory.eINSTANCE.createFormalExpression();
if(properties.get("conditionlanguage") != null && !"".equals(properties.get("conditionlanguage"))) {
// currently supporting drools and mvel
String languageStr;
if(properties.get("conditionlanguage").equals("drools")) {
languageStr = "http://www.jboss.org/drools/rule";
} else if(properties.get("conditionlanguage").equals("mvel")) {
languageStr = "http://www.mvel.org/2.0";
} else {
// default to drools
languageStr = "http://www.jboss.org/drools/rule";
}
conditionExpression.setLanguage(languageStr);
}
if(properties.get("conditionexpression") != null && !"".equals(properties.get("conditionexpression"))) {
conditionExpression.setBody(properties.get("conditionexpression"));
}
((ConditionalEventDefinition) event.getEventDefinitions().get(0)).setCondition(conditionExpression);
} else if(ed instanceof EscalationEventDefinition) {
if(properties.get("escalationcode") != null && !"".equals(properties.get("escalationcode"))) {
ExtendedMetaData metadata = ExtendedMetaData.INSTANCE;
EAttributeImpl extensionAttribute = (EAttributeImpl) metadata.demandFeature(
"http://www.jboss.org/drools", "esccode", false, false);
EStructuralFeatureImpl.SimpleFeatureMapEntry extensionEntry = new EStructuralFeatureImpl.SimpleFeatureMapEntry(extensionAttribute,
properties.get("escalationcode"));
((EscalationEventDefinition) event.getEventDefinitions().get(0)).getAnyAttribute().add(extensionEntry);
}
} else if(ed instanceof MessageEventDefinition) {
if(properties.get("messageref") != null && !"".equals(properties.get("messageref"))) {
ExtendedMetaData metadata = ExtendedMetaData.INSTANCE;
EAttributeImpl extensionAttribute = (EAttributeImpl) metadata.demandFeature(
"http://www.jboss.org/drools", "msgref", false, false);
EStructuralFeatureImpl.SimpleFeatureMapEntry extensionEntry = new EStructuralFeatureImpl.SimpleFeatureMapEntry(extensionAttribute,
properties.get("messageref"));
((MessageEventDefinition) event.getEventDefinitions().get(0)).getAnyAttribute().add(extensionEntry);
}
} else if(ed instanceof CompensateEventDefinition) {
if(properties.get("activityref") != null && !"".equals(properties.get("activityref"))) {
ExtendedMetaData metadata = ExtendedMetaData.INSTANCE;
EAttributeImpl extensionAttribute = (EAttributeImpl) metadata.demandFeature(
"http://www.jboss.org/drools", "actrefname", false, false);
EStructuralFeatureImpl.SimpleFeatureMapEntry extensionEntry = new EStructuralFeatureImpl.SimpleFeatureMapEntry(extensionAttribute,
properties.get("activityref"));
((CompensateEventDefinition) event.getEventDefinitions().get(0)).getAnyAttribute().add(extensionEntry);
}
}
} catch (IndexOutOfBoundsException e) {
// TODO we dont want to barf here as test for example do not define event definitions in the bpmn2....
}
}
private void applyGlobalTaskProperties(GlobalTask globalTask, Map<String, String> properties) {
if(properties.get("name") != null) {
globalTask.setName(properties.get("name"));
} else {
globalTask.setName("");
}
}
private void applyBaseElementProperties(BaseElement baseElement, Map<String, String> properties) {
if (properties.get("documentation") != null && !"".equals(properties.get("documentation"))) {
baseElement.getDocumentation().add(createDocumentation(properties.get("documentation")));
}
if(baseElement.getId() == null || baseElement.getId().length() < 1) {
baseElement.setId(properties.get("resourceId"));
}
if(properties.get("bgcolor") != null && properties.get("bgcolor").length() > 0) {
if(!properties.get("bgcolor").equals(defaultBgColor)) {
ExtendedMetaData metadata = ExtendedMetaData.INSTANCE;
EAttributeImpl extensionAttribute = (EAttributeImpl) metadata.demandFeature(
"http://www.jboss.org/drools", "bgcolor", false, false);
EStructuralFeatureImpl.SimpleFeatureMapEntry extensionEntry = new EStructuralFeatureImpl.SimpleFeatureMapEntry(extensionAttribute,
properties.get("bgcolor"));
baseElement.getAnyAttribute().add(extensionEntry);
}
}
}
private void applyDefinitionProperties(Definitions def, Map<String, String> properties) {
def.setTypeLanguage(properties.get("typelanguage"));
//def.setTargetNamespace(properties.get("targetnamespace"));
def.setTargetNamespace("http://www.omg.org/bpmn20");
def.setExpressionLanguage(properties.get("expressionlanguage"));
ExtendedMetaData metadata = ExtendedMetaData.INSTANCE;
EAttributeImpl extensionAttribute = (EAttributeImpl) metadata.demandFeature(
"xsi", "schemaLocation", false, false);
EStructuralFeatureImpl.SimpleFeatureMapEntry extensionEntry = new EStructuralFeatureImpl.SimpleFeatureMapEntry(extensionAttribute,
"http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd");
def.getAnyAttribute().add(extensionEntry);
//_currentResource.getContents().add(def);// hook the definitions object to the resource early.
}
private void applyProcessProperties(Process process, Map<String, String> properties) {
if(properties.get("name") != null) {
process.setName(properties.get("name"));
} else {
process.setName("");
}
if (properties.get("auditing") != null && !"".equals(properties.get("auditing"))) {
Auditing audit = Bpmn2Factory.eINSTANCE.createAuditing();
audit.getDocumentation().add(createDocumentation(properties.get("auditing")));
process.setAuditing(audit);
}
process.setProcessType(ProcessType.getByName(properties.get("processtype")));
process.setIsClosed(Boolean.parseBoolean(properties.get("isclosed")));
process.setIsExecutable(Boolean.parseBoolean(properties.get("executable")));
// get the drools-specific extension packageName attribute to Process if defined
if(properties.get("package") != null && properties.get("package").length() > 0) {
ExtendedMetaData metadata = ExtendedMetaData.INSTANCE;
EAttributeImpl extensionAttribute = (EAttributeImpl) metadata.demandFeature(
"http://www.jboss.org/drools", "packageName", false, false);
EStructuralFeatureImpl.SimpleFeatureMapEntry extensionEntry = new EStructuralFeatureImpl.SimpleFeatureMapEntry(extensionAttribute,
properties.get("package"));
process.getAnyAttribute().add(extensionEntry);
}
// add version attrbute to process
if(properties.get("version") != null && properties.get("version").length() > 0) {
ExtendedMetaData metadata = ExtendedMetaData.INSTANCE;
EAttributeImpl extensionAttribute = (EAttributeImpl) metadata.demandFeature(
"http://www.jboss.org/drools", "version", false, false);
EStructuralFeatureImpl.SimpleFeatureMapEntry extensionEntry = new EStructuralFeatureImpl.SimpleFeatureMapEntry(extensionAttribute,
properties.get("version"));
process.getAnyAttribute().add(extensionEntry);
}
if (properties.get("monitoring") != null && !"".equals(properties.get("monitoring"))) {
Monitoring monitoring = Bpmn2Factory.eINSTANCE.createMonitoring();
monitoring.getDocumentation().add(createDocumentation(properties.get("monitoring")));
process.setMonitoring(monitoring);
}
// import extension elements
if(properties.get("imports") != null && properties.get("imports").length() > 0) {
String[] allImports = properties.get("imports").split( ",\\s*" );
for(String importStr : allImports) {
ImportType importType = DroolsFactory.eINSTANCE.createImportType();
importType.setName(importStr);
if(process.getExtensionValues() == null || process.getExtensionValues().size() < 1) {
ExtensionAttributeValue extensionElement = Bpmn2Factory.eINSTANCE.createExtensionAttributeValue();
process.getExtensionValues().add(extensionElement);
}
FeatureMap.Entry extensionElementEntry = new SimpleFeatureMapEntry(
(Internal) DroolsPackage.Literals.DOCUMENT_ROOT__IMPORT, importType);
process.getExtensionValues().get(0).getValue().add(extensionElementEntry);
}
}
// globals extension elements
if(properties.get("globals") != null && properties.get("globals").length() > 0) {
String[] allGlobals = properties.get("globals").split( ",\\s*" );
for(String globalStr : allGlobals) {
String[] globalParts = globalStr.split( ":\\s*" ); // identifier:type
if(globalParts.length == 2) {
GlobalType globalType = DroolsFactory.eINSTANCE.createGlobalType();
globalType.setIdentifier(globalParts[0]);
globalType.setType(globalParts[1]);
if(process.getExtensionValues() == null || process.getExtensionValues().size() < 1) {
ExtensionAttributeValue extensionElement = Bpmn2Factory.eINSTANCE.createExtensionAttributeValue();
process.getExtensionValues().add(extensionElement);
}
FeatureMap.Entry extensionElementEntry = new SimpleFeatureMapEntry(
(Internal) DroolsPackage.Literals.DOCUMENT_ROOT__GLOBAL, globalType);
process.getExtensionValues().get(0).getValue().add(extensionElementEntry);
}
}
}
}
private void applyBusinessRuleTaskProperties(BusinessRuleTask task, Map<String, String> properties) {
if(properties.get("name") != null) {
task.setName(properties.get("name"));
} else {
task.setName("");
}
if(properties.get("ruleflowgroup") != null && properties.get("ruleflowgroup").length() > 0) {
// add droolsjbpm-specific attribute "ruleFlowGroup"
ExtendedMetaData metadata = ExtendedMetaData.INSTANCE;
EAttributeImpl extensionAttribute = (EAttributeImpl) metadata.demandFeature(
"http://www.jboss.org/drools", "ruleFlowGroup", false, false);
EStructuralFeatureImpl.SimpleFeatureMapEntry extensionEntry = new EStructuralFeatureImpl.SimpleFeatureMapEntry(extensionAttribute,
properties.get("ruleflowgroup"));
task.getAnyAttribute().add(extensionEntry);
}
}
private void applyScriptTaskProperties(ScriptTask scriptTask, Map<String, String> properties) {
if(properties.get("name") != null) {
scriptTask.setName(properties.get("name"));
} else {
scriptTask.setName("");
}
if(properties.get("script") != null && properties.get("script").length() > 0) {
scriptTask.setScript(properties.get("script"));
}
if(properties.get("script_language") != null && properties.get("script_language").length() > 0) {
String scriptLanguage = "";
if(properties.get("script_language").equals("java")) {
scriptLanguage = "http://www.java.com/java";
} else if(properties.get("script_language").equals("mvel")) {
scriptLanguage = "http://www.mvel.org/2.0";
} else {
// default to java
scriptLanguage = "http://www.java.com/java";
}
scriptTask.setScriptFormat(scriptLanguage);
}
}
public void applyServiceTaskProperties(ServiceTask serviceTask, Map<String, String> properties) {
if(properties.get("interface") != null) {
serviceTask.setImplementation("Other");
ExtendedMetaData metadata = ExtendedMetaData.INSTANCE;
EAttributeImpl extensionAttribute = (EAttributeImpl) metadata.demandFeature(
"http://www.jboss.org/drools", "servicetaskinterface", false, false);
EStructuralFeatureImpl.SimpleFeatureMapEntry extensionEntry = new EStructuralFeatureImpl.SimpleFeatureMapEntry(extensionAttribute,
properties.get("interface"));
serviceTask.getAnyAttribute().add(extensionEntry);
}
if(properties.get("operation") != null) {
ExtendedMetaData metadata = ExtendedMetaData.INSTANCE;
EAttributeImpl extensionAttribute = (EAttributeImpl) metadata.demandFeature(
"http://www.jboss.org/drools", "servicetaskoperation", false, false);
EStructuralFeatureImpl.SimpleFeatureMapEntry extensionEntry = new EStructuralFeatureImpl.SimpleFeatureMapEntry(extensionAttribute,
properties.get("operation"));
serviceTask.getAnyAttribute().add(extensionEntry);
}
}
public void applyReceiveTaskProperties(ReceiveTask receiveTask, Map<String, String> properties) {
if(properties.get("messageref") != null && properties.get("messageref").length() > 0) {
ExtendedMetaData metadata = ExtendedMetaData.INSTANCE;
EAttributeImpl extensionAttribute = (EAttributeImpl) metadata.demandFeature(
"http://www.jboss.org/drools", "msgref", false, false);
EStructuralFeatureImpl.SimpleFeatureMapEntry extensionEntry = new EStructuralFeatureImpl.SimpleFeatureMapEntry(extensionAttribute,
properties.get("messageref"));
receiveTask.getAnyAttribute().add(extensionEntry);
}
receiveTask.setImplementation("Other");
}
public void applySendTaskProperties(SendTask sendTask, Map<String, String> properties) {
if(properties.get("messageref") != null && properties.get("messageref").length() > 0) {
ExtendedMetaData metadata = ExtendedMetaData.INSTANCE;
EAttributeImpl extensionAttribute = (EAttributeImpl) metadata.demandFeature(
"http://www.jboss.org/drools", "msgref", false, false);
EStructuralFeatureImpl.SimpleFeatureMapEntry extensionEntry = new EStructuralFeatureImpl.SimpleFeatureMapEntry(extensionAttribute,
properties.get("messageref"));
sendTask.getAnyAttribute().add(extensionEntry);
}
sendTask.setImplementation("Other");
}
private void applyLaneProperties(Lane lane, Map<String, String> properties) {
if(properties.get("name") != null) {
lane.setName(properties.get("name"));
} else {
lane.setName("");
}
}
private void applyCallActivityProperties(CallActivity callActivity, Map<String, String> properties) {
if(properties.get("name") != null) {
callActivity.setName(properties.get("name"));
} else {
callActivity.setName("");
}
if(properties.get("independent") != null && properties.get("independent").length() > 0) {
ExtendedMetaData metadata = ExtendedMetaData.INSTANCE;
EAttributeImpl extensionAttribute = (EAttributeImpl) metadata.demandFeature(
"http://www.jboss.org/drools", "independent", false, false);
EStructuralFeatureImpl.SimpleFeatureMapEntry extensionEntry = new EStructuralFeatureImpl.SimpleFeatureMapEntry(extensionAttribute,
properties.get("independent"));
callActivity.getAnyAttribute().add(extensionEntry);
}
if(properties.get("waitforcompletion") != null && properties.get("waitforcompletion").length() > 0) {
ExtendedMetaData metadata = ExtendedMetaData.INSTANCE;
EAttributeImpl extensionAttribute = (EAttributeImpl) metadata.demandFeature(
"http://www.jboss.org/drools", "waitForCompletion", false, false);
EStructuralFeatureImpl.SimpleFeatureMapEntry extensionEntry = new EStructuralFeatureImpl.SimpleFeatureMapEntry(extensionAttribute,
properties.get("waitforcompletion"));
callActivity.getAnyAttribute().add(extensionEntry);
}
if(properties.get("calledelement") != null && properties.get("calledelement").length() > 0) {
callActivity.setCalledElement(properties.get("calledelement"));
}
//callActivity data input set
if(properties.get("datainputset") != null && properties.get("datainputset").length() > 0) {
String[] allDataInputs = properties.get("datainputset").split( ",\\s*" );
if(callActivity.getIoSpecification() == null) {
InputOutputSpecification iospec = Bpmn2Factory.eINSTANCE.createInputOutputSpecification();
callActivity.setIoSpecification(iospec);
}
InputSet inset = Bpmn2Factory.eINSTANCE.createInputSet();
for(String dataInput : allDataInputs) {
DataInput nextInput = Bpmn2Factory.eINSTANCE.createDataInput();
nextInput.setId(callActivity.getId() + "_" + dataInput + "Input");
nextInput.setName(dataInput);
callActivity.getIoSpecification().getDataInputs().add(nextInput);
inset.getDataInputRefs().add(nextInput);
}
callActivity.getIoSpecification().getInputSets().add(inset);
} else {
if(callActivity.getIoSpecification() != null) {
callActivity.getIoSpecification().getInputSets().add(Bpmn2Factory.eINSTANCE.createInputSet());
}
}
//callActivity data output set
if(properties.get("dataoutputset") != null && properties.get("dataoutputset").length() > 0) {
String[] allDataOutputs = properties.get("dataoutputset").split( ",\\s*" );
if(callActivity.getIoSpecification() == null) {
InputOutputSpecification iospec = Bpmn2Factory.eINSTANCE.createInputOutputSpecification();
callActivity.setIoSpecification(iospec);
}
OutputSet outset = Bpmn2Factory.eINSTANCE.createOutputSet();
for(String dataOutput : allDataOutputs) {
DataOutput nextOut = Bpmn2Factory.eINSTANCE.createDataOutput();
nextOut.setId(callActivity.getId() + "_" + dataOutput + "Output");
nextOut.setName(dataOutput);
callActivity.getIoSpecification().getDataOutputs().add(nextOut);
outset.getDataOutputRefs().add(nextOut);
}
callActivity.getIoSpecification().getOutputSets().add(outset);
} else {
if(callActivity.getIoSpecification() != null) {
callActivity.getIoSpecification().getOutputSets().add(Bpmn2Factory.eINSTANCE.createOutputSet());
}
}
//callActivity assignments
if(properties.get("assignments") != null && properties.get("assignments").length() > 0) {
String[] allAssignments = properties.get("assignments").split( ",\\s*" );
for(String assignment : allAssignments) {
if(assignment.contains("=")) {
String[] assignmentParts = assignment.split( "=\\s*" );
DataInputAssociation dia = Bpmn2Factory.eINSTANCE.createDataInputAssociation();
boolean foundTaskName = false;
if(callActivity.getIoSpecification() != null && callActivity.getIoSpecification().getDataOutputs() != null) {
List<DataInput> dataInputs = callActivity.getIoSpecification().getDataInputs();
for(DataInput di : dataInputs) {
if(di.getId().equals(callActivity.getId() + "_" + assignmentParts[0] + "Input")) {
dia.setTargetRef(di);
if(di.getName().equals("TaskName")) {
foundTaskName = true;
break;
}
}
}
}
Assignment a = Bpmn2Factory.eINSTANCE.createAssignment();
FormalExpression fromExpression = Bpmn2Factory.eINSTANCE.createFormalExpression();
if(assignmentParts.length > 1) {
fromExpression.setBody(assignmentParts[1]);
} else {
fromExpression.setBody("");
}
FormalExpression toExpression = Bpmn2Factory.eINSTANCE.createFormalExpression();
toExpression.setBody(dia.getTargetRef().getId());
a.setFrom(fromExpression);
a.setTo(toExpression);
dia.getAssignment().add(a);
callActivity.getDataInputAssociations().add(dia);
} else if(assignment.contains("<->")) {
String[] assignmentParts = assignment.split( "<->\\s*" );
DataInputAssociation dia = Bpmn2Factory.eINSTANCE.createDataInputAssociation();
DataOutputAssociation doa = Bpmn2Factory.eINSTANCE.createDataOutputAssociation();
ItemAwareElement ie = Bpmn2Factory.eINSTANCE.createItemAwareElement();
ie.setId(assignmentParts[0]);
dia.getSourceRef().add(ie);
doa.setTargetRef(ie);
List<DataInput> dataInputs = callActivity.getIoSpecification().getDataInputs();
for(DataInput di : dataInputs) {
if(di.getId().equals(callActivity.getId() + "_" + assignmentParts[1] + "Input")) {
dia.setTargetRef(di);
break;
}
}
List<DataOutput> dataOutputs = callActivity.getIoSpecification().getDataOutputs();
for(DataOutput dout : dataOutputs) {
if(dout.getId().equals(callActivity.getId() + "_" + assignmentParts[1] + "Output")) {
doa.getSourceRef().add(dout);
break;
}
}
callActivity.getDataInputAssociations().add(dia);
callActivity.getDataOutputAssociations().add(doa);
} else if(assignment.contains("->")) {
String[] assignmentParts = assignment.split( "->\\s*" );
// we need to check if this is an data input or data output assignment
boolean leftHandAssignMentIsDO = false;
List<DataOutput> dataOutputs = callActivity.getIoSpecification().getDataOutputs();
for(DataOutput dout : dataOutputs) {
if(dout.getId().equals(callActivity.getId() + "_" + assignmentParts[0] + "Output")) {
leftHandAssignMentIsDO = true;
break;
}
}
if(leftHandAssignMentIsDO) {
// doing data output
DataOutputAssociation doa = Bpmn2Factory.eINSTANCE.createDataOutputAssociation();
for(DataOutput dout : dataOutputs) {
if(dout.getId().equals(callActivity.getId() + "_" + assignmentParts[0] + "Output")) {
doa.getSourceRef().add(dout);
break;
}
}
ItemAwareElement ie = Bpmn2Factory.eINSTANCE.createItemAwareElement();
ie.setId(assignmentParts[1]);
doa.setTargetRef(ie);
callActivity.getDataOutputAssociations().add(doa);
} else {
// doing data input
DataInputAssociation dia = Bpmn2Factory.eINSTANCE.createDataInputAssociation();
// association from process var to dataInput var
ItemAwareElement ie = Bpmn2Factory.eINSTANCE.createItemAwareElement();
ie.setId(assignmentParts[0]);
dia.getSourceRef().add(ie);
List<DataInput> dataInputs = callActivity.getIoSpecification().getDataInputs();
for(DataInput di : dataInputs) {
if(di.getId().equals(callActivity.getId() + "_" + assignmentParts[1] + "Input")) {
dia.setTargetRef(di);
break;
}
}
callActivity.getDataInputAssociations().add(dia);
}
} else {
// TODO throw exception here?
}
}
}
// process on-entry and on-exit actions as custom elements
if(properties.get("onentryactions") != null && properties.get("onentryactions").length() > 0) {
String[] allActions = properties.get("onentryactions").split( "\\|\\s*" );
for(String action : allActions) {
OnEntryScriptType onEntryScript = DroolsFactory.eINSTANCE.createOnEntryScriptType();
onEntryScript.setScript(action);
String scriptLanguage = "";
if(properties.get("script_language").equals("java")) {
scriptLanguage = "http://www.java.com/java";
} else if(properties.get("script_language").equals("mvel")) {
scriptLanguage = "http://www.mvel.org/2.0";
} else {
// default to java
scriptLanguage = "http://www.java.com/java";
}
onEntryScript.setScriptFormat(scriptLanguage);
if(callActivity.getExtensionValues() == null || callActivity.getExtensionValues().size() < 1) {
ExtensionAttributeValue extensionElement = Bpmn2Factory.eINSTANCE.createExtensionAttributeValue();
callActivity.getExtensionValues().add(extensionElement);
}
FeatureMap.Entry extensionElementEntry = new SimpleFeatureMapEntry(
(Internal) DroolsPackage.Literals.DOCUMENT_ROOT__ON_ENTRY_SCRIPT, onEntryScript);
callActivity.getExtensionValues().get(0).getValue().add(extensionElementEntry);
}
}
if(properties.get("onexitactions") != null && properties.get("onexitactions").length() > 0) {
String[] allActions = properties.get("onexitactions").split( "\\|\\s*" );
for(String action : allActions) {
OnExitScriptType onExitScript = DroolsFactory.eINSTANCE.createOnExitScriptType();
onExitScript.setScript(action);
String scriptLanguage = "";
if(properties.get("script_language").equals("java")) {
scriptLanguage = "http://www.java.com/java";
} else if(properties.get("script_language").equals("mvel")) {
scriptLanguage = "http://www.mvel.org/2.0";
} else {
// default to java
scriptLanguage = "http://www.java.com/java";
}
onExitScript.setScriptFormat(scriptLanguage);
if(callActivity.getExtensionValues() == null || callActivity.getExtensionValues().size() < 1) {
ExtensionAttributeValue extensionElement = Bpmn2Factory.eINSTANCE.createExtensionAttributeValue();
callActivity.getExtensionValues().add(extensionElement);
}
FeatureMap.Entry extensionElementEntry = new SimpleFeatureMapEntry(
(Internal) DroolsPackage.Literals.DOCUMENT_ROOT__ON_EXIT_SCRIPT, onExitScript);
callActivity.getExtensionValues().get(0).getValue().add(extensionElementEntry);
}
}
}
private void applyTaskProperties(Task task, Map<String, String> properties) {
if(properties.get("name") != null) {
task.setName(properties.get("name"));
} else {
task.setName("");
}
DataInput taskNameDataInput = null;
if(properties.get("taskname") != null && properties.get("taskname").length() > 0) {
// add droolsjbpm-specific attribute "taskName"
ExtendedMetaData metadata = ExtendedMetaData.INSTANCE;
EAttributeImpl extensionAttribute = (EAttributeImpl) metadata.demandFeature(
"http://www.jboss.org/drools", "taskName", false, false);
EStructuralFeatureImpl.SimpleFeatureMapEntry extensionEntry = new EStructuralFeatureImpl.SimpleFeatureMapEntry(extensionAttribute,
properties.get("taskname"));
task.getAnyAttribute().add(extensionEntry);
// map the taskName to iospecification
taskNameDataInput = Bpmn2Factory.eINSTANCE.createDataInput();
taskNameDataInput.setId(task.getId() + "_TaskNameInput");
taskNameDataInput.setName("TaskName");
if(task.getIoSpecification() == null) {
InputOutputSpecification iospec = Bpmn2Factory.eINSTANCE.createInputOutputSpecification();
task.setIoSpecification(iospec);
}
task.getIoSpecification().getDataInputs().add(taskNameDataInput);
// taskName also needs to be in dataInputAssociation
DataInputAssociation taskNameDataInputAssociation = Bpmn2Factory.eINSTANCE.createDataInputAssociation();
taskNameDataInputAssociation.setTargetRef(taskNameDataInput);
Assignment taskNameAssignment = Bpmn2Factory.eINSTANCE.createAssignment();
FormalExpression fromExp = Bpmn2Factory.eINSTANCE.createFormalExpression();
fromExp.setBody(properties.get("taskname"));
taskNameAssignment.setFrom(fromExp);
FormalExpression toExp = Bpmn2Factory.eINSTANCE.createFormalExpression();
toExp.setBody(task.getId() + "_TaskNameInput");
taskNameAssignment.setTo(toExp);
taskNameDataInputAssociation.getAssignment().add(taskNameAssignment);
task.getDataInputAssociations().add(taskNameDataInputAssociation);
}
//process lanes
if(properties.get("lanes") != null && properties.get("lanes").length() > 0) {
ExtendedMetaData metadata = ExtendedMetaData.INSTANCE;
EAttributeImpl extensionAttribute = (EAttributeImpl) metadata.demandFeature(
"http://www.jboss.org/drools", "lanes", false, false);
EStructuralFeatureImpl.SimpleFeatureMapEntry extensionEntry = new EStructuralFeatureImpl.SimpleFeatureMapEntry(extensionAttribute,
properties.get("lanes"));
task.getAnyAttribute().add(extensionEntry);
}
//process data input set
if(properties.get("datainputset") != null && properties.get("datainputset").length() > 0) {
String[] allDataInputs = properties.get("datainputset").split( ",\\s*" );
if(task.getIoSpecification() == null) {
InputOutputSpecification iospec = Bpmn2Factory.eINSTANCE.createInputOutputSpecification();
task.setIoSpecification(iospec);
}
InputSet inset = Bpmn2Factory.eINSTANCE.createInputSet();
for(String dataInput : allDataInputs) {
DataInput nextInput = Bpmn2Factory.eINSTANCE.createDataInput();
nextInput.setId(task.getId() + "_" + dataInput + "Input");
nextInput.setName(dataInput);
task.getIoSpecification().getDataInputs().add(nextInput);
inset.getDataInputRefs().add(nextInput);
}
// add the taskName as well if it was defined
if(taskNameDataInput != null) {
inset.getDataInputRefs().add(taskNameDataInput);
}
task.getIoSpecification().getInputSets().add(inset);
} else {
if(task.getIoSpecification() != null) {
task.getIoSpecification().getInputSets().add(Bpmn2Factory.eINSTANCE.createInputSet());
}
}
//process data output set
if(properties.get("dataoutputset") != null && properties.get("dataoutputset").length() > 0) {
String[] allDataOutputs = properties.get("dataoutputset").split( ",\\s*" );
if(task.getIoSpecification() == null) {
InputOutputSpecification iospec = Bpmn2Factory.eINSTANCE.createInputOutputSpecification();
task.setIoSpecification(iospec);
}
OutputSet outset = Bpmn2Factory.eINSTANCE.createOutputSet();
for(String dataOutput : allDataOutputs) {
DataOutput nextOut = Bpmn2Factory.eINSTANCE.createDataOutput();
nextOut.setId(task.getId() + "_" + dataOutput + "Output");
nextOut.setName(dataOutput);
task.getIoSpecification().getDataOutputs().add(nextOut);
outset.getDataOutputRefs().add(nextOut);
}
task.getIoSpecification().getOutputSets().add(outset);
} else {
if(task.getIoSpecification() != null) {
task.getIoSpecification().getOutputSets().add(Bpmn2Factory.eINSTANCE.createOutputSet());
}
}
//process assignments
if(properties.get("assignments") != null && properties.get("assignments").length() > 0) {
String[] allAssignments = properties.get("assignments").split( ",\\s*" );
for(String assignment : allAssignments) {
if(assignment.contains("=")) {
String[] assignmentParts = assignment.split( "=\\s*" );
DataInputAssociation dia = Bpmn2Factory.eINSTANCE.createDataInputAssociation();
boolean foundTaskName = false;
if(task.getIoSpecification() != null && task.getIoSpecification().getDataOutputs() != null) {
List<DataInput> dataInputs = task.getIoSpecification().getDataInputs();
for(DataInput di : dataInputs) {
if(di.getId().equals(task.getId() + "_" + assignmentParts[0] + "Input")) {
dia.setTargetRef(di);
if(di.getName().equals("TaskName")) {
foundTaskName = true;
break;
}
}
}
}
// if we are dealing with TaskName and none has been defined, add it
if(assignmentParts[0].equals("TaskName") && !foundTaskName) {
DataInput assignmentTaskNameDataInput = Bpmn2Factory.eINSTANCE.createDataInput();
assignmentTaskNameDataInput.setId(task.getId() + "_TaskNameInput");
assignmentTaskNameDataInput.setName("TaskName");
if(task.getIoSpecification() == null) {
InputOutputSpecification iospec = Bpmn2Factory.eINSTANCE.createInputOutputSpecification();
task.setIoSpecification(iospec);
}
task.getIoSpecification().getDataInputs().add(assignmentTaskNameDataInput);
dia.setTargetRef(assignmentTaskNameDataInput);
InputSet inset = task.getIoSpecification().getInputSets().get(0);
inset.getDataInputRefs().add(assignmentTaskNameDataInput);
}
Assignment a = Bpmn2Factory.eINSTANCE.createAssignment();
FormalExpression fromExpression = Bpmn2Factory.eINSTANCE.createFormalExpression();
if(assignmentParts.length > 1) {
fromExpression.setBody(assignmentParts[1]);
} else {
fromExpression.setBody("");
}
FormalExpression toExpression = Bpmn2Factory.eINSTANCE.createFormalExpression();
toExpression.setBody(dia.getTargetRef().getId());
a.setFrom(fromExpression);
a.setTo(toExpression);
dia.getAssignment().add(a);
task.getDataInputAssociations().add(dia);
} else if(assignment.contains("<->")) {
String[] assignmentParts = assignment.split( "<->\\s*" );
DataInputAssociation dia = Bpmn2Factory.eINSTANCE.createDataInputAssociation();
DataOutputAssociation doa = Bpmn2Factory.eINSTANCE.createDataOutputAssociation();
ItemAwareElement ie = Bpmn2Factory.eINSTANCE.createItemAwareElement();
ie.setId(assignmentParts[0]);
dia.getSourceRef().add(ie);
doa.setTargetRef(ie);
List<DataInput> dataInputs = task.getIoSpecification().getDataInputs();
for(DataInput di : dataInputs) {
if(di.getId().equals(task.getId() + "_" + assignmentParts[1] + "Input")) {
dia.setTargetRef(di);
break;
}
}
List<DataOutput> dataOutputs = task.getIoSpecification().getDataOutputs();
for(DataOutput dout : dataOutputs) {
if(dout.getId().equals(task.getId() + "_" + assignmentParts[1] + "Output")) {
doa.getSourceRef().add(dout);
break;
}
}
task.getDataInputAssociations().add(dia);
task.getDataOutputAssociations().add(doa);
} else if(assignment.contains("->")) {
String[] assignmentParts = assignment.split( "->\\s*" );
// we need to check if this is an data input or data output assignment
boolean leftHandAssignMentIsDO = false;
List<DataOutput> dataOutputs = task.getIoSpecification().getDataOutputs();
for(DataOutput dout : dataOutputs) {
if(dout.getId().equals(task.getId() + "_" + assignmentParts[0] + "Output")) {
leftHandAssignMentIsDO = true;
break;
}
}
if(leftHandAssignMentIsDO) {
// doing data output
DataOutputAssociation doa = Bpmn2Factory.eINSTANCE.createDataOutputAssociation();
for(DataOutput dout : dataOutputs) {
if(dout.getId().equals(task.getId() + "_" + assignmentParts[0] + "Output")) {
doa.getSourceRef().add(dout);
break;
}
}
ItemAwareElement ie = Bpmn2Factory.eINSTANCE.createItemAwareElement();
ie.setId(assignmentParts[1]);
doa.setTargetRef(ie);
task.getDataOutputAssociations().add(doa);
} else {
// doing data input
DataInputAssociation dia = Bpmn2Factory.eINSTANCE.createDataInputAssociation();
// association from process var to dataInput var
ItemAwareElement ie = Bpmn2Factory.eINSTANCE.createItemAwareElement();
ie.setId(assignmentParts[0]);
dia.getSourceRef().add(ie);
List<DataInput> dataInputs = task.getIoSpecification().getDataInputs();
for(DataInput di : dataInputs) {
if(di.getId().equals(task.getId() + "_" + assignmentParts[1] + "Input")) {
dia.setTargetRef(di);
break;
}
}
task.getDataInputAssociations().add(dia);
}
} else {
// TODO throw exception here?
}
}
// check if multiple taskname datainput associations exist and remove them
List<DataInputAssociation> dataInputAssociations = task.getDataInputAssociations();
boolean haveTaskNameInput = false;
for(Iterator<DataInputAssociation> itr = dataInputAssociations.iterator(); itr.hasNext();)
{
DataInputAssociation da = itr.next();
if(da.getAssignment() != null && da.getAssignment().size() > 0) {
Assignment a = da.getAssignment().get(0);
if(((FormalExpression) a.getTo()).getBody().equals(task.getId() + "_TaskNameInput")) {
if(!haveTaskNameInput) {
haveTaskNameInput = true;
} else {
itr.remove();
}
}
}
}
}
// process on-entry and on-exit actions as custom elements
if(properties.get("onentryactions") != null && properties.get("onentryactions").length() > 0) {
String[] allActions = properties.get("onentryactions").split( "\\|\\s*" );
for(String action : allActions) {
OnEntryScriptType onEntryScript = DroolsFactory.eINSTANCE.createOnEntryScriptType();
onEntryScript.setScript(action);
String scriptLanguage = "";
if(properties.get("script_language").equals("java")) {
scriptLanguage = "http://www.java.com/java";
} else if(properties.get("script_language").equals("mvel")) {
scriptLanguage = "http://www.mvel.org/2.0";
} else {
// default to java
scriptLanguage = "http://www.java.com/java";
}
onEntryScript.setScriptFormat(scriptLanguage);
if(task.getExtensionValues() == null || task.getExtensionValues().size() < 1) {
ExtensionAttributeValue extensionElement = Bpmn2Factory.eINSTANCE.createExtensionAttributeValue();
task.getExtensionValues().add(extensionElement);
}
FeatureMap.Entry extensionElementEntry = new SimpleFeatureMapEntry(
(Internal) DroolsPackage.Literals.DOCUMENT_ROOT__ON_ENTRY_SCRIPT, onEntryScript);
task.getExtensionValues().get(0).getValue().add(extensionElementEntry);
}
}
if(properties.get("onexitactions") != null && properties.get("onexitactions").length() > 0) {
String[] allActions = properties.get("onexitactions").split( "\\|\\s*" );
for(String action : allActions) {
OnExitScriptType onExitScript = DroolsFactory.eINSTANCE.createOnExitScriptType();
onExitScript.setScript(action);
String scriptLanguage = "";
if(properties.get("script_language").equals("java")) {
scriptLanguage = "http://www.java.com/java";
} else if(properties.get("script_language").equals("mvel")) {
scriptLanguage = "http://www.mvel.org/2.0";
} else {
// default to java
scriptLanguage = "http://www.java.com/java";
}
onExitScript.setScriptFormat(scriptLanguage);
if(task.getExtensionValues() == null || task.getExtensionValues().size() < 1) {
ExtensionAttributeValue extensionElement = Bpmn2Factory.eINSTANCE.createExtensionAttributeValue();
task.getExtensionValues().add(extensionElement);
}
FeatureMap.Entry extensionElementEntry = new SimpleFeatureMapEntry(
(Internal) DroolsPackage.Literals.DOCUMENT_ROOT__ON_EXIT_SCRIPT, onExitScript);
task.getExtensionValues().get(0).getValue().add(extensionElementEntry);
}
}
}
private void applyUserTaskProperties(UserTask task, Map<String, String> properties) {
if(properties.get("actors") != null && properties.get("actors").length() > 0) {
String[] allActors = properties.get("actors").split( ",\\s*" );
for(String actor : allActors) {
PotentialOwner po = Bpmn2Factory.eINSTANCE.createPotentialOwner();
ResourceAssignmentExpression rae = Bpmn2Factory.eINSTANCE.createResourceAssignmentExpression();
FormalExpression fe = Bpmn2Factory.eINSTANCE.createFormalExpression();
fe.setBody(actor);
rae.setExpression(fe);
po.setResourceAssignmentExpression(rae);
task.getResources().add(po);
}
}
if(properties.get("script_language") != null && properties.get("script_language").length() > 0) {
String scriptLanguage = "";
if(properties.get("script_language").equals("java")) {
scriptLanguage = "http://www.java.com/java";
} else if(properties.get("script_language").equals("mvel")) {
scriptLanguage = "http://www.mvel.org/2.0";
} else {
// default to java
scriptLanguage = "http://www.java.com/java";
}
ExtendedMetaData metadata = ExtendedMetaData.INSTANCE;
EAttributeImpl scriptLanguageElement = (EAttributeImpl) metadata.demandFeature(
"http://www.jboss.org/drools", "scriptFormat", false , false);
EStructuralFeatureImpl.SimpleFeatureMapEntry extensionEntry = new EStructuralFeatureImpl.SimpleFeatureMapEntry(scriptLanguageElement,
scriptLanguage);
task.getAnyAttribute().add(extensionEntry);
}
if(properties.get("groupid") != null && properties.get("groupid").length() > 0) {
if(task.getIoSpecification() == null) {
InputOutputSpecification iospec = Bpmn2Factory.eINSTANCE.createInputOutputSpecification();
task.setIoSpecification(iospec);
}
List<DataInput> dataInputs = task.getIoSpecification().getDataInputs();
boolean foundGroupIdInput = false;
DataInput foundInput = null;
for(DataInput din : dataInputs) {
if(din.getName().equals("GroupId")) {
foundGroupIdInput = true;
foundInput = din;
break;
}
}
if(!foundGroupIdInput) {
DataInput d = Bpmn2Factory.eINSTANCE.createDataInput();
d.setId(task.getId() + "_" + "GroupId" + "Input");
d.setName("GroupId");
task.getIoSpecification().getDataInputs().add(d);
foundInput = d;
if(task.getIoSpecification().getInputSets() == null || task.getIoSpecification().getInputSets().size() < 1) {
InputSet inset = Bpmn2Factory.eINSTANCE.createInputSet();
task.getIoSpecification().getInputSets().add(inset);
}
task.getIoSpecification().getInputSets().get(0).getDataInputRefs().add(d);
}
boolean foundGroupIdAssociation = false;
List<DataInputAssociation> inputAssociations = task.getDataInputAssociations();
for(DataInputAssociation da : inputAssociations) {
if(da.getTargetRef().getId().equals(foundInput.getId())) {
foundGroupIdAssociation = true;
((FormalExpression) da.getAssignment().get(0).getFrom()).setBody(properties.get("groupid"));
}
}
if(!foundGroupIdAssociation) {
DataInputAssociation dia = Bpmn2Factory.eINSTANCE.createDataInputAssociation();
dia.setTargetRef(foundInput);
Assignment a = Bpmn2Factory.eINSTANCE.createAssignment();
FormalExpression groupFromExpression = Bpmn2Factory.eINSTANCE.createFormalExpression();
groupFromExpression.setBody(properties.get("groupid"));
FormalExpression groupToExpression = Bpmn2Factory.eINSTANCE.createFormalExpression();
groupToExpression.setBody(foundInput.getId());
a.setFrom(groupFromExpression);
a.setTo(groupToExpression);
dia.getAssignment().add(a);
task.getDataInputAssociations().add(dia);
}
}
}
private void applyGatewayProperties(Gateway gateway, Map<String, String> properties) {
if(properties.get("name") != null && properties.get("name").length() > 0) {
gateway.setName(properties.get("name"));
} else {
gateway.setName("");
}
if(properties.get("defaultgate") != null && gateway instanceof InclusiveGateway) {
ExtendedMetaData metadata = ExtendedMetaData.INSTANCE;
EAttributeImpl extensionAttribute = (EAttributeImpl) metadata.demandFeature(
"http://www.jboss.org/drools", "dg", false, false);
EStructuralFeatureImpl.SimpleFeatureMapEntry extensionEntry = new EStructuralFeatureImpl.SimpleFeatureMapEntry(extensionAttribute,
properties.get("defaultgate"));
gateway.getAnyAttribute().add(extensionEntry);
}
}
private void applySequenceFlowProperties(SequenceFlow sequenceFlow, Map<String, String> properties) {
// sequence flow name is options
if(properties.get("name") != null && !"".equals(properties.get("name"))) {
sequenceFlow.setName(properties.get("name"));
}
if (properties.get("auditing") != null && !"".equals(properties.get("auditing"))) {
Auditing audit = Bpmn2Factory.eINSTANCE.createAuditing();
audit.getDocumentation().add(createDocumentation(properties.get("auditing")));
sequenceFlow.setAuditing(audit);
}
if (properties.get("conditionexpression") != null && !"".equals(properties.get("conditionexpression"))) {
FormalExpression expr = Bpmn2Factory.eINSTANCE.createFormalExpression();
expr.setBody(properties.get("conditionexpression"));
// check if language was specified
if (properties.get("conditionexpressionlanguage") != null && !"".equals(properties.get("conditionexpressionlanguage"))) {
String languageStr;
if(properties.get("conditionexpressionlanguage").equals("drools")) {
languageStr = "http://www.jboss.org/drools/rule";
} else if(properties.get("conditionexpressionlanguage").equals("mvel")) {
languageStr = "http://www.mvel.org/2.0";
} else if(properties.get("conditionexpressionlanguage").equals("java")) {
languageStr = "http://www.java.com/java";
} else {
// default to mvel
languageStr = "http://www.mvel.org/2.0";
}
expr.setLanguage(languageStr);
}
sequenceFlow.setConditionExpression(expr);
}
if (properties.get("priority") != null && !"".equals(properties.get("priority"))) {
ExtendedMetaData metadata = ExtendedMetaData.INSTANCE;
EAttributeImpl priorityElement = (EAttributeImpl) metadata.demandFeature(
"http://www.jboss.org/drools", "priority", false , false);
EStructuralFeatureImpl.SimpleFeatureMapEntry extensionEntry = new EStructuralFeatureImpl.SimpleFeatureMapEntry(priorityElement,
properties.get("priority"));
sequenceFlow.getAnyAttribute().add(extensionEntry);
}
if (properties.get("monitoring") != null && !"".equals(properties.get("monitoring"))) {
Monitoring monitoring = Bpmn2Factory.eINSTANCE.createMonitoring();
monitoring.getDocumentation().add(createDocumentation(properties.get("monitoring")));
sequenceFlow.setMonitoring(monitoring);
}
sequenceFlow.setIsImmediate(Boolean.parseBoolean(properties.get("isimmediate")));
}
private Map<String, String> unmarshallProperties(JsonParser parser) throws JsonParseException, IOException {
Map<String, String> properties = new HashMap<String, String>();
while (parser.nextToken() != JsonToken.END_OBJECT) {
String fieldname = parser.getCurrentName();
parser.nextToken();
properties.put(fieldname, parser.getText());
}
return properties;
}
private Documentation createDocumentation(String text) {
Documentation doc = Bpmn2Factory.eINSTANCE.createDocumentation();
doc.setText(text);
return doc;
}
private boolean isCustomElement(String taskType, String preProcessingData) {
if(taskType != null && taskType.length() > 0 && preProcessingData != null && preProcessingData.length() > 0) {
String[] preProcessingDataElements = preProcessingData.split( ",\\s*" );
for(String preProcessingDataElement : preProcessingDataElements) {
if(taskType.equals(preProcessingDataElement)) {
return true;
}
}
}
return false;
}
}
| true | false | null | null |
diff --git a/components/bio-formats/src/loci/formats/in/ZeissZVIReader.java b/components/bio-formats/src/loci/formats/in/ZeissZVIReader.java
index 17adec439..6b27a8fbc 100644
--- a/components/bio-formats/src/loci/formats/in/ZeissZVIReader.java
+++ b/components/bio-formats/src/loci/formats/in/ZeissZVIReader.java
@@ -1,1508 +1,1510 @@
//
// ZeissZVIReader.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 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats.in;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.Vector;
import loci.common.DataTools;
import loci.common.DateTools;
import loci.common.Location;
import loci.common.RandomAccessInputStream;
import loci.common.services.DependencyException;
import loci.common.services.ServiceFactory;
import loci.formats.CoreMetadata;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.codec.Codec;
import loci.formats.codec.CodecOptions;
import loci.formats.codec.JPEGCodec;
import loci.formats.codec.ZlibCodec;
import loci.formats.meta.DummyMetadata;
import loci.formats.meta.MetadataStore;
import ome.xml.model.primitives.PositiveFloat;
import loci.formats.services.POIService;
import ome.xml.model.primitives.PositiveInteger;
/**
* ZeissZVIReader is the file format reader for Zeiss ZVI files.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/bio-formats/src/loci/formats/in/ZeissZVIReader.java">Trac</a>,
* <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/bio-formats/src/loci/formats/in/ZeissZVIReader.java;hb=HEAD">Gitweb</a></dd></dl>
*
* @author Melissa Linkert melissa at glencoesoftware.com
*/
public class ZeissZVIReader extends FormatReader {
// -- Constants --
public static final int ZVI_MAGIC_BYTES = 0xd0cf11e0;
private static final long ROI_SIGNATURE = 0x21fff6977547000dL;
/** ROI types. */
private static final int ELLIPSE = 15;
private static final int CURVE = 12;
private static final int OUTLINE = 16;
private static final int RECTANGLE = 13;
private static final int LINE = 2;
private static final int TEXT = 17;
private static final int SCALE_BAR = 10;
private static final int OUTLINE_SPLINE = 50;
// -- Fields --
/** Number of bytes per pixel. */
private int bpp;
private String[] imageFiles;
private int[] offsets;
private int[][] coordinates;
private Hashtable<Integer, String> timestamps, exposureTime;
private int cIndex = -1;
private boolean isJPEG, isZlib;
private int realWidth, realHeight;
private POIService poi;
private Vector<String> tagsToParse;
private int nextEmWave = 0, nextExWave = 0, nextChName = 0;
private Hashtable<Integer, Double> stageX = new Hashtable<Integer, Double>();
private Hashtable<Integer, Double> stageY = new Hashtable<Integer, Double>();
private int timepoint = 0;
private int[] channelColors;
private int lastPlane = 0;
private Hashtable<Integer, Integer> tiles = new Hashtable<Integer, Integer>();
private Hashtable<Integer, Double> detectorGain =
new Hashtable<Integer, Double>();
private Hashtable<Integer, Double> detectorOffset =
new Hashtable<Integer, Double>();
private Hashtable<Integer, PositiveInteger> emWavelength =
new Hashtable<Integer, PositiveInteger>();
private Hashtable<Integer, PositiveInteger> exWavelength =
new Hashtable<Integer, PositiveInteger>();
private Hashtable<Integer, String> channelName =
new Hashtable<Integer, String>();
private Double physicalSizeX, physicalSizeY, physicalSizeZ;
private String imageDescription;
private Vector<String> roiIDs = new Vector<String>();
// -- Constructor --
/** Constructs a new ZeissZVI reader. */
public ZeissZVIReader() {
super("Zeiss Vision Image (ZVI)", "zvi");
domains = new String[] {FormatTools.LM_DOMAIN};
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#getOptimalTileHeight() */
public int getOptimalTileHeight() {
FormatTools.assertId(currentId, true, 1);
return getSizeY();
}
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
final int blockLen = 65536;
if (!FormatTools.validStream(stream, blockLen, false)) return false;
int magic = stream.readInt();
if (magic != ZVI_MAGIC_BYTES) return false;
return true;
}
/* @see loci.formats.IFormatReader#get8BitLookupTable() */
public byte[][] get8BitLookupTable() throws FormatException, IOException {
int pixelType = getPixelType();
if ((pixelType != FormatTools.INT8 && pixelType != FormatTools.UINT8) ||
!isIndexed())
{
return null;
}
byte[][] lut = new byte[3][256];
int channel = getZCTCoords(lastPlane)[1];
if (channel >= channelColors.length) return null;
int color = channelColors[channel];
float red = (color & 0xff) / 255f;
float green = ((color & 0xff00) >> 8) / 255f;
float blue = ((color & 0xff0000) >> 16) / 255f;
for (int i=0; i<lut[0].length; i++) {
lut[0][i] = (byte) (red * i);
lut[1][i] = (byte) (green * i);
lut[2][i] = (byte) (blue * i);
}
return lut;
}
/* @see loci.formats.IFormatReader#get16BitLookupTable() */
public short[][] get16BitLookupTable() throws FormatException, IOException {
int pixelType = getPixelType();
if ((pixelType != FormatTools.INT16 && pixelType != FormatTools.UINT16) ||
!isIndexed())
{
return null;
}
short[][] lut = new short[3][65536];
int channel = getZCTCoords(lastPlane)[1];
if (channel >= channelColors.length) return null;
int color = channelColors[channel];
float red = (color & 0xff) / 255f;
float green = ((color & 0xff00) >> 8) / 255f;
float blue = ((color & 0xff0000) >> 16) / 255f;
for (int i=0; i<lut[0].length; i++) {
lut[0][i] = (short) (red * i);
lut[1][i] = (short) (green * i);
lut[2][i] = (short) (blue * i);
}
return lut;
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
lastPlane = no;
int bytes = FormatTools.getBytesPerPixel(getPixelType());
int pixel = bytes * getRGBChannelCount();
CodecOptions options = new CodecOptions();
options.littleEndian = isLittleEndian();
options.interleaved = isInterleaved();
int index = no;
if (getSeriesCount() > 1) {
index += getSeries() * getImageCount();
}
if (index >= imageFiles.length) {
return buf;
}
RandomAccessInputStream s = poi.getDocumentStream(imageFiles[index]);
s.seek(offsets[index]);
int len = w * pixel;
int row = getSizeX() * pixel;
if (isJPEG) {
byte[] t = new JPEGCodec().decompress(s, options);
for (int yy=0; yy<h; yy++) {
System.arraycopy(t, (yy + y) * row + x * pixel, buf, yy*len, len);
}
}
else if (isZlib) {
byte[] t = new ZlibCodec().decompress(s, options);
for (int yy=0; yy<h; yy++) {
int src = (yy + y) * row + x * pixel;
int dest = yy * len;
if (src + len <= t.length && dest + len <= buf.length) {
System.arraycopy(t, src, buf, dest, len);
}
else break;
}
}
else {
readPlane(s, x, y, w, h, buf);
}
s.close();
if (isRGB() && !isJPEG) {
// reverse bytes in groups of 3 to account for BGR storage
byte[] bb = new byte[bytes];
for (int i=0; i<buf.length; i+=bpp) {
System.arraycopy(buf, i + 2*bytes, bb, 0, bytes);
System.arraycopy(buf, i, buf, i + 2*bytes, bytes);
System.arraycopy(bb, 0, buf, i, bytes);
}
}
return buf;
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly) {
timestamps = exposureTime = null;
offsets = null;
coordinates = null;
imageFiles = null;
cIndex = -1;
bpp = 0;
isJPEG = isZlib = false;
if (poi != null) poi.close();
poi = null;
tagsToParse = null;
nextEmWave = nextExWave = nextChName = 0;
realWidth = realHeight = 0;
stageX.clear();
stageY.clear();
channelColors = null;
lastPlane = 0;
tiles.clear();
detectorGain.clear();
detectorOffset.clear();
emWavelength.clear();
exWavelength.clear();
channelName.clear();
physicalSizeX = physicalSizeY = physicalSizeZ = null;
imageDescription = null;
timepoint = 0;
roiIDs.clear();
}
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
try {
ServiceFactory factory = new ServiceFactory();
poi = factory.getInstance(POIService.class);
}
catch (DependencyException de) {
throw new FormatException("POI library not found", de);
}
poi.initialize(Location.getMappedId(id));
timestamps = new Hashtable<Integer, String>();
exposureTime = new Hashtable<Integer, String>();
tagsToParse = new Vector<String>();
// count number of images
String[] files = (String[]) poi.getDocumentList().toArray(new String[0]);
Arrays.sort(files, new Comparator() {
public int compare(Object o1, Object o2) {
int n1 = getImageNumber((String) o1, -1);
int n2 = getImageNumber((String) o2, -1);
return new Integer(n1).compareTo(new Integer(n2));
}
});
core[0].imageCount = 0;
for (String file : files) {
String uname = file.toUpperCase();
uname = uname.substring(uname.indexOf(File.separator) + 1);
if (uname.endsWith("CONTENTS") && (uname.startsWith("IMAGE") ||
uname.indexOf("ITEM") != -1) && poi.getFileSize(file) > 1024)
{
int imageNumber = getImageNumber(file, 0);
if (imageNumber >= getImageCount()) {
core[0].imageCount++;
}
}
}
offsets = new int[getImageCount()];
coordinates = new int[getImageCount()][3];
imageFiles = new String[getImageCount()];
// parse each embedded file
Vector<Integer> cIndices = new Vector<Integer>();
Vector<Integer> zIndices = new Vector<Integer>();
Vector<Integer> tIndices = new Vector<Integer>();
MetadataStore store = makeFilterMetadata();
for (String name : files) {
String relPath = name.substring(name.lastIndexOf(File.separator) + 1);
if (!relPath.toUpperCase().equals("CONTENTS")) continue;
String dirName = name.substring(0, name.lastIndexOf(File.separator));
if (dirName.indexOf(File.separator) != -1) {
dirName = dirName.substring(dirName.lastIndexOf(File.separator) + 1);
}
if (name.indexOf("Scaling") == -1 && dirName.equals("Tags")) {
int imageNum = getImageNumber(name, -1);
if (imageNum == -1) {
parseTags(imageNum, name, new DummyMetadata());
}
else tagsToParse.add(name);
}
else if (dirName.equals("Shapes") && name.indexOf("Item") != -1) {
int imageNum = getImageNumber(name, -1);
if (imageNum != -1) {
try {
parseROIs(imageNum, name, store);
}
catch (IOException e) {
LOGGER.debug("Could not parse all ROIs.", e);
}
}
}
else if (dirName.equals("Image") ||
dirName.toUpperCase().indexOf("ITEM") != -1)
{
int imageNum = getImageNumber(dirName, getImageCount() == 1 ? 0 : -1);
if (imageNum == -1) continue;
// found a valid image stream
RandomAccessInputStream s = poi.getDocumentStream(name);
s.order(true);
if (s.length() <= 1024) {
s.close();
continue;
}
for (int q=0; q<11; q++) {
getNextTag(s);
}
s.skipBytes(2);
int len = s.readInt() - 20;
s.skipBytes(8);
int zidx = s.readInt();
int cidx = s.readInt();
int tidx = s.readInt();
if (!zIndices.contains(zidx)) zIndices.add(zidx);
if (!tIndices.contains(tidx)) tIndices.add(tidx);
if (!cIndices.contains(cidx)) cIndices.add(cidx);
s.skipBytes(len);
for (int q=0; q<5; q++) {
getNextTag(s);
}
s.skipBytes(4);
if (getSizeX() == 0) {
core[0].sizeX = s.readInt();
core[0].sizeY = s.readInt();
}
else s.skipBytes(8);
s.skipBytes(4);
if (bpp == 0) {
bpp = s.readInt();
}
else s.skipBytes(4);
s.skipBytes(4);
int valid = s.readInt();
String check = s.readString(4).trim();
isZlib = (valid == 0 || valid == 1) && check.equals("WZL");
isJPEG = (valid == 0 || valid == 1) && !isZlib;
// save the offset to the pixel data
offsets[imageNum] = (int) s.getFilePointer() - 4;
if (isZlib) offsets[imageNum] += 8;
coordinates[imageNum][0] = zidx;
coordinates[imageNum][1] = cidx;
coordinates[imageNum][2] = tidx;
imageFiles[imageNum] = name;
s.close();
}
}
LOGGER.info("Populating metadata");
stageX.clear();
stageY.clear();
core[0].sizeZ = zIndices.size();
core[0].sizeT = tIndices.size();
core[0].sizeC = cIndices.size();
core[0].littleEndian = true;
core[0].interleaved = true;
core[0].falseColor = true;
core[0].metadataComplete = true;
core[0].imageCount = getSizeZ() * getSizeT() * getSizeC();
core[0].rgb = (bpp % 3) == 0;
if (isRGB()) core[0].sizeC *= 3;
for (String name : tagsToParse) {
int imageNum = getImageNumber(name, -1);
parseTags(imageNum, name, store);
}
// calculate tile dimensions and number of tiles
if (core.length > 1) {
Integer[] t = tiles.keySet().toArray(new Integer[tiles.size()]);
Arrays.sort(t);
Vector<Integer> tmpOffsets = new Vector<Integer>();
Vector<String> tmpFiles = new Vector<String>();
int index = 0;
for (Integer key : t) {
int nTiles = tiles.get(key).intValue();
if (nTiles < getImageCount()) {
tiles.remove(key);
}
else {
for (int p=0; p<nTiles; p++) {
tmpOffsets.add(new Integer(offsets[index + p]));
tmpFiles.add(imageFiles[index + p]);
}
}
index += nTiles;
}
offsets = new int[tmpOffsets.size()];
for (int i=0; i<offsets.length; i++) {
offsets[i] = tmpOffsets.get(i).intValue();
}
imageFiles = tmpFiles.toArray(new String[tmpFiles.size()]);
}
if (getSizeX() == 0) {
core[0].sizeX = 1;
}
if (getSizeY() == 0) {
core[0].sizeY = 1;
}
if (getImageCount() == 0) {
core[0].imageCount = 1;
core[0].sizeZ = 1;
core[0].sizeC = 1;
core[0].sizeT = 1;
}
int totalTiles = offsets.length / getImageCount();
int tileRows = realHeight / getSizeY();
int tileColumns = realWidth / getSizeX();
if (getSizeY() * tileRows != realHeight) tileRows++;
if (getSizeX() * tileColumns != realWidth) tileColumns++;
if (totalTiles <= 1) {
tileRows = 1;
tileColumns = 1;
}
if (tileRows == 0) tileRows = 1;
if (tileColumns == 0) tileColumns = 1;
if (tileColumns > 1 || tileRows > 1) {
CoreMetadata originalCore = core[0];
core = new CoreMetadata[tileRows * tileColumns];
core[0] = originalCore;
}
core[0].dimensionOrder = "XY";
if (isRGB()) core[0].dimensionOrder += "C";
for (int i=0; i<coordinates.length-1; i++) {
int[] zct1 = coordinates[i];
int[] zct2 = coordinates[i + 1];
int deltaZ = zct2[0] - zct1[0];
int deltaC = zct2[1] - zct1[1];
int deltaT = zct2[2] - zct1[2];
if (deltaZ > 0 && getDimensionOrder().indexOf("Z") == -1) {
core[0].dimensionOrder += "Z";
}
if (deltaC > 0 && getDimensionOrder().indexOf("C") == -1) {
core[0].dimensionOrder += "C";
}
if (deltaT > 0 && getDimensionOrder().indexOf("T") == -1) {
core[0].dimensionOrder += "T";
}
}
core[0].dimensionOrder =
MetadataTools.makeSaneDimensionOrder(getDimensionOrder());
if (bpp == 1 || bpp == 3) core[0].pixelType = FormatTools.UINT8;
else if (bpp == 2 || bpp == 6) core[0].pixelType = FormatTools.UINT16;
if (isJPEG) core[0].pixelType = FormatTools.UINT8;
core[0].indexed = !isRGB() && channelColors != null;
for (int i=1; i<core.length; i++) {
core[i] = new CoreMetadata(this, 0);
}
MetadataTools.populatePixels(store, this, true);
for (int i=0; i<getSeriesCount(); i++) {
long firstStamp = 0;
if (timestamps.size() > 0) {
String timestamp = timestamps.get(new Integer(0));
firstStamp = parseTimestamp(timestamp);
String date =
DateTools.convertDate((long) (firstStamp / 1600), DateTools.ZVI);
store.setImageAcquiredDate(date, i);
}
else MetadataTools.setDefaultCreationDate(store, getCurrentFile(), i);
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
// link Instrument and Image
String instrumentID = MetadataTools.createLSID("Instrument", 0);
store.setInstrumentID(instrumentID, 0);
String objectiveID = MetadataTools.createLSID("Objective", 0, 0);
store.setObjectiveID(objectiveID, 0, 0);
store.setObjectiveCorrection(getCorrection("Other"), 0, 0);
store.setObjectiveImmersion(getImmersion("Other"), 0, 0);
int channelIndex = 0;
if (channelName.size() > 0 && channelName.get(0) == null) {
channelIndex = 1;
}
// link DetectorSettings to an actual Detector
for (int i=0; i<getEffectiveSizeC(); i++) {
String detectorID = MetadataTools.createLSID("Detector", 0, i);
store.setDetectorID(detectorID, 0, i);
store.setDetectorType(getDetectorType("Other"), 0, i);
for (int s=0; s<getSeriesCount(); s++) {
+ int c = channelIndex + i;
+
store.setDetectorSettingsID(detectorID, s, i);
- store.setDetectorSettingsGain(detectorGain.get(i), s, i);
- store.setDetectorSettingsOffset(detectorOffset.get(i), s, i);
+ store.setDetectorSettingsGain(detectorGain.get(c), s, i);
+ store.setDetectorSettingsOffset(detectorOffset.get(c), s, i);
- store.setChannelName(channelName.get(channelIndex + i), s, i);
- store.setChannelEmissionWavelength(emWavelength.get(i), s, i);
- store.setChannelExcitationWavelength(exWavelength.get(i), s, i);
+ store.setChannelName(channelName.get(c), s, i);
+ store.setChannelEmissionWavelength(emWavelength.get(c), s, i);
+ store.setChannelExcitationWavelength(exWavelength.get(c), s, i);
}
}
for (int i=0; i<getSeriesCount(); i++) {
store.setImageInstrumentRef(instrumentID, i);
store.setImageObjectiveSettingsID(objectiveID, i);
if (imageDescription != null) {
store.setImageDescription(imageDescription, i);
}
if (getSeriesCount() > 1) {
store.setImageName("Tile #" + (i + 1), i);
}
if (physicalSizeX != null && physicalSizeX > 0) {
store.setPixelsPhysicalSizeX(new PositiveFloat(physicalSizeX), i);
}
if (physicalSizeY != null && physicalSizeY > 0) {
store.setPixelsPhysicalSizeY(new PositiveFloat(physicalSizeY), i);
}
if (physicalSizeZ != null && physicalSizeZ > 0) {
store.setPixelsPhysicalSizeZ(new PositiveFloat(physicalSizeZ), i);
}
long firstStamp = parseTimestamp(timestamps.get(new Integer(0)));
for (int plane=0; plane<getImageCount(); plane++) {
int[] zct = getZCTCoords(plane);
String exposure =
exposureTime.get(new Integer(zct[1] + channelIndex));
if (exposure == null && exposureTime.size() == 1) {
exposure = exposureTime.get(exposureTime.keys().nextElement());
}
Double exp = new Double(0.0);
try { exp = new Double(exposure); }
catch (NumberFormatException e) { }
catch (NullPointerException e) { }
store.setPlaneExposureTime(exp, i, plane);
int posIndex = i * getImageCount() + plane;
if (posIndex < timestamps.size()) {
String timestamp = timestamps.get(new Integer(posIndex));
long stamp = parseTimestamp(timestamp);
stamp -= firstStamp;
store.setPlaneDeltaT(new Double(stamp / 1600000), i, plane);
}
if (stageX.get(posIndex) != null) {
store.setPlanePositionX(stageX.get(posIndex), i, plane);
}
if (stageY.get(posIndex) != null) {
store.setPlanePositionY(stageY.get(posIndex), i, plane);
}
}
}
for (int i=0; i<getSeriesCount(); i++) {
for (int roi=0; roi<roiIDs.size(); roi++) {
store.setImageROIRef(roiIDs.get(roi), i, roi);
}
}
}
}
private int getImageNumber(String dirName, int defaultNumber) {
if (dirName.toUpperCase().indexOf("ITEM") != -1) {
int open = dirName.indexOf("(");
int close = dirName.indexOf(")");
if (open < 0 || close < 0 || close < open) return defaultNumber;
return Integer.parseInt(dirName.substring(open + 1, close));
}
return defaultNumber;
}
private String getNextTag(RandomAccessInputStream s) throws IOException {
int type = s.readShort();
switch (type) {
case 0:
case 1:
return "";
case 2:
return String.valueOf(s.readShort());
case 3:
case 22:
case 23:
return String.valueOf(s.readInt());
case 4:
return String.valueOf(s.readFloat());
case 5:
return String.valueOf(s.readDouble());
case 7:
case 20:
case 21:
return String.valueOf(s.readLong());
case 8:
case 69:
int len = s.readInt();
return s.readString(len);
case 9:
case 13:
s.skipBytes(16);
return "";
case 63:
case 65:
len = s.readInt();
s.skipBytes(len);
return "";
case 66:
len = s.readShort();
return s.readString(len);
default:
long old = s.getFilePointer();
while (s.readShort() != 3 &&
s.getFilePointer() + 2 < s.length());
long fp = s.getFilePointer() - 2;
s.seek(old - 2);
return s.readString((int) (fp - old + 2));
}
}
/** Parse all of the tags in a stream. */
private void parseTags(int image, String file, MetadataStore store)
throws FormatException, IOException
{
RandomAccessInputStream s = poi.getDocumentStream(file);
s.order(true);
s.seek(8);
int count = s.readInt();
int effectiveSizeC = 0;
try {
effectiveSizeC = getEffectiveSizeC();
}
catch (ArithmeticException e) { }
for (int i=0; i<count; i++) {
if (s.getFilePointer() + 2 >= s.length()) break;
String value = DataTools.stripString(getNextTag(s));
s.skipBytes(2);
int tagID = s.readInt();
s.skipBytes(6);
try {
String key = getKey(tagID);
if (key.equals("Image Channel Index")) {
cIndex = Integer.parseInt(value);
int v = 0;
while (getGlobalMeta(key + " " + v) != null) v++;
if (!getGlobalMetadata().containsValue(cIndex)) {
addGlobalMeta(key + " " + v, cIndex);
}
continue;
}
else if (key.equals("ImageWidth")) {
int v = Integer.parseInt(value);
if (getSizeX() == 0 || v < getSizeX()) {
core[0].sizeX = v;
}
if (realWidth == 0 && v > realWidth) realWidth = v;
}
else if (key.equals("ImageHeight")) {
int v = Integer.parseInt(value);
if (getSizeY() == 0 || v < getSizeY()) core[0].sizeY = v;
if (realHeight == 0 || v > realHeight) realHeight = v;
}
if (cIndex != -1) key += " " + cIndex;
addGlobalMeta(key, value);
if (key.startsWith("ImageTile") && !(store instanceof DummyMetadata)) {
if (!tiles.containsKey(new Integer(value))) {
tiles.put(new Integer(value), new Integer(1));
}
else {
int v = tiles.get(new Integer(value)).intValue() + 1;
tiles.put(new Integer(value), new Integer(v));
}
}
if (key.startsWith("MultiChannel Color")) {
if (cIndex >= 0 && cIndex < effectiveSizeC) {
if (channelColors == null ||
effectiveSizeC > channelColors.length)
{
channelColors = new int[effectiveSizeC];
}
channelColors[cIndex] = Integer.parseInt(value);
}
}
else if (key.startsWith("Scale Factor for X") && physicalSizeX == null)
{
physicalSizeX = Double.parseDouble(value);
}
else if (key.startsWith("Scale Factor for Y") && physicalSizeY == null)
{
physicalSizeY = Double.parseDouble(value);
}
else if (key.startsWith("Scale Factor for Z") && physicalSizeZ == null)
{
physicalSizeZ = Double.parseDouble(value);
}
else if (key.startsWith("Emission Wavelength")) {
if (cIndex != -1) {
Integer wave = new Integer(value);
if (wave.intValue() > 0) {
emWavelength.put(cIndex, new PositiveInteger(wave));
}
}
}
else if (key.startsWith("Excitation Wavelength")) {
if (cIndex != -1) {
Integer wave = new Integer((int) Double.parseDouble(value));
if (wave.intValue() > 0) {
exWavelength.put(cIndex, new PositiveInteger(wave));
}
}
}
else if (key.startsWith("Channel Name")) {
if (cIndex != -1) {
channelName.put(cIndex, value);
}
}
else if (key.startsWith("Exposure Time [ms]")) {
if (exposureTime.get(new Integer(cIndex)) == null) {
double exp = Double.parseDouble(value) / 1000;
exposureTime.put(new Integer(cIndex), String.valueOf(exp));
}
}
else if (key.startsWith("User Name")) {
String[] username = value.split(" ");
if (username.length >= 2) {
store.setExperimenterFirstName(username[0], 0);
store.setExperimenterLastName(username[username.length - 1], 0);
}
}
else if (key.equals("User company")) {
store.setExperimenterInstitution(value, 0);
}
else if (key.startsWith("Objective Magnification")) {
int magnification = (int) Double.parseDouble(value);
if (magnification > 0) {
store.setObjectiveNominalMagnification(
new PositiveInteger(magnification), 0, 0);
}
}
else if (key.startsWith("Objective ID")) {
store.setObjectiveID("Objective:" + value, 0, 0);
store.setObjectiveCorrection(getCorrection("Other"), 0, 0);
store.setObjectiveImmersion(getImmersion("Other"), 0, 0);
}
else if (key.startsWith("Objective N.A.")) {
store.setObjectiveLensNA(new Double(value), 0, 0);
}
else if (key.startsWith("Objective Name")) {
String[] tokens = value.split(" ");
for (int q=0; q<tokens.length; q++) {
int slash = tokens[q].indexOf("/");
if (slash != -1 && slash - q > 0) {
int mag = (int)
Double.parseDouble(tokens[q].substring(0, slash - q));
String na = tokens[q].substring(slash + 1);
store.setObjectiveNominalMagnification(
new PositiveInteger(mag), 0, 0);
store.setObjectiveLensNA(new Double(na), 0, 0);
store.setObjectiveCorrection(getCorrection(tokens[q - 1]), 0, 0);
break;
}
}
}
else if (key.startsWith("Objective Working Distance")) {
store.setObjectiveWorkingDistance(new Double(value), 0, 0);
}
else if (key.startsWith("Objective Immersion Type")) {
String immersion = "Other";
switch (Integer.parseInt(value)) {
// case 1: no immersion
case 2:
immersion = "Oil";
break;
case 3:
immersion = "Water";
break;
}
store.setObjectiveImmersion(getImmersion(immersion), 0, 0);
}
else if (key.startsWith("Stage Position X")) {
stageX.put(image, new Double(value));
addGlobalMeta("X position for position #" + stageX.size(), value);
}
else if (key.startsWith("Stage Position Y")) {
stageY.put(image, new Double(value));
addGlobalMeta("Y position for position #" + stageY.size(), value);
}
else if (key.startsWith("Orca Analog Gain")) {
detectorGain.put(cIndex, new Double(value));
}
else if (key.startsWith("Orca Analog Offset")) {
detectorOffset.put(cIndex, new Double(value));
}
else if (key.startsWith("Comments")) {
imageDescription = value;
}
else if (key.startsWith("Acquisition Date")) {
if (timepoint > 0) {
timestamps.put(new Integer(timepoint - 1), value);
addGlobalMeta("Timestamp " + timepoint, value);
}
timepoint++;
}
}
catch (NumberFormatException e) { }
}
s.close();
}
/**
* Parse ROI data from the given RandomAccessInputStream and store it in the
* given MetadataStore.
*/
private void parseROIs(int imageNum, String name, MetadataStore store)
throws IOException
{
MetadataLevel level = getMetadataOptions().getMetadataLevel();
if (level == MetadataLevel.MINIMUM || level == MetadataLevel.NO_OVERLAYS) {
return;
}
RandomAccessInputStream s = poi.getDocumentStream(name);
s.order(true);
// scan stream for offsets to each ROI
Vector<Long> roiOffsets = new Vector<Long>();
s.seek(0);
while (s.getFilePointer() < s.length() - 8) {
// find next ROI signature
long signature = s.readLong() & 0xffffffffffffffffL;
while (signature != ROI_SIGNATURE) {
if (s.getFilePointer() >= s.length()) break;
s.seek(s.getFilePointer() - 6);
signature = s.readLong() & 0xffffffffffffffffL;
}
if (s.getFilePointer() < s.length()) {
roiOffsets.add(new Long(s.getFilePointer()));
}
}
int shapeIndex = 0;
for (int shape=0; shape<roiOffsets.size(); shape++) {
s.seek(roiOffsets.get(shape).longValue() + 18);
int length = s.readInt();
s.skipBytes(length + 10);
int roiType = s.readInt();
s.skipBytes(8);
// read the bounding box
int x = s.readInt();
int y = s.readInt();
int w = s.readInt() - x;
int h = s.readInt() - y;
// read text label and font data
long nextOffset = shape < roiOffsets.size() - 1 ?
roiOffsets.get(shape + 1).longValue() : s.length();
long nameBlock = s.getFilePointer();
long fontBlock = s.getFilePointer();
long lastBlock = s.getFilePointer();
while (s.getFilePointer() < nextOffset - 1) {
while (s.readShort() != 8) {
if (s.getFilePointer() >= nextOffset) break;
}
if (s.getFilePointer() >= nextOffset) break;
if (s.getFilePointer() - lastBlock > 64 && lastBlock != fontBlock) {
break;
}
nameBlock = fontBlock;
fontBlock = lastBlock;
lastBlock = s.getFilePointer();
}
s.seek(nameBlock);
int strlen = s.readInt();
if (strlen + s.getFilePointer() > s.length()) continue;
String roiName = DataTools.stripString(s.readString(strlen));
s.seek(fontBlock);
int fontLength = s.readInt();
String fontName = DataTools.stripString(s.readString(fontLength));
s.skipBytes(2);
int typeLength = s.readInt();
s.skipBytes(typeLength);
// read list of points that define this ROI
s.skipBytes(10);
int nPoints = s.readInt();
s.skipBytes(6);
String roiID = MetadataTools.createLSID("ROI", imageNum);
String shapeID = MetadataTools.createLSID("Shape", imageNum, shapeIndex);
roiIDs.add(roiID);
if (roiType == ELLIPSE) {
store.setROIID(roiID, imageNum);
store.setEllipseID(shapeID, imageNum, shapeIndex);
store.setEllipseX(new Double(x + (w / 2)), imageNum, shapeIndex);
store.setEllipseY(new Double(y + (h / 2)), imageNum, shapeIndex);
store.setEllipseRadiusX(new Double(w / 2), imageNum, shapeIndex);
store.setEllipseRadiusY(new Double(h / 2), imageNum, shapeIndex);
shapeIndex++;
}
else if (roiType == CURVE || roiType == OUTLINE ||
roiType == OUTLINE_SPLINE)
{
store.setROIID(roiID, imageNum);
StringBuffer points = new StringBuffer();
for (int p=0; p<nPoints; p++) {
double px = s.readDouble();
double py = s.readDouble();
points.append(px);
points.append(",");
points.append(py);
if (p < nPoints - 1) points.append(" ");
}
store.setPolylineID(shapeID, imageNum, shapeIndex);
store.setPolylinePoints(points.toString(), imageNum, shapeIndex);
store.setPolylineClosed(roiType != CURVE, imageNum, shapeIndex);
shapeIndex++;
}
else if (roiType == RECTANGLE || roiType == TEXT) {
store.setROIID(roiID, imageNum);
store.setRectangleID(shapeID, imageNum, shapeIndex);
store.setRectangleX(new Double(x), imageNum, shapeIndex);
store.setRectangleY(new Double(y), imageNum, shapeIndex);
store.setRectangleWidth(new Double(w), imageNum, shapeIndex);
store.setRectangleHeight(new Double(h), imageNum, shapeIndex);
shapeIndex++;
}
else if (roiType == LINE || roiType == SCALE_BAR) {
store.setROIID(roiID, imageNum);
double x1 = s.readDouble();
double y1 = s.readDouble();
double x2 = s.readDouble();
double y2 = s.readDouble();
store.setLineID(shapeID, imageNum, shapeIndex);
store.setLineX1(x1, imageNum, shapeIndex);
store.setLineY1(y1, imageNum, shapeIndex);
store.setLineX2(x2, imageNum, shapeIndex);
store.setLineY2(y2, imageNum, shapeIndex);
shapeIndex++;
}
}
s.close();
}
/** Return the string corresponding to the given ID. */
private String getKey(int tagID) {
switch (tagID) {
case 222: return "Compression";
case 258: return "BlackValue";
case 259: return "WhiteValue";
case 260: return "ImageDataMappingAutoRange";
case 261: return "Thumbnail";
case 262: return "GammaValue";
case 264: return "ImageOverExposure";
case 265: return "ImageRelativeTime1";
case 266: return "ImageRelativeTime2";
case 267: return "ImageRelativeTime3";
case 268: return "ImageRelativeTime4";
case 333: return "RelFocusPosition1";
case 334: return "RelFocusPosition2";
case 513: return "ObjectType";
case 515: return "ImageWidth";
case 516: return "ImageHeight";
case 517: return "Number Raw Count";
case 518: return "PixelType";
case 519: return "NumberOfRawImages";
case 520: return "ImageSize";
case 523: return "Acquisition pause annotation";
case 530: return "Document Subtype";
case 531: return "Acquisition Bit Depth";
case 532: return "Image Memory Usage (RAM)";
case 534: return "Z-Stack single representative";
case 769: return "Scale Factor for X";
case 770: return "Scale Unit for X";
case 771: return "Scale Width";
case 772: return "Scale Factor for Y";
case 773: return "Scale Unit for Y";
case 774: return "Scale Height";
case 775: return "Scale Factor for Z";
case 776: return "Scale Unit for Z";
case 777: return "Scale Depth";
case 778: return "Scaling Parent";
case 1001: return "Date";
case 1002: return "code";
case 1003: return "Source";
case 1004: return "Message";
case 1025: return "Acquisition Date";
case 1026: return "8-bit acquisition";
case 1027: return "Camera Bit Depth";
case 1029: return "MonoReferenceLow";
case 1030: return "MonoReferenceHigh";
case 1031: return "RedReferenceLow";
case 1032: return "RedReferenceHigh";
case 1033: return "GreenReferenceLow";
case 1034: return "GreenReferenceHigh";
case 1035: return "BlueReferenceLow";
case 1036: return "BlueReferenceHigh";
case 1041: return "FrameGrabber Name";
case 1042: return "Camera";
case 1044: return "CameraTriggerSignalType";
case 1045: return "CameraTriggerEnable";
case 1046: return "GrabberTimeout";
case 1281: return "MultiChannelEnabled";
case 1282: return "MultiChannel Color";
case 1283: return "MultiChannel Weight";
case 1284: return "Channel Name";
case 1536: return "DocumentInformationGroup";
case 1537: return "Title";
case 1538: return "Author";
case 1539: return "Keywords";
case 1540: return "Comments";
case 1541: return "SampleID";
case 1542: return "Subject";
case 1543: return "RevisionNumber";
case 1544: return "Save Folder";
case 1545: return "FileLink";
case 1546: return "Document Type";
case 1547: return "Storage Media";
case 1548: return "File ID";
case 1549: return "Reference";
case 1550: return "File Date";
case 1551: return "File Size";
case 1553: return "Filename";
case 1792: return "ProjectGroup";
case 1793: return "Acquisition Date";
case 1794: return "Last modified by";
case 1795: return "User company";
case 1796: return "User company logo";
case 1797: return "Image";
case 1800: return "User ID";
case 1801: return "User Name";
case 1802: return "User City";
case 1803: return "User Address";
case 1804: return "User Country";
case 1805: return "User Phone";
case 1806: return "User Fax";
case 2049: return "Objective Name";
case 2050: return "Optovar";
case 2051: return "Reflector";
case 2052: return "Condenser Contrast";
case 2053: return "Transmitted Light Filter 1";
case 2054: return "Transmitted Light Filter 2";
case 2055: return "Reflected Light Shutter";
case 2056: return "Condenser Front Lens";
case 2057: return "Excitation Filter Name";
case 2060: return "Transmitted Light Fieldstop Aperture";
case 2061: return "Reflected Light Aperture";
case 2062: return "Condenser N.A.";
case 2063: return "Light Path";
case 2064: return "HalogenLampOn";
case 2065: return "Halogen Lamp Mode";
case 2066: return "Halogen Lamp Voltage";
case 2068: return "Fluorescence Lamp Level";
case 2069: return "Fluorescence Lamp Intensity";
case 2070: return "LightManagerEnabled";
case 2071: return "tag_ID_2071";
case 2072: return "Focus Position";
case 2073: return "Stage Position X";
case 2074: return "Stage Position Y";
case 2075: return "Microscope Name";
case 2076: return "Objective Magnification";
case 2077: return "Objective N.A.";
case 2078: return "MicroscopeIllumination";
case 2079: return "External Shutter 1";
case 2080: return "External Shutter 2";
case 2081: return "External Shutter 3";
case 2082: return "External Filter Wheel 1 Name";
case 2083: return "External Filter Wheel 2 Name";
case 2084: return "Parfocal Correction";
case 2086: return "External Shutter 4";
case 2087: return "External Shutter 5";
case 2088: return "External Shutter 6";
case 2089: return "External Filter Wheel 3 Name";
case 2090: return "External Filter Wheel 4 Name";
case 2103: return "Objective Turret Position";
case 2104: return "Objective Contrast Method";
case 2105: return "Objective Immersion Type";
case 2107: return "Reflector Position";
case 2109: return "Transmitted Light Filter 1 Position";
case 2110: return "Transmitted Light Filter 2 Position";
case 2112: return "Excitation Filter Position";
case 2113: return "Lamp Mirror Position";
case 2114: return "External Filter Wheel 1 Position";
case 2115: return "External Filter Wheel 2 Position";
case 2116: return "External Filter Wheel 3 Position";
case 2117: return "External Filter Wheel 4 Position";
case 2118: return "Lightmanager Mode";
case 2119: return "Halogen Lamp Calibration";
case 2120: return "CondenserNAGoSpeed";
case 2121: return "TransmittedLightFieldstopGoSpeed";
case 2122: return "OptovarGoSpeed";
case 2123: return "Focus calibrated";
case 2124: return "FocusBasicPosition";
case 2125: return "FocusPower";
case 2126: return "FocusBacklash";
case 2127: return "FocusMeasurementOrigin";
case 2128: return "FocusMeasurementDistance";
case 2129: return "FocusSpeed";
case 2130: return "FocusGoSpeed";
case 2131: return "FocusDistance";
case 2132: return "FocusInitPosition";
case 2133: return "Stage calibrated";
case 2134: return "StagePower";
case 2135: return "StageXBacklash";
case 2136: return "StageYBacklash";
case 2137: return "StageSpeedX";
case 2138: return "StageSpeedY";
case 2139: return "StageSpeed";
case 2140: return "StageGoSpeedX";
case 2141: return "StageGoSpeedY";
case 2142: return "StageStepDistanceX";
case 2143: return "StageStepDistanceY";
case 2144: return "StageInitialisationPositionX";
case 2145: return "StageInitialisationPositionY";
case 2146: return "MicroscopeMagnification";
case 2147: return "ReflectorMagnification";
case 2148: return "LampMirrorPosition";
case 2149: return "FocusDepth";
case 2150: return "MicroscopeType";
case 2151: return "Objective Working Distance";
case 2152: return "ReflectedLightApertureGoSpeed";
case 2153: return "External Shutter";
case 2154: return "ObjectiveImmersionStop";
case 2155: return "Focus Start Speed";
case 2156: return "Focus Acceleration";
case 2157: return "ReflectedLightFieldstop";
case 2158: return "ReflectedLightFieldstopGoSpeed";
case 2159: return "ReflectedLightFilter 1";
case 2160: return "ReflectedLightFilter 2";
case 2161: return "ReflectedLightFilter1Position";
case 2162: return "ReflectedLightFilter2Position";
case 2163: return "TransmittedLightAttenuator";
case 2164: return "ReflectedLightAttenuator";
case 2165: return "Transmitted Light Shutter";
case 2166: return "TransmittedLightAttenuatorGoSpeed";
case 2167: return "ReflectedLightAttenuatorGoSpeed";
case 2176: return "TransmittedLightVirtualFilterPosition";
case 2177: return "TransmittedLightVirtualFilter";
case 2178: return "ReflectedLightVirtualFilterPosition";
case 2179: return "ReflectedLightVirtualFilter";
case 2180: return "ReflectedLightHalogenLampMode";
case 2181: return "ReflectedLightHalogenLampVoltage";
case 2182: return "ReflectedLightHalogenLampColorTemperature";
case 2183: return "ContrastManagerMode";
case 2184: return "Dazzle Protection Active";
case 2195: return "Zoom";
case 2196: return "ZoomGoSpeed";
case 2197: return "LightZoom";
case 2198: return "LightZoomGoSpeed";
case 2199: return "LightZoomCoupled";
case 2200: return "TransmittedLightHalogenLampMode";
case 2201: return "TransmittedLightHalogenLampVoltage";
case 2202: return "TransmittedLightHalogenLampColorTemperature";
case 2203: return "Reflected Coldlight Mode";
case 2204: return "Reflected Coldlight Intensity";
case 2205: return "Reflected Coldlight Color Temperature";
case 2206: return "Transmitted Coldlight Mode";
case 2207: return "Transmitted Coldlight Intensity";
case 2208: return "Transmitted Coldlight Color Temperature";
case 2209: return "Infinityspace Portchanger Position";
case 2210: return "Beamsplitter Infinity Space";
case 2211: return "TwoTv VisCamChanger Position";
case 2212: return "Beamsplitter Ocular";
case 2213: return "TwoTv CamerasChanger Position";
case 2214: return "Beamsplitter Cameras";
case 2215: return "Ocular Shutter";
case 2216: return "TwoTv CamerasChangerCube";
case 2218: return "Ocular Magnification";
case 2219: return "Camera Adapter Magnification";
case 2220: return "Microscope Port";
case 2221: return "Ocular Total Magnification";
case 2222: return "Field of View";
case 2223: return "Ocular";
case 2224: return "CameraAdapter";
case 2225: return "StageJoystickEnabled";
case 2226: return "ContrastManager Contrast Method";
case 2229: return "CamerasChanger Beamsplitter Type";
case 2235: return "Rearport Slider Position";
case 2236: return "Rearport Source";
case 2237: return "Beamsplitter Type Infinity Space";
case 2238: return "Fluorescence Attenuator";
case 2239: return "Fluorescence Attenuator Position";
case 2261: return "Objective ID";
case 2262: return "Reflector ID";
case 2307: return "Camera Framestart Left";
case 2308: return "Camera Framestart Top";
case 2309: return "Camera Frame Width";
case 2310: return "Camera Frame Height";
case 2311: return "Camera Binning";
case 2312: return "CameraFrameFull";
case 2313: return "CameraFramePixelDistance";
case 2318: return "DataFormatUseScaling";
case 2319: return "CameraFrameImageOrientation";
case 2320: return "VideoMonochromeSignalType";
case 2321: return "VideoColorSignalType";
case 2322: return "MeteorChannelInput";
case 2323: return "MeteorChannelSync";
case 2324: return "WhiteBalanceEnabled";
case 2325: return "CameraWhiteBalanceRed";
case 2326: return "CameraWhiteBalanceGreen";
case 2327: return "CameraWhiteBalanceBlue";
case 2331: return "CameraFrameScalingFactor";
case 2562: return "Meteor Camera Type";
case 2564: return "Exposure Time [ms]";
case 2568: return "CameraExposureTimeAutoCalculate";
case 2569: return "Meteor Gain Value";
case 2571: return "Meteor Gain Automatic";
case 2572: return "MeteorAdjustHue";
case 2573: return "MeteorAdjustSaturation";
case 2574: return "MeteorAdjustRedLow";
case 2575: return "MeteorAdjustGreenLow";
case 2576: return "Meteor Blue Low";
case 2577: return "MeteorAdjustRedHigh";
case 2578: return "MeteorAdjustGreenHigh";
case 2579: return "MeteorBlue High";
case 2582: return "CameraExposureTimeCalculationControl";
case 2585: return "AxioCamFadingCorrectionEnable";
case 2587: return "CameraLiveImage";
case 2588: return "CameraLiveEnabled";
case 2589: return "LiveImageSyncObjectName";
case 2590: return "CameraLiveSpeed";
case 2591: return "CameraImage";
case 2592: return "CameraImageWidth";
case 2593: return "CameraImageHeight";
case 2594: return "CameraImagePixelType";
case 2595: return "CameraImageShMemoryName";
case 2596: return "CameraLiveImageWidth";
case 2597: return "CameraLiveImageHeight";
case 2598: return "CameraLiveImagePixelType";
case 2599: return "CameraLiveImageShMemoryName";
case 2600: return "CameraLiveMaximumSpeed";
case 2601: return "CameraLiveBinning";
case 2602: return "CameraLiveGainValue";
case 2603: return "CameraLiveExposureTimeValue";
case 2604: return "CameraLiveScalingFactor";
case 2819: return "Image Index Z";
case 2820: return "Image Channel Index";
case 2821: return "Image Index T";
case 2822: return "ImageTile Index";
case 2823: return "Image acquisition Index";
case 2827: return "Image IndexS";
case 2841: return "Original Stage Position X";
case 2842: return "Original Stage Position Y";
case 3088: return "LayerDrawFlags";
case 3334: return "RemainingTime";
case 3585: return "User Field 1";
case 3586: return "User Field 2";
case 3587: return "User Field 3";
case 3588: return "User Field 4";
case 3589: return "User Field 5";
case 3590: return "User Field 6";
case 3591: return "User Field 7";
case 3592: return "User Field 8";
case 3593: return "User Field 9";
case 3594: return "User Field 10";
case 3840: return "ID";
case 3841: return "Name";
case 3842: return "Value";
case 5501: return "PvCamClockingMode";
case 8193: return "Autofocus Status Report";
case 8194: return "Autofocus Position";
case 8195: return "Autofocus Position Offset";
case 8196: return "Autofocus Empty Field Threshold";
case 8197: return "Autofocus Calibration Name";
case 8198: return "Autofocus Current Calibration Item";
case 20478: return "tag_ID_20478";
case 65537: return "CameraFrameFullWidth";
case 65538: return "CameraFrameFullHeight";
case 65541: return "AxioCam Shutter Signal";
case 65542: return "AxioCam Delay Time";
case 65543: return "AxioCam Shutter Control";
case 65544: return "AxioCam BlackRefIsCalculated";
case 65545: return "AxioCam Black Reference";
case 65547: return "Camera Shading Correction";
case 65550: return "AxioCam Enhance Color";
case 65551: return "AxioCam NIR Mode";
case 65552: return "CameraShutterCloseDelay";
case 65553: return "CameraWhiteBalanceAutoCalculate";
case 65556: return "AxioCam NIR Mode Available";
case 65557: return "AxioCam Fading Correction Available";
case 65559: return "AxioCam Enhance Color Available";
case 65565: return "MeteorVideoNorm";
case 65566: return "MeteorAdjustWhiteReference";
case 65567: return "MeteorBlackReference";
case 65568: return "MeteorChannelInputCountMono";
case 65570: return "MeteorChannelInputCountRGB";
case 65571: return "MeteorEnableVCR";
case 65572: return "Meteor Brightness";
case 65573: return "Meteor Contrast";
case 65575: return "AxioCam Selector";
case 65576: return "AxioCam Type";
case 65577: return "AxioCam Info";
case 65580: return "AxioCam Resolution";
case 65581: return "AxioCam Color Model";
case 65582: return "AxioCam MicroScanning";
case 65585: return "Amplification Index";
case 65586: return "Device Command";
case 65587: return "BeamLocation";
case 65588: return "ComponentType";
case 65589: return "ControllerType";
case 65590: return "CameraWhiteBalanceCalculationRedPaint";
case 65591: return "CameraWhiteBalanceCalculationBluePaint";
case 65592: return "CameraWhiteBalanceSetRed";
case 65593: return "CameraWhiteBalanceSetGreen";
case 65594: return "CameraWhiteBalanceSetBlue";
case 65595: return "CameraWhiteBalanceSetTargetRed";
case 65596: return "CameraWhiteBalanceSetTargetGreen";
case 65597: return "CameraWhiteBalanceSetTargetBlue";
case 65598: return "ApotomeCamCalibrationMode";
case 65599: return "ApoTome Grid Position";
case 65600: return "ApotomeCamScannerPosition";
case 65601: return "ApoTome Full Phase Shift";
case 65602: return "ApoTome Grid Name";
case 65603: return "ApoTome Staining";
case 65604: return "ApoTome Processing Mode";
case 65605: return "ApotomeCamLiveCombineMode";
case 65606: return "ApoTome Filter Name";
case 65607: return "Apotome Filter Strength";
case 65608: return "ApotomeCamFilterHarmonics";
case 65609: return "ApoTome Grating Period";
case 65610: return "ApoTome Auto Shutter Used";
case 65611: return "Apotome Cam Status";
case 65612: return "ApotomeCamNormalize";
case 65613: return "ApotomeCamSettingsManager";
case 65614: return "DeepviewCamSupervisorMode";
case 65615: return "DeepView Processing";
case 65616: return "DeepviewCamFilterName";
case 65617: return "DeepviewCamStatus";
case 65618: return "DeepviewCamSettingsManager";
case 65619: return "DeviceScalingName";
case 65620: return "CameraShadingIsCalculated";
case 65621: return "CameraShadingCalculationName";
case 65622: return "CameraShadingAutoCalculate";
case 65623: return "CameraTriggerAvailable";
case 65626: return "CameraShutterAvailable";
case 65627: return "AxioCam ShutterMicroScanningEnable";
case 65628: return "ApotomeCamLiveFocus";
case 65629: return "DeviceInitStatus";
case 65630: return "DeviceErrorStatus";
case 65631: return "ApotomeCamSliderInGridPosition";
case 65632: return "Orca NIR Mode Used";
case 65633: return "Orca Analog Gain";
case 65634: return "Orca Analog Offset";
case 65635: return "Orca Binning";
case 65636: return "Orca Bit Depth";
case 65637: return "ApoTome Averaging Count";
case 65638: return "DeepView DoF";
case 65639: return "DeepView EDoF";
case 65643: return "DeepView Slider Name";
case 65655: return "DeepView Slider Name";
case 5439491: return "Acquisition Sofware";
case 16777488: return "Excitation Wavelength";
case 16777489: return "Emission Wavelength";
case 101515267: return "File Name";
case 101253123:
case 101777411:
return "Image Name";
default: return "" + tagID;
}
}
private long parseTimestamp(String s) {
long stamp = 0;
try {
stamp = Long.parseLong(s);
}
catch (NumberFormatException exc) {
if (s != null) {
stamp = DateTools.getTime(s, "M/d/y h:mm:ss aa");
}
}
return stamp;
}
}
| false | false | null | null |
diff --git a/src/main/java/org/powertac/householdcustomer/customers/Village.java b/src/main/java/org/powertac/householdcustomer/customers/Village.java
index 6459723..bf1d2fc 100644
--- a/src/main/java/org/powertac/householdcustomer/customers/Village.java
+++ b/src/main/java/org/powertac/householdcustomer/customers/Village.java
@@ -1,1527 +1,1528 @@
/*
* Copyright 2009-2012 the original author or authors.
*
* 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.powertac.householdcustomer.customers;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Properties;
import java.util.Random;
import java.util.Vector;
import org.apache.log4j.Logger;
import org.joda.time.Instant;
import org.powertac.common.AbstractCustomer;
import org.powertac.common.CustomerInfo;
import org.powertac.common.Tariff;
import org.powertac.common.TariffSubscription;
import org.powertac.common.TimeService;
import org.powertac.common.Timeslot;
import org.powertac.common.WeatherReport;
import org.powertac.common.enumerations.PowerType;
import org.powertac.common.repo.TimeslotRepo;
import org.powertac.common.repo.WeatherReportRepo;
import org.powertac.common.spring.SpringApplicationContext;
import org.powertac.householdcustomer.configurations.VillageConstants;
import org.springframework.beans.factory.annotation.Autowired;
/**
* The village domain class is a set of households that comprise a small village
* that consumes aggregated energy by the appliances installed in each
* household.
*
* @author Antonios Chrysopoulos
* @version 1.5, Date: 2.25.12
*/
public class Village extends AbstractCustomer
{
/**
* logger for trace logging -- use log.info(), log.warn(), and log.error()
* appropriately. Use log.debug() for output you want to see in testing or
* debugging.
*/
static protected Logger log = Logger.getLogger(Village.class.getName());
@Autowired
TimeService timeService;
@Autowired
TimeslotRepo timeslotRepo;
@Autowired
WeatherReportRepo weatherReportRepo;
/**
* These are the vectors containing aggregated each day's base load from the
* appliances installed inside the households of each type.
**/
Vector<Vector<Long>> aggDailyBaseLoadNS = new Vector<Vector<Long>>();
Vector<Vector<Long>> aggDailyBaseLoadRaS = new Vector<Vector<Long>>();
Vector<Vector<Long>> aggDailyBaseLoadReS = new Vector<Vector<Long>>();
Vector<Vector<Long>> aggDailyBaseLoadSS = new Vector<Vector<Long>>();
/**
* These are the vectors containing aggregated each day's controllable load
* from the appliances installed inside the households.
**/
Vector<Vector<Long>> aggDailyControllableLoadNS = new Vector<Vector<Long>>();
Vector<Vector<Long>> aggDailyControllableLoadRaS = new Vector<Vector<Long>>();
Vector<Vector<Long>> aggDailyControllableLoadReS = new Vector<Vector<Long>>();
Vector<Vector<Long>> aggDailyControllableLoadSS = new Vector<Vector<Long>>();
/**
* These are the vectors containing aggregated each day's weather sensitive
* load from the appliances installed inside the households.
**/
Vector<Vector<Long>> aggDailyWeatherSensitiveLoadNS = new Vector<Vector<Long>>();
Vector<Vector<Long>> aggDailyWeatherSensitiveLoadRaS = new Vector<Vector<Long>>();
Vector<Vector<Long>> aggDailyWeatherSensitiveLoadReS = new Vector<Vector<Long>>();
Vector<Vector<Long>> aggDailyWeatherSensitiveLoadSS = new Vector<Vector<Long>>();
/**
* These are the aggregated vectors containing each day's base load of all the
* households in hours.
**/
Vector<Vector<Long>> aggDailyBaseLoadInHoursNS = new Vector<Vector<Long>>();
Vector<Vector<Long>> aggDailyBaseLoadInHoursRaS = new Vector<Vector<Long>>();
Vector<Vector<Long>> aggDailyBaseLoadInHoursReS = new Vector<Vector<Long>>();
Vector<Vector<Long>> aggDailyBaseLoadInHoursSS = new Vector<Vector<Long>>();
/**
* These are the aggregated vectors containing each day's controllable load of
* all the households in hours.
**/
Vector<Vector<Long>> aggDailyControllableLoadInHoursNS = new Vector<Vector<Long>>();
Vector<Vector<Long>> aggDailyControllableLoadInHoursRaS = new Vector<Vector<Long>>();
Vector<Vector<Long>> aggDailyControllableLoadInHoursReS = new Vector<Vector<Long>>();
Vector<Vector<Long>> aggDailyControllableLoadInHoursSS = new Vector<Vector<Long>>();
/**
* These are the aggregated vectors containing each day's weather sensitive
* load of all the households in hours.
**/
Vector<Vector<Long>> aggDailyWeatherSensitiveLoadInHoursNS = new Vector<Vector<Long>>();
Vector<Vector<Long>> aggDailyWeatherSensitiveLoadInHoursRaS = new Vector<Vector<Long>>();
Vector<Vector<Long>> aggDailyWeatherSensitiveLoadInHoursReS = new Vector<Vector<Long>>();
Vector<Vector<Long>> aggDailyWeatherSensitiveLoadInHoursSS = new Vector<Vector<Long>>();
/**
* This is an vector containing the days of the competition that the household
* model will use in order to check which of the tariffs that are available at
* any given moment are the optimal for their consumption or production.
**/
Vector<Integer> daysList = new Vector<Integer>();
/**
* This variable is utilized for the creation of the random numbers and is
* taken from the service.
*/
Random gen;
/**
* These variables are mapping of the characteristics of the types of houses.
* The first is used to keep track of their subscription at any given time.
* The second is the inertia parameter for each type of houses. The third is
* the period that they are evaluating the available tariffs and choose the
* best for their type. The forth is setting the lamda variable for the
* possibility function of the evaluation.
*/
HashMap<String, TariffSubscription> subscriptionMap = new HashMap<String, TariffSubscription>();
HashMap<String, Double> inertiaMap = new HashMap<String, Double>();
HashMap<String, Integer> periodMap = new HashMap<String, Integer>();
HashMap<String, Double> lamdaMap = new HashMap<String, Double>();
/**
* These vectors contain the houses of type in the village. There are 4 types
* available: 1) Not Shifting Houses: They do not change the tariff
* subscriptions during the game. 2) Randomly Shifting Houses: They change
* their tariff subscriptions in a random way. 3) Regularly Shifting Houses:
* They change their tariff subscriptions during the game in regular time
* periods. 4) Smart Shifting Houses: They change their tariff subscriptions
* in a smart way in order to minimize their costs.
*/
Vector<Household> notShiftingHouses = new Vector<Household>();
Vector<Household> randomlyShiftingHouses = new Vector<Household>();
Vector<Household> regularlyShiftingHouses = new Vector<Household>();
Vector<Household> smartShiftingHouses = new Vector<Household>();
/** This is the constructor function of the Village customer */
public Village (CustomerInfo customerInfo)
{
super(customerInfo);
timeslotRepo = (TimeslotRepo) SpringApplicationContext.getBean("timeslotRepo");
timeService = (TimeService) SpringApplicationContext.getBean("timeService");
weatherReportRepo = (WeatherReportRepo) SpringApplicationContext.getBean("weatherReportRepo");
ArrayList<String> typeList = new ArrayList<String>();
typeList.add("NS");
typeList.add("RaS");
typeList.add("ReS");
typeList.add("SS");
for (String type : typeList) {
subscriptionMap.put(type, null);
inertiaMap.put(type, null);
periodMap.put(type, null);
lamdaMap.put(type, null);
}
}
/**
* This is the initialization function. It uses the variable values for the
* configuration file to create the village with its households and then fill
* them with persons and appliances.
*
* @param conf
* @param gen
*/
public void initialize (Properties conf, Random generator)
{
// Initializing variables
int nshouses = Integer.parseInt(conf.getProperty("NotShiftingCustomers"));
int rashouses = Integer.parseInt(conf.getProperty("RegularlyShiftingCustomers"));
int reshouses = Integer.parseInt(conf.getProperty("RandomlyShiftingCustomers"));
int sshouses = Integer.parseInt(conf.getProperty("SmartShiftingCustomers"));
int days = Integer.parseInt(conf.getProperty("PublicVacationDuration"));
gen = generator;
createCostEstimationDaysList(VillageConstants.RANDOM_DAYS_NUMBER);
Vector<Integer> publicVacationVector = createPublicVacationVector(days);
for (int i = 0; i < nshouses; i++) {
log.info("Initializing " + customerInfo.toString() + " NSHouse " + i);
Household hh = new Household();
hh.initialize(customerInfo.toString() + " NSHouse" + i, conf, publicVacationVector, gen);
notShiftingHouses.add(hh);
hh.householdOf = this;
}
for (int i = 0; i < rashouses; i++) {
log.info("Initializing " + customerInfo.toString() + " RaSHouse " + i);
Household hh = new Household();
hh.initialize(customerInfo.toString() + " RaSHouse" + i, conf, publicVacationVector, gen);
randomlyShiftingHouses.add(hh);
hh.householdOf = this;
}
for (int i = 0; i < reshouses; i++) {
log.info("Initializing " + customerInfo.toString() + " ReSHouse " + i);
Household hh = new Household();
hh.initialize(customerInfo.toString() + " ReSHouse" + i, conf, publicVacationVector, gen);
regularlyShiftingHouses.add(hh);
hh.householdOf = this;
}
for (int i = 0; i < sshouses; i++) {
log.info("Initializing " + customerInfo.toString() + " SSHouse " + i);
Household hh = new Household();
hh.initialize(customerInfo.toString() + " SSHouse" + i, conf, publicVacationVector, gen);
smartShiftingHouses.add(hh);
hh.householdOf = this;
}
for (String type : subscriptionMap.keySet()) {
fillAggWeeklyLoad(type);
inertiaMap.put(type, Double.parseDouble(conf.getProperty(type + "Inertia")));
periodMap.put(type, Integer.parseInt(conf.getProperty(type + "Period")));
lamdaMap.put(type, Double.parseDouble(conf.getProperty(type + "Lamda")));
}
/*
System.out.println("Subscriptions:" + subscriptionMap.toString());
System.out.println("Inertia:" + inertiaMap.toString());
System.out.println("Period:" + periodMap.toString());
System.out.println("Lamda:" + lamdaMap.toString());
for (String type : subscriptionMap.keySet()) {
showAggLoad(type);
}
*/
}
// =====SUBSCRIPTION FUNCTIONS===== //
@Override
public void subscribeDefault ()
{
super.subscribeDefault();
List<TariffSubscription> subscriptions = tariffSubscriptionRepo.findSubscriptionsForCustomer(this.getCustomerInfo());
if (subscriptions.size() > 0) {
log.debug(subscriptions.toString());
for (String type : subscriptionMap.keySet()) {
subscriptionMap.put(type, subscriptions.get(0));
}
log.debug(this.toString() + " Default");
log.debug(subscriptionMap.toString());
}
}
/**
* The first implementation of the changing subscription function. Here we
* just put the tariff we want to change and the whole population is moved to
* another random tariff.
*
* @param tariff
*/
public void changeSubscription (Tariff tariff)
{
TariffSubscription ts = tariffSubscriptionRepo.findSubscriptionForTariffAndCustomer(tariff, customerInfo);
int populationCount = ts.getCustomersCommitted();
unsubscribe(ts, populationCount);
Tariff newTariff = selectTariff(tariff.getTariffSpec().getPowerType());
subscribe(newTariff, populationCount);
updateSubscriptions(tariff, newTariff);
}
/**
* The second implementation of the changing subscription function only for
* certain type of the households.
*
* @param tariff
*/
public void changeSubscription (Tariff tariff, String type)
{
TariffSubscription ts = tariffSubscriptionRepo.findSubscriptionForTariffAndCustomer(tariff, customerInfo);
int populationCount = getHouses(type).size();
unsubscribe(ts, populationCount);
Tariff newTariff = selectTariff(tariff.getTariffSpec().getPowerType());
subscribe(newTariff, populationCount);
updateSubscriptions(tariff, newTariff, type);
}
/**
* In this overloaded implementation of the changing subscription function,
* Here we just put the tariff we want to change and the whole population is
* moved to another random tariff.
*
* @param tariff
*/
public void changeSubscription (Tariff tariff, Tariff newTariff)
{
TariffSubscription ts = tariffSubscriptionRepo.getSubscription(customerInfo, tariff);
int populationCount = ts.getCustomersCommitted();
unsubscribe(ts, populationCount);
subscribe(newTariff, populationCount);
updateSubscriptions(tariff, newTariff);
}
/**
* In this overloaded implementation of the changing subscription function
* only certain type of the households.
*
* @param tariff
*/
public void changeSubscription (Tariff tariff, Tariff newTariff, String type)
{
TariffSubscription ts = tariffSubscriptionRepo.getSubscription(customerInfo, tariff);
int populationCount = getHouses(type).size();
unsubscribe(ts, populationCount);
subscribe(newTariff, populationCount);
updateSubscriptions(tariff, newTariff, type);
}
/**
* This function is used to update the subscriptionMap variable with the
* changes made.
*
*/
private void updateSubscriptions (Tariff tariff, Tariff newTariff)
{
TariffSubscription ts = tariffSubscriptionRepo.getSubscription(customerInfo, tariff);
TariffSubscription newTs = tariffSubscriptionRepo.getSubscription(customerInfo, newTariff);
log.debug(this.toString() + " Changing");
log.debug("Old:" + ts.toString() + " New:" + newTs.toString());
if (subscriptionMap.get("NS") == ts || subscriptionMap.get("NS") == null)
subscriptionMap.put("NS", newTs);
if (subscriptionMap.get("RaS") == ts || subscriptionMap.get("RaS") == null)
subscriptionMap.put("RaS", newTs);
if (subscriptionMap.get("ReS") == ts || subscriptionMap.get("ReS") == null)
subscriptionMap.put("ReS", newTs);
if (subscriptionMap.get("SS") == ts || subscriptionMap.get("SS") == null)
subscriptionMap.put("SS", newTs);
log.debug(subscriptionMap.toString());
}
/**
* This function is overloading the previous one and is used when only certain
* types of houses changed tariff.
*
*/
private void updateSubscriptions (Tariff tariff, Tariff newTariff, String type)
{
TariffSubscription ts = tariffSubscriptionRepo.getSubscription(customerInfo, tariff);
TariffSubscription newTs = tariffSubscriptionRepo.getSubscription(customerInfo, newTariff);
if (type.equals("NS")) {
subscriptionMap.put("NS", newTs);
} else if (type.equals("RaS")) {
subscriptionMap.put("RaS", newTs);
} else if (type.equals("ReS")) {
subscriptionMap.put("ReS", newTs);
} else {
subscriptionMap.put("SS", newTs);
}
log.debug(this.toString() + " Changing Only " + type);
log.debug("Old:" + ts.toString() + " New:" + newTs.toString());
log.debug(subscriptionMap.toString());
}
@Override
public void checkRevokedSubscriptions ()
{
List<TariffSubscription> revoked = tariffSubscriptionRepo.getRevokedSubscriptionList(customerInfo);
log.debug(revoked.toString());
for (TariffSubscription revokedSubscription : revoked) {
revokedSubscription.handleRevokedTariff();
Tariff tariff = revokedSubscription.getTariff();
Tariff newTariff = revokedSubscription.getTariff().getIsSupersededBy();
Tariff defaultTariff = tariffMarketService.getDefaultTariff(PowerType.CONSUMPTION);
log.debug("Tariff:" + tariff.toString());
if (newTariff != null)
log.debug("New Tariff:" + newTariff.toString());
else
log.debug("New Tariff is Null");
log.debug("Default Tariff:" + defaultTariff.toString());
if (newTariff == null)
updateSubscriptions(tariff, defaultTariff);
else
updateSubscriptions(tariff, newTariff);
}
}
// =====LOAD FUNCTIONS===== //
/**
* This function is used in order to fill each week day of the aggregated
* daily Load of the village households for each quarter of the hour.
*
* @param type
* @return
*/
void fillAggWeeklyLoad (String type)
{
if (type.equals("NS")) {
for (int i = 0; i < VillageConstants.DAYS_OF_WEEK * (VillageConstants.WEEKS_OF_COMPETITION + VillageConstants.WEEKS_OF_BOOTSTRAP); i++) {
aggDailyBaseLoadNS.add(fillAggDailyBaseLoad(i, type));
aggDailyControllableLoadNS.add(fillAggDailyControllableLoad(i, type));
aggDailyWeatherSensitiveLoadNS.add(fillAggDailyWeatherSensitiveLoad(i, type));
aggDailyBaseLoadInHoursNS.add(fillAggDailyBaseLoadInHours(i, type));
aggDailyControllableLoadInHoursNS.add(fillAggDailyControllableLoadInHours(i, type));
aggDailyWeatherSensitiveLoadInHoursNS.add(fillAggDailyWeatherSensitiveLoadInHours(i, type));
}
} else if (type.equals("RaS")) {
for (int i = 0; i < VillageConstants.DAYS_OF_WEEK * (VillageConstants.WEEKS_OF_COMPETITION + VillageConstants.WEEKS_OF_BOOTSTRAP); i++) {
aggDailyBaseLoadRaS.add(fillAggDailyBaseLoad(i, type));
aggDailyControllableLoadRaS.add(fillAggDailyControllableLoad(i, type));
aggDailyWeatherSensitiveLoadRaS.add(fillAggDailyWeatherSensitiveLoad(i, type));
aggDailyBaseLoadInHoursRaS.add(fillAggDailyBaseLoadInHours(i, type));
aggDailyControllableLoadInHoursRaS.add(fillAggDailyControllableLoadInHours(i, type));
aggDailyWeatherSensitiveLoadInHoursRaS.add(fillAggDailyWeatherSensitiveLoadInHours(i, type));
}
} else if (type.equals("ReS")) {
for (int i = 0; i < VillageConstants.DAYS_OF_WEEK * (VillageConstants.WEEKS_OF_COMPETITION + VillageConstants.WEEKS_OF_BOOTSTRAP); i++) {
aggDailyBaseLoadReS.add(fillAggDailyBaseLoad(i, type));
aggDailyControllableLoadReS.add(fillAggDailyControllableLoad(i, type));
aggDailyWeatherSensitiveLoadReS.add(fillAggDailyWeatherSensitiveLoad(i, type));
aggDailyBaseLoadInHoursReS.add(fillAggDailyBaseLoadInHours(i, type));
aggDailyControllableLoadInHoursReS.add(fillAggDailyControllableLoadInHours(i, type));
aggDailyWeatherSensitiveLoadInHoursReS.add(fillAggDailyWeatherSensitiveLoadInHours(i, type));
}
} else {
for (int i = 0; i < VillageConstants.DAYS_OF_WEEK * (VillageConstants.WEEKS_OF_COMPETITION + VillageConstants.WEEKS_OF_BOOTSTRAP); i++) {
aggDailyBaseLoadSS.add(fillAggDailyBaseLoad(i, type));
aggDailyControllableLoadSS.add(fillAggDailyControllableLoad(i, type));
aggDailyWeatherSensitiveLoadSS.add(fillAggDailyWeatherSensitiveLoad(i, type));
aggDailyBaseLoadInHoursSS.add(fillAggDailyBaseLoadInHours(i, type));
aggDailyControllableLoadInHoursSS.add(fillAggDailyControllableLoadInHours(i, type));
aggDailyWeatherSensitiveLoadInHoursSS.add(fillAggDailyWeatherSensitiveLoadInHours(i, type));
}
}
}
/**
* This function is used in order to update the daily aggregated Load in case
* there are changes in the weather sensitive loads of the village's
* households.
*
* @param type
* @return
*/
void updateAggDailyWeatherSensitiveLoad (String type, int day)
{
int dayTemp = day % (VillageConstants.DAYS_OF_BOOTSTRAP + VillageConstants.DAYS_OF_COMPETITION);
if (type.equals("NS")) {
aggDailyWeatherSensitiveLoadNS.set(dayTemp, fillAggDailyWeatherSensitiveLoad(dayTemp, type));
aggDailyWeatherSensitiveLoadInHoursNS.set(dayTemp, fillAggDailyWeatherSensitiveLoadInHours(dayTemp, type));
} else if (type.equals("RaS")) {
aggDailyWeatherSensitiveLoadRaS.set(dayTemp, fillAggDailyWeatherSensitiveLoad(dayTemp, type));
aggDailyWeatherSensitiveLoadInHoursRaS.set(dayTemp, fillAggDailyWeatherSensitiveLoadInHours(dayTemp, type));
} else if (type.equals("ReS")) {
aggDailyWeatherSensitiveLoadReS.set(dayTemp, fillAggDailyWeatherSensitiveLoad(dayTemp, type));
aggDailyWeatherSensitiveLoadInHoursReS.set(dayTemp, fillAggDailyWeatherSensitiveLoadInHours(dayTemp, type));
} else {
aggDailyWeatherSensitiveLoadSS.set(dayTemp, fillAggDailyWeatherSensitiveLoad(dayTemp, type));
aggDailyWeatherSensitiveLoadInHoursSS.set(dayTemp, fillAggDailyWeatherSensitiveLoadInHours(dayTemp, type));
}
}
/**
* This function is used in order to fill the aggregated daily Base Load of
* the village's households for each quarter of the hour.
*
* @param day
* @param type
* @return
*/
Vector<Long> fillAggDailyBaseLoad (int day, String type)
{
Vector<Household> houses = new Vector<Household>();
if (type.equals("NS")) {
houses = notShiftingHouses;
} else if (type.equals("RaS")) {
houses = randomlyShiftingHouses;
} else if (type.equals("ReS")) {
houses = regularlyShiftingHouses;
} else {
houses = smartShiftingHouses;
}
Vector<Long> v = new Vector<Long>(VillageConstants.QUARTERS_OF_DAY);
long sum = 0;
for (int i = 0; i < VillageConstants.QUARTERS_OF_DAY; i++) {
sum = 0;
for (Household house : houses) {
sum = sum + house.weeklyBaseLoad.get(day).get(i);
}
v.add(sum);
}
return v;
}
/**
* This function is used in order to fill the aggregated daily Controllable
* Load of the village's households for each quarter of the hour.
*
* @param day
* @param type
* @return
*/
Vector<Long> fillAggDailyControllableLoad (int day, String type)
{
Vector<Household> houses = new Vector<Household>();
if (type.equals("NS")) {
houses = notShiftingHouses;
} else if (type.equals("RaS")) {
houses = randomlyShiftingHouses;
} else if (type.equals("ReS")) {
houses = regularlyShiftingHouses;
} else {
houses = smartShiftingHouses;
}
Vector<Long> v = new Vector<Long>(VillageConstants.QUARTERS_OF_DAY);
long sum = 0;
for (int i = 0; i < VillageConstants.QUARTERS_OF_DAY; i++) {
sum = 0;
for (Household house : houses) {
sum = sum + house.weeklyControllableLoad.get(day).get(i);
}
v.add(sum);
}
return v;
}
/**
* This function is used in order to fill the aggregated daily weather
* sensitive Load of the village's households for each quarter of the hour.
*
* @param day
* @param type
* @return
*/
Vector<Long> fillAggDailyWeatherSensitiveLoad (int day, String type)
{
Vector<Household> houses = new Vector<Household>();
if (type.equals("NS")) {
houses = notShiftingHouses;
} else if (type.equals("RaS")) {
houses = randomlyShiftingHouses;
} else if (type.equals("ReS")) {
houses = regularlyShiftingHouses;
} else {
houses = smartShiftingHouses;
}
Vector<Long> v = new Vector<Long>(VillageConstants.QUARTERS_OF_DAY);
long sum = 0;
for (int i = 0; i < VillageConstants.QUARTERS_OF_DAY; i++) {
sum = 0;
for (Household house : houses) {
sum = sum + house.weeklyWeatherSensitiveLoad.get(day).get(i);
}
v.add(sum);
}
return v;
}
/**
* This function is used in order to fill the daily Base Load of the household
* for each hour for a certain type of households.
*
* @param day
* @param type
* @return
*/
Vector<Long> fillAggDailyBaseLoadInHours (int day, String type)
{
Vector<Long> daily = new Vector<Long>();
long sum = 0;
if (type.equals("NS")) {
for (int i = 0; i < VillageConstants.HOURS_OF_DAY; i++) {
sum = 0;
sum = aggDailyBaseLoadNS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR) + aggDailyBaseLoadNS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR + 1)
+ aggDailyBaseLoadNS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR + 2) + aggDailyBaseLoadNS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR + 3);
daily.add(sum);
}
} else if (type.equals("RaS")) {
for (int i = 0; i < VillageConstants.HOURS_OF_DAY; i++) {
sum = 0;
sum = aggDailyBaseLoadRaS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR) + aggDailyBaseLoadRaS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR + 1)
+ aggDailyBaseLoadRaS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR + 2) + aggDailyBaseLoadRaS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR + 3);
daily.add(sum);
}
} else if (type.equals("ReS")) {
for (int i = 0; i < VillageConstants.HOURS_OF_DAY; i++) {
sum = 0;
sum = aggDailyBaseLoadReS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR) + aggDailyBaseLoadReS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR + 1)
+ aggDailyBaseLoadReS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR + 2) + aggDailyBaseLoadReS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR + 3);
daily.add(sum);
}
} else {
for (int i = 0; i < VillageConstants.HOURS_OF_DAY; i++) {
sum = 0;
sum = aggDailyBaseLoadSS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR) + aggDailyBaseLoadSS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR + 1)
+ aggDailyBaseLoadSS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR + 2) + aggDailyBaseLoadSS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR + 3);
daily.add(sum);
}
}
return daily;
}
/**
* This function is used in order to fill the daily Controllable Load of the
* household for each hour for a certain type of households.
*
* @param day
* @param type
* @return
*/
Vector<Long> fillAggDailyControllableLoadInHours (int day, String type)
{
Vector<Long> daily = new Vector<Long>();
long sum = 0;
if (type.equals("NS")) {
for (int i = 0; i < VillageConstants.HOURS_OF_DAY; i++) {
sum = 0;
sum = aggDailyControllableLoadNS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR) + aggDailyControllableLoadNS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR + 1)
+ aggDailyControllableLoadNS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR + 2) + aggDailyControllableLoadNS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR + 3);
daily.add(sum);
}
} else if (type.equals("RaS")) {
for (int i = 0; i < VillageConstants.HOURS_OF_DAY; i++) {
sum = 0;
sum = aggDailyControllableLoadRaS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR) + aggDailyControllableLoadRaS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR + 1)
+ aggDailyControllableLoadRaS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR + 2) + aggDailyControllableLoadRaS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR + 3);
daily.add(sum);
}
} else if (type.equals("ReS")) {
for (int i = 0; i < VillageConstants.HOURS_OF_DAY; i++) {
sum = 0;
sum = aggDailyControllableLoadReS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR) + aggDailyControllableLoadReS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR + 1)
+ aggDailyControllableLoadReS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR + 2) + aggDailyControllableLoadReS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR + 3);
daily.add(sum);
}
} else {
for (int i = 0; i < VillageConstants.HOURS_OF_DAY; i++) {
sum = 0;
sum = aggDailyControllableLoadSS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR) + aggDailyControllableLoadSS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR + 1)
+ aggDailyControllableLoadSS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR + 2) + aggDailyControllableLoadSS.get(day).get(i * VillageConstants.QUARTERS_OF_HOUR + 3);
daily.add(sum);
}
}
return daily;
}
/**
* This function is used in order to fill the daily weather sensitive Load of
* the household for each hour for a certain type of households.
*
* @param day
* @param type
* @return
*/
Vector<Long> fillAggDailyWeatherSensitiveLoadInHours (int day, String type)
{
int dayTemp = day % (VillageConstants.DAYS_OF_BOOTSTRAP + VillageConstants.DAYS_OF_COMPETITION);
Vector<Long> daily = new Vector<Long>();
long sum = 0;
if (type.equals("NS")) {
for (int i = 0; i < VillageConstants.HOURS_OF_DAY; i++) {
sum = 0;
sum = aggDailyWeatherSensitiveLoadNS.get(dayTemp).get(i * VillageConstants.QUARTERS_OF_HOUR) + aggDailyWeatherSensitiveLoadNS.get(dayTemp).get(i * VillageConstants.QUARTERS_OF_HOUR + 1)
+ aggDailyWeatherSensitiveLoadNS.get(dayTemp).get(i * VillageConstants.QUARTERS_OF_HOUR + 2) + aggDailyWeatherSensitiveLoadNS.get(dayTemp).get(i * VillageConstants.QUARTERS_OF_HOUR + 3);
daily.add(sum);
}
} else if (type.equals("RaS")) {
for (int i = 0; i < VillageConstants.HOURS_OF_DAY; i++) {
sum = 0;
sum = aggDailyWeatherSensitiveLoadRaS.get(dayTemp).get(i * VillageConstants.QUARTERS_OF_HOUR) + aggDailyWeatherSensitiveLoadRaS.get(dayTemp).get(i * VillageConstants.QUARTERS_OF_HOUR + 1)
+ aggDailyWeatherSensitiveLoadRaS.get(dayTemp).get(i * VillageConstants.QUARTERS_OF_HOUR + 2) + aggDailyWeatherSensitiveLoadRaS.get(dayTemp).get(i * VillageConstants.QUARTERS_OF_HOUR + 3);
daily.add(sum);
}
} else if (type.equals("ReS")) {
for (int i = 0; i < VillageConstants.HOURS_OF_DAY; i++) {
sum = 0;
sum = aggDailyWeatherSensitiveLoadReS.get(dayTemp).get(i * VillageConstants.QUARTERS_OF_HOUR) + aggDailyWeatherSensitiveLoadReS.get(dayTemp).get(i * VillageConstants.QUARTERS_OF_HOUR + 1)
+ aggDailyWeatherSensitiveLoadReS.get(dayTemp).get(i * VillageConstants.QUARTERS_OF_HOUR + 2) + aggDailyWeatherSensitiveLoadReS.get(dayTemp).get(i * VillageConstants.QUARTERS_OF_HOUR + 3);
daily.add(sum);
}
} else {
for (int i = 0; i < VillageConstants.HOURS_OF_DAY; i++) {
sum = 0;
sum = aggDailyWeatherSensitiveLoadSS.get(dayTemp).get(i * VillageConstants.QUARTERS_OF_HOUR) + aggDailyWeatherSensitiveLoadSS.get(dayTemp).get(i * VillageConstants.QUARTERS_OF_HOUR + 1)
+ aggDailyWeatherSensitiveLoadSS.get(dayTemp).get(i * VillageConstants.QUARTERS_OF_HOUR + 2) + aggDailyWeatherSensitiveLoadSS.get(dayTemp).get(i * VillageConstants.QUARTERS_OF_HOUR + 3);
daily.add(sum);
}
}
return daily;
}
/**
* This function is used in order to print the aggregated hourly load of the
* village's households.
*
* @param type
* @return
*/
void showAggLoad (String type)
{
log.info("Portion " + type + " Weekly Aggregated Load");
if (type.equals("NS")) {
for (int i = 0; i < VillageConstants.DAYS_OF_COMPETITION + VillageConstants.DAYS_OF_BOOTSTRAP; i++) {
log.debug("Day " + i);
for (int j = 0; j < VillageConstants.HOURS_OF_DAY; j++) {
log.debug("Hour : " + j + " Base Load : " + aggDailyBaseLoadInHoursNS.get(i).get(j) + " Controllable Load: " + aggDailyControllableLoadInHoursNS.get(i).get(j) + " Weather Sensitive Load: "
+ aggDailyWeatherSensitiveLoadInHoursNS.get(i).get(j));
}
}
} else if (type.equals("RaS")) {
for (int i = 0; i < VillageConstants.DAYS_OF_COMPETITION + VillageConstants.DAYS_OF_BOOTSTRAP; i++) {
log.debug("Day " + i);
for (int j = 0; j < VillageConstants.HOURS_OF_DAY; j++) {
log.debug("Hour : " + j + " Base Load : " + aggDailyBaseLoadInHoursRaS.get(i).get(j) + " Controllable Load: " + aggDailyControllableLoadInHoursRaS.get(i).get(j)
+ " Weather Sensitive Load: " + aggDailyWeatherSensitiveLoadInHoursRaS.get(i).get(j));
}
}
} else if (type.equals("ReS")) {
for (int i = 0; i < VillageConstants.DAYS_OF_COMPETITION + VillageConstants.DAYS_OF_BOOTSTRAP; i++) {
log.debug("Day " + i);
for (int j = 0; j < VillageConstants.HOURS_OF_DAY; j++) {
log.debug("Hour : " + j + " Base Load : " + aggDailyBaseLoadInHoursReS.get(i).get(j) + " Controllable Load: " + aggDailyControllableLoadInHoursReS.get(i).get(j)
+ " Weather Sensitive Load: " + aggDailyWeatherSensitiveLoadInHoursReS.get(i).get(j));
}
}
} else {
for (int i = 0; i < VillageConstants.DAYS_OF_COMPETITION + VillageConstants.DAYS_OF_BOOTSTRAP; i++) {
log.debug("Day " + i);
for (int j = 0; j < VillageConstants.HOURS_OF_DAY; j++) {
log.debug("Hour : " + j + " Base Load : " + aggDailyBaseLoadInHoursSS.get(i).get(j) + " Controllable Load: " + aggDailyControllableLoadInHoursSS.get(i).get(j) + " Weather Sensitive Load: "
+ aggDailyWeatherSensitiveLoadInHoursSS.get(i).get(j));
}
}
}
}
/**
* This function is used in order to print the aggregated hourly load of the
* village households for a certain type of households.
*
* @param type
* @return
*/
public void showAggDailyLoad (String type, int day)
{
log.debug("Portion " + type + " Daily Aggregated Load");
log.debug("Day " + day);
if (type.equals("NS")) {
for (int j = 0; j < VillageConstants.HOURS_OF_DAY; j++) {
log.debug("Hour : " + j + " Base Load : " + aggDailyBaseLoadInHoursNS.get(day).get(j) + " Controllable Load: " + aggDailyControllableLoadInHoursNS.get(day).get(j)
+ " Weather Sensitive Load: " + aggDailyWeatherSensitiveLoadInHoursNS.get(day).get(j));
}
} else if (type.equals("RaS")) {
for (int j = 0; j < VillageConstants.HOURS_OF_DAY; j++) {
log.debug("Hour : " + j + " Base Load : " + aggDailyBaseLoadInHoursRaS.get(day).get(j) + " Controllable Load: " + aggDailyControllableLoadInHoursRaS.get(day).get(j)
+ " Weather Sensitive Load: " + aggDailyWeatherSensitiveLoadInHoursRaS.get(day).get(j));
}
} else if (type.equals("ReS")) {
for (int j = 0; j < VillageConstants.HOURS_OF_DAY; j++) {
log.debug("Hour : " + j + " Base Load : " + aggDailyBaseLoadInHoursReS.get(day).get(j) + " Controllable Load: " + aggDailyControllableLoadInHoursReS.get(day).get(j)
+ " Weather Sensitive Load: " + aggDailyWeatherSensitiveLoadInHoursReS.get(day).get(j));
}
} else {
for (int j = 0; j < VillageConstants.HOURS_OF_DAY; j++) {
log.debug("Hour : " + j + " Base Load : " + aggDailyBaseLoadInHoursSS.get(day).get(j) + " Controllable Load: " + aggDailyControllableLoadInHoursSS.get(day).get(j)
+ " Weather Sensitive Load: " + aggDailyWeatherSensitiveLoadInHoursSS.get(day).get(j));
}
}
}
// =====CONSUMPTION FUNCTIONS===== //
@Override
public void consumePower ()
{
Timeslot ts = timeslotRepo.currentTimeslot();
double summary = 0;
for (String type : subscriptionMap.keySet()) {
TariffSubscription sub = subscriptionMap.get(type);
if (ts == null) {
log.debug("Current timeslot is null");
int serial = (int) ((timeService.getCurrentTime().getMillis() - timeService.getBase()) / TimeService.HOUR);
summary = getConsumptionByTimeslot(serial, type);
} else {
summary = getConsumptionByTimeslot(ts.getSerialNumber(), type);
}
log.info("Consumption Load for " + type + ": " + summary);
- sub.usePower(summary);
+ if (sub.getCustomersCommitted() > 0)
+ sub.usePower(summary);
}
}
/**
* This method takes as an input the time-slot serial number (in order to know
* in the current time) and estimates the consumption for this time-slot over
* the population under the Village Household Consumer.
*/
double getConsumptionByTimeslot (int serial, String type)
{
int day = (int) (serial / VillageConstants.HOURS_OF_DAY);
int hour = (int) (serial % VillageConstants.HOURS_OF_DAY);
long summary = 0;
log.debug("Serial : " + serial + " Day: " + day + " Hour: " + hour);
summary = (getBaseConsumptions(day, hour, type) + getControllableConsumptions(day, hour, type) + getWeatherSensitiveConsumptions(day, hour, type));
return (double) summary / VillageConstants.THOUSAND;
}
// =====GETTER FUNCTIONS===== //
/** This function returns the subscription Map variable of the village. */
public HashMap<String, TariffSubscription> getSubscriptionMap ()
{
return subscriptionMap;
}
/** This function returns the inertia Map variable of the village. */
public HashMap<String, Double> getInertiaMap ()
{
return inertiaMap;
}
/** This function returns the period Map variable of the village. */
public HashMap<String, Integer> getPeriodMap ()
{
return periodMap;
}
/**
* This function returns the quantity of base load for a specific day and hour
* of that day for a specific type of households.
*/
long getBaseConsumptions (int day, int hour, String type)
{
long summaryBase = 0;
int dayTemp = day % (VillageConstants.DAYS_OF_BOOTSTRAP + VillageConstants.DAYS_OF_COMPETITION);
if (type.equals("NS")) {
summaryBase = aggDailyBaseLoadInHoursNS.get(dayTemp).get(hour);
} else if (type.equals("RaS")) {
summaryBase = aggDailyBaseLoadInHoursRaS.get(dayTemp).get(hour);
} else if (type.equals("ReS")) {
summaryBase = aggDailyBaseLoadInHoursReS.get(dayTemp).get(hour);
} else {
summaryBase = aggDailyBaseLoadInHoursSS.get(dayTemp).get(hour);
}
log.debug("Base Load for " + type + ":" + summaryBase);
return summaryBase;
}
/**
* This function returns the quantity of controllable load for a specific day
* and hour of that day for a specific type of households.
*/
long getControllableConsumptions (int day, int hour, String type)
{
long summaryControllable = 0;
int dayTemp = day % (VillageConstants.DAYS_OF_BOOTSTRAP + VillageConstants.DAYS_OF_COMPETITION);
if (type.equals("NS")) {
summaryControllable = aggDailyControllableLoadInHoursNS.get(dayTemp).get(hour);
} else if (type.equals("RaS")) {
summaryControllable = aggDailyControllableLoadInHoursRaS.get(dayTemp).get(hour);
} else if (type.equals("ReS")) {
summaryControllable = aggDailyControllableLoadInHoursReS.get(dayTemp).get(hour);
} else {
summaryControllable = aggDailyControllableLoadInHoursSS.get(dayTemp).get(hour);
}
log.debug("Controllable Load for " + type + ":" + summaryControllable);
return summaryControllable;
}
/**
* This function returns the quantity of weather sensitive load for a specific
* day and hour of that day for a specific type of household.
*/
long getWeatherSensitiveConsumptions (int day, int hour, String type)
{
long summaryWeatherSensitive = 0;
int dayTemp = day % (VillageConstants.DAYS_OF_BOOTSTRAP + VillageConstants.DAYS_OF_COMPETITION);
if (type.equals("NS")) {
summaryWeatherSensitive = aggDailyWeatherSensitiveLoadInHoursNS.get(dayTemp).get(hour);
} else if (type.equals("RaS")) {
summaryWeatherSensitive = aggDailyWeatherSensitiveLoadInHoursRaS.get(dayTemp).get(hour);
} else if (type.equals("ReS")) {
summaryWeatherSensitive = aggDailyWeatherSensitiveLoadInHoursReS.get(dayTemp).get(hour);
} else {
summaryWeatherSensitive = aggDailyWeatherSensitiveLoadInHoursSS.get(dayTemp).get(hour);
}
log.debug("WeatherSensitive Load for " + type + ":" + summaryWeatherSensitive);
return summaryWeatherSensitive;
}
/**
* This function returns the quantity of controllable load for a specific day
* in form of a vector for a certain type of households.
*/
Vector<Long> getControllableConsumptions (int day, String type)
{
Vector<Long> controllableVector = new Vector<Long>();
int dayTemp = day % (VillageConstants.DAYS_OF_BOOTSTRAP + VillageConstants.DAYS_OF_COMPETITION);
if (type.equals("NS")) {
controllableVector = aggDailyControllableLoadInHoursNS.get(dayTemp);
} else if (type.equals("RaS")) {
controllableVector = aggDailyControllableLoadInHoursRaS.get(dayTemp);
} else if (type.equals("ReS")) {
controllableVector = aggDailyControllableLoadInHoursReS.get(dayTemp);
} else {
controllableVector = aggDailyControllableLoadInHoursSS.get(dayTemp);
}
return controllableVector;
}
/**
* This function returns the quantity of weather sensitive load for a specific
* day in form of a vector for a certain type of households.
*/
Vector<Long> getWeatherSensitiveConsumptions (int day, String type)
{
Vector<Long> weatherSensitiveVector = new Vector<Long>();
int dayTemp = day % (VillageConstants.DAYS_OF_BOOTSTRAP + VillageConstants.DAYS_OF_COMPETITION);
if (type.equals("NS")) {
weatherSensitiveVector = aggDailyWeatherSensitiveLoadInHoursNS.get(dayTemp);
} else if (type.equals("RaS")) {
weatherSensitiveVector = aggDailyWeatherSensitiveLoadInHoursRaS.get(dayTemp);
} else if (type.equals("ReS")) {
weatherSensitiveVector = aggDailyWeatherSensitiveLoadInHoursReS.get(dayTemp);
} else {
weatherSensitiveVector = aggDailyWeatherSensitiveLoadInHoursSS.get(dayTemp);
}
return weatherSensitiveVector;
}
/**
* This function returns a vector with all the houses that are present in this
* village.
*/
public Vector<Household> getHouses ()
{
Vector<Household> houses = new Vector<Household>();
for (Household house : notShiftingHouses)
houses.add(house);
for (Household house : regularlyShiftingHouses)
houses.add(house);
for (Household house : randomlyShiftingHouses)
houses.add(house);
for (Household house : smartShiftingHouses)
houses.add(house);
return houses;
}
/**
* This function returns a vector with all the households of a certain type
* that are present in this village.
*/
public Vector<Household> getHouses (String type)
{
Vector<Household> houses = new Vector<Household>();
if (type.equals("NS")) {
for (Household house : notShiftingHouses) {
houses.add(house);
}
} else if (type.equals("RaS")) {
for (Household house : regularlyShiftingHouses) {
houses.add(house);
}
} else if (type.equals("ReS")) {
for (Household house : randomlyShiftingHouses) {
houses.add(house);
}
} else {
for (Household house : smartShiftingHouses) {
houses.add(house);
}
}
return houses;
}
// =====EVALUATION FUNCTIONS===== //
/**
* This is the basic evaluation function, taking into consideration the
* minimum cost without shifting the appliances' load but the tariff chosen is
* picked up randomly by using a possibility pattern. The better tariffs have
* more chances to be chosen.
*/
public void possibilityEvaluationNewTariffs (List<Tariff> newTariffs, String type)
{
List<TariffSubscription> subscriptions = tariffSubscriptionRepo.findActiveSubscriptionsForCustomer(this.getCustomerInfo());
if (subscriptions == null || subscriptions.size() == 0) {
subscribeDefault();
return;
}
Vector<Double> estimation = new Vector<Double>();
// getting the active tariffs for evaluation
ArrayList<Tariff> evaluationTariffs = new ArrayList<Tariff>(newTariffs);
log.debug("Estimation size for " + this.toString() + " = " + evaluationTariffs.size());
if (evaluationTariffs.size() > 1) {
for (Tariff tariff : evaluationTariffs) {
log.debug("Tariff : " + tariff.toString() + " Tariff Type : " + tariff.getTariffSpecification().getPowerType());
if (tariff.isExpired() == false && tariff.getTariffSpecification().getPowerType() == PowerType.CONSUMPTION) {
estimation.add(-(costEstimation(tariff, type)));
} else
estimation.add(Double.NEGATIVE_INFINITY);
}
int minIndex = logitPossibilityEstimation(estimation, type);
TariffSubscription sub = subscriptionMap.get(type);
log.debug("Equality: " + sub.getTariff().getTariffSpec().toString() + " = " + evaluationTariffs.get(minIndex).getTariffSpec().toString());
if (!(sub.getTariff().getTariffSpec() == evaluationTariffs.get(minIndex).getTariffSpec())) {
log.debug("Changing From " + sub.toString() + " After Evaluation");
changeSubscription(sub.getTariff(), evaluationTariffs.get(minIndex), type);
}
}
}
/**
* This function estimates the overall cost, taking into consideration the
* fixed payments as well as the variable that are depending on the tariff
* rates
*/
double costEstimation (Tariff tariff, String type)
{
double costVariable = 0;
/* if it is NotShifting Houses the evaluation is done without shifting devices
if it is RandomShifting Houses the evaluation is may be done without shifting devices or maybe shifting will be taken into consideration
In any other case shifting will be done. */
if (type.equals("NS")) {
// System.out.println("Simple Evaluation for " + type);
log.debug("Simple Evaluation for " + type);
costVariable = estimateVariableTariffPayment(tariff, type);
} else if (type.equals("RaS")) {
Double rand = gen.nextDouble();
// System.out.println(rand);
if (rand < getInertiaMap().get(type)) {
// System.out.println("Simple Evaluation for " + type);
log.debug("Simple Evaluation for " + type);
costVariable = estimateShiftingVariableTariffPayment(tariff, type);
} else {
// System.out.println("Shifting Evaluation for " + type);
log.debug("Shifting Evaluation for " + type);
costVariable = estimateVariableTariffPayment(tariff, type);
}
} else {
// System.out.println("Shifting Evaluation for " + type);
log.debug("Shifting Evaluation for " + type);
costVariable = estimateShiftingVariableTariffPayment(tariff, type);
}
double costFixed = estimateFixedTariffPayments(tariff);
return (costVariable + costFixed) / VillageConstants.MILLION;
}
/**
* This function estimates the fixed cost, comprised by fees, bonuses and
* penalties that are the same no matter how much you consume
*/
double estimateFixedTariffPayments (Tariff tariff)
{
double lifecyclePayment = -tariff.getEarlyWithdrawPayment() - tariff.getSignupPayment();
double minDuration;
// When there is not a Minimum Duration of the contract, you cannot divide
// with the duration
// because you don't know it.
if (tariff.getMinDuration() == 0)
minDuration = VillageConstants.MEAN_TARIFF_DURATION * TimeService.DAY;
else
minDuration = tariff.getMinDuration();
log.debug("Minimum Duration: " + minDuration);
return (-tariff.getPeriodicPayment() + (lifecyclePayment / minDuration));
}
/**
* This function estimates the variable cost, depending only to the load
* quantity you consume
*/
double estimateVariableTariffPayment (Tariff tariff, String type)
{
double finalCostSummary = 0;
int serial = (int) ((timeService.getCurrentTime().getMillis() - timeService.getBase()) / TimeService.HOUR);
Instant base = new Instant(timeService.getCurrentTime().getMillis() - serial * TimeService.HOUR);
int daylimit = (int) (serial / VillageConstants.HOURS_OF_DAY) + 1;
for (int day : daysList) {
if (day < daylimit)
day = (int) (day + (daylimit / VillageConstants.RANDOM_DAYS_NUMBER));
Instant now = base.plus(day * TimeService.DAY);
double costSummary = 0;
double summary = 0, cumulativeSummary = 0;
for (int hour = 0; hour < VillageConstants.HOURS_OF_DAY; hour++) {
summary = getBaseConsumptions(day, hour, type) + getControllableConsumptions(day, hour, type);
log.debug("Cost for hour " + hour + ":" + tariff.getUsageCharge(now, 1, 0));
cumulativeSummary += summary;
costSummary -= tariff.getUsageCharge(now, summary, cumulativeSummary);
now = now.plus(TimeService.HOUR);
}
log.debug("Variable Cost Summary: " + finalCostSummary);
finalCostSummary += costSummary;
}
return finalCostSummary / VillageConstants.RANDOM_DAYS_NUMBER;
}
/**
* This is the new function, used in order to find the most cost efficient
* tariff over the available ones. It is using Daily shifting in order to put
* the appliances operation in most suitable hours (less costly) of the day.
*
* @param tariff
* @return
*/
double estimateShiftingVariableTariffPayment (Tariff tariff, String type)
{
double finalCostSummary = 0;
int serial = (int) ((timeService.getCurrentTime().getMillis() - timeService.getBase()) / TimeService.HOUR);
Instant base = timeService.getCurrentTime().minus(serial * TimeService.HOUR);
int daylimit = (int) (serial / VillageConstants.HOURS_OF_DAY) + 1;
for (int day : daysList) {
if (day < daylimit)
day = (int) (day + (daylimit / VillageConstants.RANDOM_DAYS_NUMBER));
Instant now = base.plus(day * TimeService.DAY);
double costSummary = 0;
double summary = 0, cumulativeSummary = 0;
long[] newControllableLoad = dailyShifting(tariff, now, day, type);
for (int hour = 0; hour < VillageConstants.HOURS_OF_DAY; hour++) {
summary = getBaseConsumptions(day, hour, type) + newControllableLoad[hour];
cumulativeSummary += summary;
costSummary -= tariff.getUsageCharge(now, summary, cumulativeSummary);
now = now.plus(TimeService.HOUR);
}
log.debug("Variable Cost Summary: " + finalCostSummary);
finalCostSummary += costSummary;
}
return finalCostSummary / VillageConstants.RANDOM_DAYS_NUMBER;
}
/**
* This is the function that realizes the mathematical possibility formula for
* the choice of tariff.
*/
int logitPossibilityEstimation (Vector<Double> estimation, String type)
{
double lamda = lamdaMap.get(type);
double summedEstimations = 0;
Vector<Integer> randomizer = new Vector<Integer>();
Vector<Integer> possibilities = new Vector<Integer>();
for (int i = 0; i < estimation.size(); i++) {
summedEstimations += Math.pow(VillageConstants.EPSILON, lamda * estimation.get(i));
log.debug("Cost variable: " + estimation.get(i));
log.debug("Summary of Estimation: " + summedEstimations);
}
for (int i = 0; i < estimation.size(); i++) {
possibilities.add((int) (VillageConstants.PERCENTAGE * (Math.pow(VillageConstants.EPSILON, lamda * estimation.get(i)) / summedEstimations)));
for (int j = 0; j < possibilities.get(i); j++) {
randomizer.add(i);
}
}
log.debug("Randomizer Vector: " + randomizer);
log.debug("Possibility Vector: " + possibilities.toString());
int index = randomizer.get((int) (randomizer.size() * rs1.nextDouble()));
log.debug("Resulting Index = " + index);
return index;
}
// =====SHIFTING FUNCTIONS===== //
/**
* This is the function that takes every household in the village and reads
* the shifted Controllable Consumption for the needs of the tariff
* evaluation.
*
* @param tariff
* @param now
* @param day
* @param type
* @return
*/
long[] dailyShifting (Tariff tariff, Instant now, int day, String type)
{
long[] newControllableLoad = new long[VillageConstants.HOURS_OF_DAY];
int dayTemp = day % (VillageConstants.DAYS_OF_BOOTSTRAP + VillageConstants.DAYS_OF_COMPETITION);
Vector<Household> houses = new Vector<Household>();
if (type.equals("NS")) {
houses = notShiftingHouses;
} else if (type.equals("RaS")) {
houses = randomlyShiftingHouses;
} else if (type.equals("ReS")) {
houses = regularlyShiftingHouses;
} else {
houses = smartShiftingHouses;
}
for (Household house : houses) {
long[] temp = house.dailyShifting(tariff, now, dayTemp, gen);
for (int j = 0; j < VillageConstants.HOURS_OF_DAY; j++)
newControllableLoad[j] += temp[j];
}
log.debug("New Controllable Load of Village " + toString() + " type " + type + " for Tariff " + tariff.toString());
for (int i = 0; i < VillageConstants.HOURS_OF_DAY; i++) {
log.debug("Hour: " + i + " Cost: " + tariff.getUsageCharge(now, 1, 0) + " Load For Type " + type + " : " + newControllableLoad[i]);
now = new Instant(now.getMillis() + TimeService.HOUR);
}
return newControllableLoad;
}
// =====STATUS FUNCTIONS===== //
/**
* This function prints to the screen the daily load of the village's
* households for the weekday at hand.
*
* @param day
* @param type
* @return
*/
void printDailyLoad (int day, String type)
{
Vector<Household> houses = new Vector<Household>();
int dayTemp = day % (VillageConstants.DAYS_OF_BOOTSTRAP + VillageConstants.DAYS_OF_COMPETITION);
if (type.equals("NS")) {
houses = notShiftingHouses;
} else if (type.equals("RaS")) {
houses = randomlyShiftingHouses;
} else if (type.equals("ReS")) {
houses = regularlyShiftingHouses;
} else {
houses = smartShiftingHouses;
}
log.debug("Day " + day);
for (Household house : houses) {
house.printDailyLoad(dayTemp);
}
}
// =====VECTOR CREATION===== //
/**
* This function is creating a certain number of random days that will be
* public vacation for the people living in the environment.
*
* @param days
* @param gen
* @return
*/
Vector<Integer> createPublicVacationVector (int days)
{
// Creating auxiliary variables
Vector<Integer> v = new Vector<Integer>(days);
for (int i = 0; i < days; i++) {
int x = gen.nextInt(VillageConstants.DAYS_OF_COMPETITION + VillageConstants.DAYS_OF_BOOTSTRAP);
ListIterator<Integer> iter = v.listIterator();
while (iter.hasNext()) {
int temp = (int) iter.next();
if (x == temp) {
x = x + 1;
iter = v.listIterator();
}
}
v.add(x);
}
java.util.Collections.sort(v);
return v;
}
/**
* This function is creating the list of days for each village that will be
* utilized for the tariff evaluation.
*
* @param days
* @param gen
* @return
*/
void createCostEstimationDaysList (int days)
{
for (int i = 0; i < days; i++) {
int x = gen.nextInt(VillageConstants.DAYS_OF_COMPETITION + VillageConstants.DAYS_OF_BOOTSTRAP);
ListIterator<Integer> iter = daysList.listIterator();
while (iter.hasNext()) {
int temp = (int) iter.next();
if (x == temp) {
x = x + 1;
iter = daysList.listIterator();
}
}
daysList.add(x);
}
java.util.Collections.sort(daysList);
}
// =====STEP FUNCTIONS===== //
@Override
public void step ()
{
int serial = (int) ((timeService.getCurrentTime().getMillis() - timeService.getBase()) / TimeService.HOUR);
int day = (int) (serial / VillageConstants.HOURS_OF_DAY);
int hour = timeService.getHourOfDay();
Instant now = new Instant(timeService.getCurrentTime().getMillis());
weatherCheck(day, hour, now);
checkRevokedSubscriptions();
consumePower();
if (hour == 23) {
for (String type : subscriptionMap.keySet()) {
if (!(type.equals("NS"))) {
log.info("Rescheduling " + type);
rescheduleNextDay(type);
}
}
}
}
/**
* This function is utilized in order to check the weather at each time tick
* of the competition clock and reschedule the appliances that are weather
* sensitive to work.
*/
void weatherCheck (int day, int hour, Instant now)
{
int dayTemp = day % (VillageConstants.DAYS_OF_BOOTSTRAP + VillageConstants.DAYS_OF_COMPETITION);
WeatherReport wr = null;
wr = weatherReportRepo.currentWeatherReport();
if (wr != null) {
double temperature = wr.getTemperature();
// log.debug("Temperature: " + temperature);
Vector<Household> houses = getHouses();
for (Household house : houses) {
house.weatherCheck(dayTemp, hour, now, temperature);
}
for (String type : subscriptionMap.keySet()) {
updateAggDailyWeatherSensitiveLoad(type, day);
if (dayTemp + 1 < VillageConstants.DAYS_OF_COMPETITION) {
updateAggDailyWeatherSensitiveLoad(type, dayTemp + 1);
}
// showAggDailyLoad(type, dayTemp);
// showAggDailyLoad(type, dayTemp + 1);
}
}
}
/**
* This function is utilized in order to reschedule the consumption load for
* the next day of the competition according to the tariff rates of the
* subscriptions under contract.
*/
void rescheduleNextDay (String type)
{
int serial = (int) ((timeService.getCurrentTime().getMillis() - timeService.getBase()) / TimeService.HOUR);
int day = (int) (serial / VillageConstants.HOURS_OF_DAY) + 1;
Instant now = new Instant(timeService.getCurrentTime().getMillis() + TimeService.HOUR);
int dayTemp = day % (VillageConstants.DAYS_OF_BOOTSTRAP + VillageConstants.DAYS_OF_COMPETITION);
Vector<Long> controllableVector = new Vector<Long>();
TariffSubscription sub = subscriptionMap.get(type);
log.debug("Old Consumption for day " + day + ": " + getControllableConsumptions(dayTemp, type).toString());
long[] newControllableLoad = dailyShifting(sub.getTariff(), now, dayTemp, type);
for (int i = 0; i < VillageConstants.HOURS_OF_DAY; i++)
controllableVector.add(newControllableLoad[i]);
log.debug("New Consumption for day " + day + ": " + controllableVector.toString());
if (type.equals("RaS")) {
aggDailyBaseLoadInHoursRaS.set(dayTemp, controllableVector);
} else if (type.equals("ReS")) {
aggDailyBaseLoadInHoursReS.set(dayTemp, controllableVector);
} else {
aggDailyBaseLoadInHoursSS.set(dayTemp, controllableVector);
}
}
@Override
public String toString ()
{
return customerInfo.toString();
}
}
| true | false | null | null |
diff --git a/src/ibis/ipl/impl/tcp/TcpIbis.java b/src/ibis/ipl/impl/tcp/TcpIbis.java
index e2d5c27a..a558d08f 100644
--- a/src/ibis/ipl/impl/tcp/TcpIbis.java
+++ b/src/ibis/ipl/impl/tcp/TcpIbis.java
@@ -1,378 +1,379 @@
/* $Id$ */
package ibis.ipl.impl.tcp;
import ibis.ipl.AlreadyConnectedException;
import ibis.ipl.ConnectionRefusedException;
import ibis.ipl.ConnectionTimedOutException;
import ibis.ipl.IbisCapabilities;
import ibis.ipl.MessageUpcall;
import ibis.ipl.PortMismatchException;
import ibis.ipl.PortType;
import ibis.ipl.ReceivePortConnectUpcall;
import ibis.ipl.RegistryEventHandler;
import ibis.ipl.SendPortDisconnectUpcall;
import ibis.ipl.impl.IbisIdentifier;
import ibis.ipl.impl.ReceivePort;
import ibis.ipl.impl.SendPort;
import ibis.ipl.impl.SendPortIdentifier;
import ibis.util.ThreadPool;
import ibis.io.BufferedArrayInputStream;
import ibis.io.BufferedArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Properties;
import org.apache.log4j.Logger;
public final class TcpIbis extends ibis.ipl.impl.Ibis
implements Runnable, TcpProtocol {
static final Logger logger
= Logger.getLogger("ibis.ipl.impl.tcp.TcpIbis");
static final IbisCapabilities ibisCapabilities = new IbisCapabilities(
IbisCapabilities.CLOSEDWORLD,
IbisCapabilities.MEMBERSHIP,
IbisCapabilities.MEMBERSHIP_ORDERED,
IbisCapabilities.MEMBERSHIP_RELIABLE,
IbisCapabilities.SIGNALS,
IbisCapabilities.ELECTIONS,
IbisCapabilities.MALLEABLE,
IbisCapabilities.SELECTABLE,
"nickname.tcp"
);
static final PortType portCapabilities = new PortType(
PortType.SERIALIZATION_OBJECT_SUN,
PortType.SERIALIZATION_OBJECT_IBIS,
PortType.SERIALIZATION_OBJECT,
PortType.SERIALIZATION_DATA,
PortType.SERIALIZATION_BYTE,
PortType.COMMUNICATION_FIFO,
PortType.COMMUNICATION_NUMBERED,
PortType.COMMUNICATION_RELIABLE,
PortType.CONNECTION_DOWNCALLS,
PortType.CONNECTION_UPCALLS,
PortType.CONNECTION_TIMEOUT,
PortType.CONNECTION_MANY_TO_MANY,
PortType.CONNECTION_MANY_TO_ONE,
PortType.CONNECTION_ONE_TO_MANY,
PortType.CONNECTION_ONE_TO_ONE,
PortType.RECEIVE_POLL,
PortType.RECEIVE_AUTO_UPCALLS,
PortType.RECEIVE_EXPLICIT,
PortType.RECEIVE_POLL_UPCALLS,
PortType.RECEIVE_TIMEOUT
);
private IbisSocketFactory factory;
private IbisServerSocket systemServer;
private IbisSocketAddress myAddress;
private boolean quiting = false;
private HashMap<ibis.ipl.IbisIdentifier, IbisSocketAddress> addresses
= new HashMap<ibis.ipl.IbisIdentifier, IbisSocketAddress>();
public TcpIbis(RegistryEventHandler registryEventHandler, IbisCapabilities capabilities, PortType[] types, Properties userProperties) {
super(registryEventHandler, capabilities, types, userProperties);
this.properties.checkProperties("ibis.ipl.impl.tcp.",
new String[] {"smartsockets"}, null, true);
factory.setIdent(ident);
// Create a new accept thread
ThreadPool.createNew(this, "TcpIbis Accept Thread");
}
+
protected PortType getPortCapabilities() {
return portCapabilities;
}
protected IbisCapabilities getCapabilities() {
return ibisCapabilities;
}
protected byte[] getData() throws IOException {
factory = new IbisSocketFactory(properties);
systemServer = factory.createServerSocket(0, 50, true, null);
myAddress = systemServer.getLocalSocketAddress();
if (logger.isDebugEnabled()) {
logger.debug("--> TcpIbis: address = " + myAddress);
}
return myAddress.toBytes();
}
/*
// NOTE: this is wrong ? Even though the ibis has left, the IbisIdentifier
may still be floating around in the system... We should just have
some timeout on the cache entries instead...
public void left(ibis.ipl.IbisIdentifier id) {
super.left(id);
synchronized(addresses) {
addresses.remove(id);
}
}
public void died(ibis.ipl.IbisIdentifier id) {
super.died(id);
synchronized(addresses) {
addresses.remove(id);
}
}
*/
IbisSocket connect(TcpSendPort sp, ibis.ipl.impl.ReceivePortIdentifier rip,
int timeout, boolean fillTimeout) throws IOException {
IbisIdentifier id = (IbisIdentifier) rip.ibisIdentifier();
String name = rip.name();
IbisSocketAddress idAddr;
synchronized(addresses) {
idAddr = addresses.get(id);
if (idAddr == null) {
idAddr = new IbisSocketAddress(id.getImplementationData());
addresses.put(id, idAddr);
}
}
long startTime = System.currentTimeMillis();
if (logger.isDebugEnabled()) {
logger.debug("--> Creating socket for connection to " + name
+ " at " + idAddr);
}
do {
DataOutputStream out = null;
IbisSocket s = null;
int result = -1;
try {
s = factory.createClientSocket(idAddr, timeout, fillTimeout,
sp.dynamicProperties());
s.setTcpNoDelay(true);
out = new DataOutputStream(new BufferedArrayOutputStream(
s.getOutputStream(), 4096));
out.writeUTF(name);
sp.getIdent().writeTo(out);
sp.getPortType().writeTo(out);
out.flush();
result = s.getInputStream().read();
switch(result) {
case ReceivePort.ACCEPTED:
return s;
case ReceivePort.ALREADY_CONNECTED:
throw new AlreadyConnectedException("Already connected", rip);
case ReceivePort.TYPE_MISMATCH:
throw new PortMismatchException(
"Cannot connect ports of different port types", rip);
case ReceivePort.DENIED:
throw new ConnectionRefusedException(
"Receiver denied connection", rip);
case ReceivePort.NO_MANYTOONE:
throw new ConnectionRefusedException(
"Receiver already has a connection and ManyToOne "
+ "is not set", rip);
case ReceivePort.NOT_PRESENT:
case ReceivePort.DISABLED:
// and try again if we did not reach the timeout...
if (timeout > 0 && System.currentTimeMillis()
> startTime + timeout) {
throw new ConnectionTimedOutException(
"Could not connect", rip);
}
break;
default:
throw new IOException("Illegal opcode in TcpIbis.connect");
}
} catch(SocketTimeoutException e) {
throw new ConnectionTimedOutException("Could not connect", rip);
} finally {
if (result != ReceivePort.ACCEPTED) {
try {
out.close();
} catch(Throwable e) {
// ignored
}
try {
s.close();
} catch(Throwable e) {
// ignored
}
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// ignore
}
} while (true);
}
protected void quit() {
try {
quiting = true;
// Connect so that the TcpIbis thread wakes up.
factory.createClientSocket(myAddress, 0, false, null);
} catch (Throwable e) {
// Ignore
}
}
private void handleConnectionRequest(IbisSocket s) throws IOException {
if (logger.isDebugEnabled()) {
logger.debug("--> TcpIbis got connection request from " + s);
}
BufferedArrayInputStream bais
= new BufferedArrayInputStream(s.getInputStream(), 4096);
DataInputStream in = new DataInputStream(bais);
OutputStream out = s.getOutputStream();
String name = in.readUTF();
SendPortIdentifier send = new SendPortIdentifier(in);
PortType sp = new PortType(in);
// First, lookup receiveport.
TcpReceivePort rp = (TcpReceivePort) findReceivePort(name);
int result;
if (rp == null) {
result = ReceivePort.NOT_PRESENT;
} else {
result = rp.connectionAllowed(send, sp);
}
if (logger.isDebugEnabled()) {
logger.debug("--> S RP = " + name + ": "
+ ReceivePort.getString(result));
}
out.write(result);
out.flush();
if (result == ReceivePort.ACCEPTED) {
// add the connection to the receiveport.
rp.connect(send, s, bais);
if (logger.isDebugEnabled()) {
logger.debug("--> S connect done ");
}
} else {
out.close();
in.close();
s.close();
}
}
public void run() {
// This thread handles incoming connection request from the
// connect(TcpSendPort) call.
boolean stop = false;
while (!stop) {
IbisSocket s = null;
if (logger.isDebugEnabled()) {
logger.debug("--> TcpIbis doing new accept()");
}
try {
s = systemServer.accept();
s.setTcpNoDelay(true);
} catch (Throwable e) {
/* if the accept itself fails, we have a fatal problem. */
logger.fatal("TcpIbis:run: got fatal exception in accept! ", e);
cleanup();
throw new Error("Fatal: TcpIbis could not do an accept", e);
// This error is thrown in the TcpIbis thread, not in a user
// thread. It kills the thread.
}
if (logger.isDebugEnabled()) {
logger.debug("--> TcpIbis through new accept()");
}
try {
if (quiting) {
s.close();
if (logger.isDebugEnabled()) {
logger.debug("--> it is a quit: RETURN");
}
cleanup();
return;
}
// This thread will now live on as a connection handler. Start
// a new accept thread here, and make sure that this thread does
// not do an accept again, if it ever returns to this loop.
stop = true;
try {
Thread.currentThread().setName("Connection Handler");
} catch (Exception e) {
// ignore
}
ThreadPool.createNew(this, "TcpIbis Accept Thread");
handleConnectionRequest(s);
} catch (Throwable e) {
try {
s.close();
} catch(Throwable e2) {
// ignored
}
logger.error("EEK: TcpIbis:run: got exception "
+ "(closing this socket only: ", e);
}
}
}
public void printStatistics() {
factory.printStatistics(ident.toString());
}
private void cleanup() {
try {
systemServer.close();
} catch (Throwable e) {
// Ignore
}
}
public void end() throws IOException {
super.end();
printStatistics();
}
protected SendPort doCreateSendPort(PortType tp, String nm,
SendPortDisconnectUpcall cU, Properties props) throws IOException {
return new TcpSendPort(this, tp, nm, cU, props);
}
protected ReceivePort doCreateReceivePort(PortType tp, String nm,
MessageUpcall u, ReceivePortConnectUpcall cU, Properties props)
throws IOException {
return new TcpReceivePort(this, tp, nm, u, cU, props);
}
}
diff --git a/src/ibis/ipl/impl/tcp/TcpReceivePort.java b/src/ibis/ipl/impl/tcp/TcpReceivePort.java
index 465ec182..67df250e 100644
--- a/src/ibis/ipl/impl/tcp/TcpReceivePort.java
+++ b/src/ibis/ipl/impl/tcp/TcpReceivePort.java
@@ -1,247 +1,252 @@
/* $Id$ */
package ibis.ipl.impl.tcp;
import ibis.ipl.MessageUpcall;
import ibis.ipl.PortType;
import ibis.ipl.ReceivePortConnectUpcall;
import ibis.ipl.impl.Ibis;
import ibis.ipl.impl.ReadMessage;
import ibis.ipl.impl.ReceivePort;
import ibis.ipl.impl.ReceivePortConnectionInfo;
import ibis.ipl.impl.ReceivePortIdentifier;
import ibis.ipl.impl.SendPortIdentifier;
import ibis.util.ThreadPool;
import ibis.io.BufferedArrayInputStream;
import ibis.io.Conversion;
import java.io.IOException;
import java.util.Properties;
class TcpReceivePort extends ReceivePort implements TcpProtocol {
class ConnectionHandler extends ReceivePortConnectionInfo
implements Runnable, TcpProtocol {
private final IbisSocket s;
ConnectionHandler(SendPortIdentifier origin, IbisSocket s,
ReceivePort port, BufferedArrayInputStream in)
throws IOException {
super(origin, port, in);
this.s = s;
}
public void close(Throwable e) {
super.close(e);
try {
s.close();
} catch (Throwable x) {
// ignore
}
}
public void run() {
try {
reader(false);
} catch (Throwable e) {
logger.debug("ConnectionHandler.run, connected "
+ "to " + origin + ", caught exception", e);
close(e);
}
}
protected void upcallCalledFinish() {
super.upcallCalledFinish();
ThreadPool.createNew(this, "ConnectionHandler");
}
void reader(boolean noThread) throws IOException {
byte opcode = -1;
// Moved here to prevent deadlocks and timeouts when using sun
// serialization -- Jason
if (in == null) {
newStream();
}
while (in != null) {
if (logger.isDebugEnabled()) {
logger.debug(name + ": handler for " + origin + " woke up");
}
opcode = in.readByte();
switch (opcode) {
case NEW_RECEIVER:
if (logger.isDebugEnabled()) {
logger.debug(name + ": Got a NEW_RECEIVER from "
+ origin);
}
newStream();
break;
case NEW_MESSAGE:
if (logger.isDebugEnabled()) {
logger.debug(name + ": Got a NEW_MESSAGE from "
+ origin);
}
message.setFinished(false);
if (numbered) {
message.setSequenceNumber(message.readLong());
}
ReadMessage m = message;
messageArrived(m);
// Note: if upcall calls finish, a new message is
// allocated, so we cannot look at "message" anymore.
if (noThread || m.finishCalledInUpcall()) {
return;
}
break;
case CLOSE_ALL_CONNECTIONS:
if (logger.isDebugEnabled()) {
logger.debug(name
+ ": Got a CLOSE_ALL_CONNECTIONS from "
+ origin);
}
close(null);
return;
case CLOSE_ONE_CONNECTION:
if (logger.isDebugEnabled()) {
logger.debug(name + ": Got a CLOSE_ONE_CONNECTION from "
+ origin);
}
// read the receiveport identifier from which the sendport
// disconnects.
byte[] length = new byte[Conversion.INT_SIZE];
in.readArray(length);
byte[] bytes = new byte[Conversion.defaultConversion
.byte2int(length, 0)];
in.readArray(bytes);
ReceivePortIdentifier identifier
= new ReceivePortIdentifier(bytes);
if (ident.equals(identifier)) {
// Sendport is disconnecting from me.
if (logger.isDebugEnabled()) {
logger.debug(name + ": disconnect from " + origin);
}
close(null);
}
break;
default:
throw new IOException(name + ": Got illegal opcode "
+ opcode + " from " + origin);
}
}
}
}
private final boolean no_connectionhandler_thread;
private boolean reader_busy = false;
TcpReceivePort(Ibis ibis, PortType type, String name, MessageUpcall upcall,
ReceivePortConnectUpcall connUpcall, Properties props) throws IOException {
super(ibis, type, name, upcall, connUpcall, props);
no_connectionhandler_thread = upcall == null && connUpcall == null
&& type.hasCapability(PortType.CONNECTION_ONE_TO_ONE)
&& !type.hasCapability(PortType.RECEIVE_POLL)
&& !type.hasCapability(PortType.RECEIVE_TIMEOUT);
}
public void messageArrived(ReadMessage msg) {
super.messageArrived(msg);
if (! no_connectionhandler_thread && upcall == null) {
synchronized(this) {
// Wait until the message is finished before starting to
// read from the stream again ...
while (! msg.isFinished()) {
try {
wait();
} catch(Exception e) {
// Ignored
}
}
}
}
}
public ReadMessage getMessage(long timeout) throws IOException {
if (no_connectionhandler_thread) {
// Allow only one reader in.
synchronized(this) {
while (reader_busy && ! closed) {
try {
wait();
} catch(Exception e) {
// ignored
}
}
if (closed) {
throw new IOException("receive() on closed port");
}
reader_busy = true;
}
// Since we don't have any threads or timeout here, this 'reader'
// call directly handles the receive.
for (;;) {
// Wait until there is a connection
synchronized(this) {
while (connections.size() == 0 && ! closed) {
try {
wait();
} catch (Exception e) {
/* ignore */
}
}
// Wait until the current message is done
while (message != null && ! closed) {
try {
wait();
} catch (Exception e) {
/* ignore */
}
}
if (closed) {
reader_busy = false;
notifyAll();
throw new IOException("receive() on closed port");
}
}
ReceivePortConnectionInfo conns[] = connections();
// Note: This call does NOT always result in a message!
((ConnectionHandler)conns[0]).reader(true);
synchronized(this) {
if (message != null) {
reader_busy = false;
notifyAll();
return message;
}
}
}
} else {
return super.getMessage(timeout);
}
}
public synchronized void closePort(long timeout) {
ReceivePortConnectionInfo conns[] = connections();
if (no_connectionhandler_thread && conns.length > 0) {
ThreadPool.createNew((ConnectionHandler) conns[0],
"ConnectionHandler");
}
super.closePort(timeout);
}
- synchronized void connect(SendPortIdentifier origin, IbisSocket s,
+ void connect(SendPortIdentifier origin, IbisSocket s,
BufferedArrayInputStream in) throws IOException {
- ConnectionHandler conn = new ConnectionHandler(origin, s, this, in);
+ ConnectionHandler conn;
+
+ synchronized(this) {
+ conn = new ConnectionHandler(origin, s, this, in);
+ }
if (! no_connectionhandler_thread) {
// ThreadPool.createNew(conn, "ConnectionHandler");
// We are already in a dedicated thread, so no need to create a new
// one!
+ // But this method was synchronized!!! Fixed (Ceriel).
conn.run();
}
}
}
| false | false | null | null |
diff --git a/src/main/java/com/softlysoftware/jxero/core/Invoice.java b/src/main/java/com/softlysoftware/jxero/core/Invoice.java
index 7690ee7..66ad2be 100644
--- a/src/main/java/com/softlysoftware/jxero/core/Invoice.java
+++ b/src/main/java/com/softlysoftware/jxero/core/Invoice.java
@@ -1,166 +1,169 @@
/*
* 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 com.softlysoftware.jxero.core;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.TimeZone;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "Invoice")
@XmlAccessorType(XmlAccessType.NONE)
public class Invoice {
// TODO - Parse using the Xero Account's timezone
private static SimpleDateFormat DF = new SimpleDateFormat("yyyy-MM-dd'T00:00:00'");
static {DF.setTimeZone(TimeZone.getTimeZone("UTC"));}
private static NumberFormat MONEY_FORMAT = new DecimalFormat("0.00");
@XmlElement(name = "InvoiceID")
private String id;
public String getId(){return id;}
public void setId(String id){this.id = id;}
@XmlElement(name = "InvoiceNumber")
private String number;
public String getNumber(){return number;}
public void setNumber(String number){this.number = number;}
public enum Type {ACCPAY, ACCREC};
@XmlElement(name = "Type")
private String type;
@XmlElement(name = "AmountDue")
- private double amountDue;
- public double getAmountDue() {return amountDue;}
- public void setAmountDue(double amountDue) {this.amountDue = amountDue;}
- public void setAmountDue(BigDecimal amountDue) {this.amountDue = amountDue;}
+ private String amountDue;
+ public double getAmountDue(){
+ try {return MONEY_FORMAT.parse(amountDue).doubleValue();}
+ catch (ParseException e) {throw new RuntimeException(e);}
+ }
+ public void setAmountDue(double amountDue){this.amountDue = MONEY_FORMAT.format(amountDue);}
+ public void setAmountDue(BigDecimal amountDue){this.amountDue = MONEY_FORMAT.format(amountDue);}
public Type getType() {
if (type == null) return null;
if (type.equals("ACCPAY")) return Type.ACCPAY;
if (type.equals("ACCREC")) return Type.ACCREC;
throw new RuntimeException("Bad Invoice type : " + type);
}
public void setType(Type type) {this.type = type.toString();}
@XmlElement(name = "Contact")
private Contact contact;
public Contact getContact(){return contact;}
public void setContact(Contact contact){this.contact = contact;}
@XmlElement(name = "Date")
private String date;
public Date getDate(){
try {return DF.parse(date);}
catch (ParseException e) {throw new RuntimeException(e);}
}
public void setDate(Date date){this.date = DF.format(date);}
@XmlElement(name = "DueDate")
private String dueDate;
public Date getDueDate(){
try {return DF.parse(dueDate);}
catch (ParseException e) {throw new RuntimeException(e);}
}
public void setDueDate(Date dueDate){this.dueDate = DF.format(dueDate);}
@XmlElement(name = "Reference")
private String reference;
public String getReference(){return reference;}
public void setReference(String reference){this.reference = reference;}
@XmlElement(name = "BrandingThemeID")
private String brandingThemeID;
public String getBrandingThemeID(){return brandingThemeID;}
public void setBrandingThemeID(String brandingThemeID){this.brandingThemeID = brandingThemeID;}
@XmlElement(name = "Url")
private String url;
public String getUrl(){return url;}
public void setUrl(String url){this.url = url;}
@XmlElement(name = "CurrencyCode")
private String currencyCode;
public String getCurrencyCode(){return currencyCode;}
public void setCurrencyCode(String currencyCode){this.currencyCode = currencyCode;}
public enum Status {DRAFT, SUBMITTED, AUTHORISED, PAID};
@XmlElement(name = "Status")
private String status;
public Status getStatus(){
if (status == null) return null;
if (status.equals("DRAFT")) return Status.DRAFT;
if (status.equals("SUBMITTED")) return Status.SUBMITTED;
if (status.equals("AUTHORISED")) return Status.AUTHORISED;
if (status.equals("PAID")) return Status.PAID;
throw new RuntimeException("Bad status : " + status);
}
public void setStatus(Status status){this.status = status.toString();}
@XmlElement(name = "LineAmountTypes")
private String lineAmountTypes;
public String getLineAmountTypes(){return lineAmountTypes;}
public void setLineAmountTypes(String lineAmountTypes){this.lineAmountTypes = lineAmountTypes;}
@XmlElement(name = "SubTotal")
private String subTotal;
public double getSubTotal(){
try {return MONEY_FORMAT.parse(subTotal).doubleValue();}
catch (ParseException e) {throw new RuntimeException(e);}
}
public void setSubTotal(double subTotal){this.subTotal = MONEY_FORMAT.format(subTotal);}
@XmlElement(name = "TotalTax")
private String totalTax;
public double getTotalTax(){
try {return MONEY_FORMAT.parse(totalTax).doubleValue();}
catch (ParseException e) {throw new RuntimeException(e);}
}
public void setTotalTax(double totalTax){this.totalTax = MONEY_FORMAT.format(totalTax);}
@XmlElement(name = "Total")
private String total;
public double getTotal(){
try {return MONEY_FORMAT.parse(total).doubleValue();}
catch (ParseException e) {throw new RuntimeException(e);}
}
public void setTotal(double total){this.total = MONEY_FORMAT.format(total);}
@XmlElementWrapper(name = "LineItems")
@XmlElement(name = "LineItem")
private List<LineItem> lineItems = new LinkedList<LineItem>();
public List<LineItem> getLineItems(){return lineItems;}
public void setLineItems(List<LineItem> lineItems){this.lineItems = lineItems;}
}
\ No newline at end of file
diff --git a/src/main/java/com/softlysoftware/jxero/core/LineItem.java b/src/main/java/com/softlysoftware/jxero/core/LineItem.java
index ab5e3f1..3496abd 100644
--- a/src/main/java/com/softlysoftware/jxero/core/LineItem.java
+++ b/src/main/java/com/softlysoftware/jxero/core/LineItem.java
@@ -1,92 +1,91 @@
/*
* 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 com.softlysoftware.jxero.core;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
@XmlRootElement(name = "LineItem")
@XmlAccessorType(XmlAccessType.NONE)
public class LineItem {
-
private static NumberFormat MONEY_FORMAT = new DecimalFormat("0.00");
private static NumberFormat QUANTITY_FORMAT = new DecimalFormat("0.0000");
@XmlElement(name = "Description")
private String description;
public String getDescription(){return description;}
public void setDescription(String description){this.description = description;}
@XmlElement(name = "Quantity")
private String quantity;
public double getQuantity(){
try {return QUANTITY_FORMAT.parse(quantity).doubleValue();}
catch (ParseException e) {throw new RuntimeException(e);}
}
public void setQuantity(double quantity){this.quantity = QUANTITY_FORMAT.format(quantity);}
- public void setQuantity(BigDecimal quantity){this.quantity = QUANTITY_FORMAT.format(quantity);}
+ public void setQuantity(BigDecimal quantity){this.quantity = QUANTITY_FORMAT.format(quantity);}
@XmlElement(name = "UnitAmount")
private String unitAmount;
public double getUnitAmount(){
try {return MONEY_FORMAT.parse(unitAmount).doubleValue();}
catch (ParseException e) {throw new RuntimeException(e);}
}
public void setUnitAmount(double unitAmount){this.unitAmount = MONEY_FORMAT.format(unitAmount);}
@XmlElement(name = "TaxType")
private String taxType;
public String getTaxType(){return taxType;}
public void setTaxType(String taxType){this.taxType = taxType;}
@XmlElement(name = "TaxAmount")
private String taxAmount;
public double getTaxAmount(){
try {return MONEY_FORMAT.parse(taxAmount).doubleValue();}
catch (ParseException e) {throw new RuntimeException(e);}
}
public void setTaxAmount(double taxAmount){this.taxAmount = MONEY_FORMAT.format(taxAmount);}
@XmlElement(name = "LineAmount")
private String lineAmount;
public double getLineAmount(){
try {return MONEY_FORMAT.parse(lineAmount).doubleValue();}
catch (ParseException e) {throw new RuntimeException(e);}
}
public void setLineAmount(double lineAmount){this.lineAmount = MONEY_FORMAT.format(lineAmount);}
@XmlElement(name = "AccountCode")
private String accountCode;
public String getAccountCode(){return accountCode;}
public void setAccountCode(String accountCode){this.accountCode = accountCode;}
@XmlElement(name = "ItemCode")
private String itemCode;
public String getItemCode(){return itemCode;}
public void setItemCode(String itemCode){this.itemCode = itemCode;}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/net/sf/redmine_mylyn/internal/api/client/Api_2_7_ClientImplTest.java b/src/net/sf/redmine_mylyn/internal/api/client/Api_2_7_ClientImplTest.java
index f2a736d..6f9c733 100644
--- a/src/net/sf/redmine_mylyn/internal/api/client/Api_2_7_ClientImplTest.java
+++ b/src/net/sf/redmine_mylyn/internal/api/client/Api_2_7_ClientImplTest.java
@@ -1,275 +1,302 @@
package net.sf.redmine_mylyn.internal.api.client;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.sf.redmine_mylyn.api.model.Configuration;
import net.sf.redmine_mylyn.internal.api.CustomFieldValidator;
import net.sf.redmine_mylyn.internal.api.IssueCategoryValidator;
import net.sf.redmine_mylyn.internal.api.IssuePriorityValidator;
import net.sf.redmine_mylyn.internal.api.IssueStatusValidator;
import net.sf.redmine_mylyn.internal.api.ProjectValidator;
import net.sf.redmine_mylyn.internal.api.QueryValidator;
import net.sf.redmine_mylyn.internal.api.TimeEntryActivityValidator;
import net.sf.redmine_mylyn.internal.api.TrackerValidator;
import net.sf.redmine_mylyn.internal.api.UserValidator;
import net.sf.redmine_mylyn.internal.api.VersionValidator;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.mylyn.commons.net.AbstractWebLocation;
import org.eclipse.mylyn.commons.net.WebLocation;
import org.eclipse.mylyn.commons.net.WebUtil;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class Api_2_7_ClientImplTest {
private final static String RESPONSE_HEADER_OK = "HTTP/1.0 200 OK\n\n";
private final static String RESPONSE_HEADER_NOT_FOUND = "HTTP/1.0 404 NOT FOUND\n\n";
static IProgressMonitor monitor;
static AbstractWebLocation location;
static Thread server;
// private TaskRepository repository;
Api_2_7_ClientImpl testee;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
monitor = new NullProgressMonitor();
location = new WebLocation("http://localhost:1234", "jsmith", "jsmith");
server = new Thread(new Runnable() {
+
@Override
public void run() {
+ Map <String, String> requestMap = new HashMap<String, String>();
+ requestMap.put("issues/updatedsince?issues=1,6,7,8&unixtime=123456789", "/xmldata/issues/updatedsince_1_7_8.xml");
+ requestMap.put("issues/updatedsince?issues=2,9&unixtime=123456789", "/xmldata/issues/updatedsince_2_9.xml");
+
+
try {
ServerSocket server = new ServerSocket(1234);
Pattern p = Pattern.compile("^(GET|POST)\\s+/mylyn/(\\S+).*$", Pattern.CASE_INSENSITIVE);
while(!Thread.interrupted()) {
OutputStream respStream = null;
BufferedReader reqReader = null;
Socket socket = server.accept();
try {
respStream = socket.getOutputStream();
reqReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String request = reqReader.readLine();
while(reqReader.ready()) {
reqReader.readLine();
}
boolean flag = true;
Matcher m = p.matcher(request);
if(m.find()) {
if(m.group(1).toUpperCase().equals("GET")) {
- InputStream responseStream = getClass().getResourceAsStream("/xmldata/" + m.group(2) + ".xml");
+ String uri = m.group(2);
+ InputStream responseStream = null;
+
+ if (requestMap.containsKey(uri)) {
+ responseStream = getClass().getResourceAsStream(requestMap.get(uri));
+ } else {
+ responseStream = getClass().getResourceAsStream("/xmldata/" + uri + ".xml");
+ }
+
if (responseStream!=null) {
try {
flag = false;
respStream.write(RESPONSE_HEADER_OK.getBytes());
int read = -1;
byte[] buffer = new byte[4096];
while((read=responseStream.read(buffer, 0, 4096))>-1) {
respStream.write(buffer, 0, read);
}
} finally {
responseStream.close();
}
}
}
if (flag) {
respStream.write(RESPONSE_HEADER_NOT_FOUND.getBytes());
}
}
} finally {
if(respStream!=null) {
respStream.close();
}
if(reqReader!=null) {
reqReader.close();
}
socket.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
server.start();
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
server.interrupt();
}
@Before
public void setUp() throws Exception {
testee = new Api_2_7_ClientImpl(location);
}
@After
public void tearDown() throws Exception {
}
@Test
public void testGetConfiguration() {
assertNotNull(testee.getConfiguration());
}
@Test
public void testUpdateConfiguration() throws Exception {
Configuration configuration = testee.getConfiguration();
assertNotNull(configuration.getIssueStatuses());
assertEquals(0, configuration.getIssueStatuses().getAll().size());
assertNotNull(configuration.getIssueCategories());
assertEquals(0, configuration.getIssueCategories().getAll().size());
assertNotNull(configuration.getIssuePriorities());
assertEquals(0, configuration.getIssuePriorities().getAll().size());
assertNotNull(configuration.getTrackers());
assertEquals(0, configuration.getTrackers().getAll().size());
assertNotNull(configuration.getCustomFields());
assertEquals(0, configuration.getCustomFields().getAll().size());
assertNotNull(configuration.getUsers());
assertEquals(0, configuration.getUsers().getAll().size());
assertNotNull(configuration.getTimeEntryActivities());
assertEquals(0, configuration.getTimeEntryActivities().getAll().size());
assertNotNull(configuration.getQueries());
assertEquals(0, configuration.getQueries().getAll().size());
assertNotNull(configuration.getProjects());
assertEquals(0, configuration.getProjects().getAll().size());
assertNotNull(configuration.getVersions());
assertEquals(0, configuration.getVersions().getAll().size());
assertNull(configuration.getSettings());
testee.updateConfiguration(null, true);
assertNotNull(configuration.getIssueStatuses());
assertEquals(IssueStatusValidator.COUNT, configuration.getIssueStatuses().getAll().size());
assertNotNull(configuration.getIssueCategories());
assertEquals(IssueCategoryValidator.COUNT, configuration.getIssueCategories().getAll().size());
assertNotNull(configuration.getIssuePriorities());
assertEquals(IssuePriorityValidator.COUNT, configuration.getIssuePriorities().getAll().size());
assertNotNull(configuration.getTrackers());
assertEquals(TrackerValidator.COUNT, configuration.getTrackers().getAll().size());
assertNotNull(configuration.getCustomFields());
assertEquals(CustomFieldValidator.COUNT, configuration.getCustomFields().getAll().size());
assertNotNull(configuration.getUsers());
assertEquals(UserValidator.COUNT, configuration.getUsers().getAll().size());
assertNotNull(configuration.getTimeEntryActivities());
assertEquals(TimeEntryActivityValidator.COUNT, configuration.getTimeEntryActivities().getAll().size());
assertNotNull(configuration.getQueries());
assertEquals(QueryValidator.COUNT, configuration.getQueries().getAll().size());
assertNotNull(configuration.getProjects());
assertEquals(ProjectValidator.COUNT, configuration.getProjects().getAll().size());
assertNotNull(configuration.getVersions());
assertEquals(VersionValidator.COUNT, configuration.getVersions().getAll().size());
assertNotNull(configuration.getSettings());
-
+ }
+
+ @Test
+ public void testUpdatedIssues() throws Exception {
+ int[] ids = testee.getUpdatedIssueIds(new int[]{1,6,7,8}, 123456789l, monitor);
+ assertNotNull(ids);
+ assertEquals("[1, 7, 8]", Arrays.toString(ids));
+
+ ids = testee.getUpdatedIssueIds(new int[]{2,9}, 123456789l, monitor);
+ assertNotNull(ids);
+ assertEquals(0, ids.length);
}
@Test
public void concurrencyRequests() throws Exception {
Class<AbstractClient> clazz = AbstractClient.class;
Field httpClientField = clazz.getDeclaredField("httpClient");
httpClientField.setAccessible(true);
HttpClient httpClient = (HttpClient)httpClientField.get(testee);
Method executeMethod = clazz.getDeclaredMethod("performExecuteMethod", HttpMethod.class, HostConfiguration.class, IProgressMonitor.class);
executeMethod.setAccessible(true);
HttpMethod firstMethod = new GetMethod("/mylyn/issuestatus");
HttpMethod secondMethod = new GetMethod("/mylyn/issuestatus");
HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor);
InputStream stream = getClass().getResourceAsStream(IssueStatusValidator.RESOURCE_FILE);
int len = stream.available();
int partialLen = len/2;
byte[] excpected = new byte[len];
stream.read(excpected, 0, len);
stream.close();
byte[] firstBuffer = new byte[len];
byte[] secondBuffer = new byte[len];
try {
executeMethod.invoke(testee, firstMethod, hostConfiguration, monitor);
InputStream firstStream = firstMethod.getResponseBodyAsStream();
firstStream.read(firstBuffer, 0, partialLen);
executeMethod.invoke(testee, secondMethod, hostConfiguration, monitor);
InputStream secondStream = secondMethod.getResponseBodyAsStream();
secondStream.read(secondBuffer, 0, len);
secondStream.close();
firstStream.read(firstBuffer, partialLen, len-partialLen);
firstStream.close();
} finally {
assertArrayEquals(excpected, firstBuffer);
assertArrayEquals(excpected, secondBuffer);
}
}
}
| false | false | null | null |
diff --git a/src/main/java/org/amplafi/flow/impl/BaseFlowManagement.java b/src/main/java/org/amplafi/flow/impl/BaseFlowManagement.java
index 068068c..47832b9 100644
--- a/src/main/java/org/amplafi/flow/impl/BaseFlowManagement.java
+++ b/src/main/java/org/amplafi/flow/impl/BaseFlowManagement.java
@@ -1,676 +1,676 @@
/*
* 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.amplafi.flow.impl;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
-import static com.sworddance.util.CUtilities.*;
-
import org.amplafi.flow.Flow;
import org.amplafi.flow.FlowActivity;
import org.amplafi.flow.FlowActivityImplementor;
import org.amplafi.flow.FlowActivityPhase;
import org.amplafi.flow.FlowImplementor;
import org.amplafi.flow.FlowManagement;
import org.amplafi.flow.FlowManager;
import org.amplafi.flow.FlowPropertyDefinition;
import org.amplafi.flow.FlowState;
import org.amplafi.flow.FlowStateLifecycle;
import org.amplafi.flow.FlowStateListener;
import org.amplafi.flow.FlowStepDirection;
import org.amplafi.flow.FlowTransition;
import org.amplafi.flow.FlowTranslatorResolver;
import org.amplafi.flow.FlowTx;
import org.amplafi.flow.FlowUtils;
import org.amplafi.flow.flowproperty.FlowPropertyDefinitionImpl;
import org.amplafi.flow.flowproperty.FlowPropertyDefinitionImplementor;
import org.amplafi.flow.flowproperty.FlowPropertyProvider;
import org.amplafi.flow.flowproperty.FlowPropertyProviderImplementor;
import org.amplafi.flow.flowproperty.FlowPropertyValueChangeListener;
import org.amplafi.flow.flowproperty.PropertyScope;
import org.amplafi.flow.flowproperty.PropertyUsage;
import org.amplafi.flow.launcher.ValueFromBindingProvider;
import org.amplafi.flow.web.PageProvider;
import com.sworddance.beans.ClassResolver;
import com.sworddance.beans.DefaultClassResolver;
import com.sworddance.util.ApplicationIllegalArgumentException;
import com.sworddance.util.perf.LapTimer;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import static org.amplafi.flow.FlowConstants.*;
import static org.apache.commons.lang.StringUtils.*;
+import static com.sworddance.util.CUtilities.*;
/**
* A basic implementation of FlowManagement.
*
*
*/
public class BaseFlowManagement implements FlowManagement {
private static final long serialVersionUID = -6759548552816525625L;
protected SessionFlows sessionFlows = new SessionFlows();
private transient FlowManager flowManager;
private transient FlowTx flowTx;
private transient PageProvider pageProvider;
private transient ValueFromBindingProvider valueFromBindingProvider;
private transient FlowTranslatorResolver flowTranslatorResolver;
private transient Set<FlowStateListener> flowStateListeners = Collections.synchronizedSet(new HashSet<FlowStateListener>());
private transient ClassResolver classResolver;
private URI defaultHomePage;
public BaseFlowManagement() {
}
/**
* @see org.amplafi.flow.FlowManagement#getFlowStates()
*/
public List<FlowState> getFlowStates() {
List<FlowState> collection= new ArrayList<FlowState>();
CollectionUtils.addAll(collection, sessionFlows.iterator());
return collection;
}
/**
* @see org.amplafi.flow.FlowManagement#dropFlowState(org.amplafi.flow.FlowState)
*/
public String dropFlowState(FlowState flow) {
return this.dropFlowStateByLookupKey(flow.getLookupKey());
}
public String getCurrentPage() {
FlowState flow = getCurrentFlowState();
if (flow != null ) {
return flow.getCurrentPage();
} else {
return null;
}
}
/**
* @see org.amplafi.flow.FlowManagement#getCurrentFlowState()
*/
@SuppressWarnings("unchecked")
public <FS extends FlowState> FS getCurrentFlowState() {
return (FS) sessionFlows.getFirst();
}
// /**
// * @see org.amplafi.flow.FlowManagement#getCurrentActivity()
// */
// public FlowActivity getCurrentActivity() {
// FlowState current = getCurrentFlowState();
// if ( current != null ) {
// return current.getCurrentActivity();
// } else {
// return null;
// }
// }
/**
* @see org.amplafi.flow.FlowManagement#getActiveFlowStatesByType(java.lang.String...)
*/
public synchronized List<FlowState> getActiveFlowStatesByType(String... flowTypes) {
List<String> types=Arrays.asList(flowTypes);
ArrayList<FlowState> result = new ArrayList<FlowState>();
for (FlowState flowState: sessionFlows) {
if (types.contains(flowState.getFlowTypeName())) {
result.add(flowState);
}
}
return result;
}
/**
* @see org.amplafi.flow.FlowManagement#getFirstFlowStateByType(java.lang.String...)
*/
@SuppressWarnings("unchecked")
public synchronized <FS extends FlowState> FS getFirstFlowStateByType(String... flowTypes) {
if(flowTypes == null){
return null;
}
List<String> types=Arrays.asList(flowTypes);
return (FS) getFirstFlowStateByType(types);
}
@SuppressWarnings("unchecked")
public <FS extends FlowState> FS getFirstFlowStateByType(Collection<String> types) {
for (FlowState flowState: sessionFlows) {
if (types.contains(flowState.getFlowTypeName())) {
return (FS)flowState;
}
}
return null;
}
public Flow getFlowDefinition(String flowTypeName) {
return getFlowManager().getFlowDefinition(flowTypeName);
}
/**
* @see org.amplafi.flow.FlowManagement#getFlowState(java.lang.String)
*/
@SuppressWarnings("unchecked")
public <FS extends FlowState> FS getFlowState(String lookupKey) {
FS flowState;
if ( isNotBlank(lookupKey)) {
flowState = (FS) sessionFlows.get(lookupKey);
} else {
flowState = null;
}
return flowState;
}
/**
* Override this method to create a custom {@link FlowState} object.
* @param flowTypeName
* @param initialFlowState
* @return the newly created FlowsState
*/
@SuppressWarnings("unchecked")
protected <FS extends FlowState> FS makeFlowState(String flowTypeName, Map<String, String> initialFlowState) {
return (FS) new FlowStateImpl(flowTypeName, this, initialFlowState);
}
/**
* @see org.amplafi.flow.FlowManagement#createFlowState(java.lang.String, java.util.Map, boolean)
* TODO : sees like method should be renamed.
*/
@SuppressWarnings("unchecked")
public synchronized <FS extends FlowState> FS createFlowState(String flowTypeName, Map<String, String> initialFlowState, boolean makeNewStateCurrent) {
FS flowState = (FS) makeFlowState(flowTypeName, initialFlowState);
initializeFlowState(flowState);
if (makeNewStateCurrent || this.sessionFlows.isEmpty()) {
makeCurrent(flowState);
} else {
makeLast(flowState);
}
return flowState;
}
@SuppressWarnings({ "unchecked" })
public <FS extends FlowState> FS createFlowState(String flowTypeName, FlowState initialFlowState, Map<String, String> initialValues, boolean makeNewStateCurrent) {
FS flowState = (FS) createFlowState(flowTypeName, initialFlowState.getFlowValuesMap(), makeNewStateCurrent);
return flowState;
}
protected <FS extends FlowState> void initializeFlowState(FS flowState) {
flowState.initializeFlow();
}
/**
* @see org.amplafi.flow.FlowManagement#transitionToFlowState(FlowState, String)
*/
@SuppressWarnings("unchecked")
@Override
public FlowState transitionToFlowState(FlowState flowState, String key) {
FlowState nextFlowState = null;
Map<String, FlowTransition> transitions = flowState.getProperty(key, Map.class);
String finishKey = flowState.getFinishKey();
if ( isNotEmpty(transitions) && isNotBlank(finishKey)) {
FlowTransition flowTransition = transitions.get(finishKey);
if ( flowTransition != null ) {
FlowActivityImplementor currentActivity = flowState.getCurrentActivity();
String flowType = currentActivity.resolveIndirectReference(flowTransition.getNextFlowType());
if (isNotBlank(flowType)) {
nextFlowState = this.createFlowState(flowType, flowState.getExportedValuesMap(), false);
FlowUtils.INSTANCE.copyMapToFlowState(nextFlowState, flowTransition.getInitialValues());
}
}
}
return nextFlowState;
}
/**
* @see org.amplafi.flow.FlowManagement#startFlowState(java.lang.String, boolean, java.util.Map, Object)
*/
@SuppressWarnings("unchecked")
public <FS extends FlowState> FS startFlowState(String flowTypeName, boolean makeNewStateCurrent, Map<String, String> initialFlowState, Object returnToFlow) {
initialFlowState = initReturnToFlow(initialFlowState, returnToFlow);
FS flowState = (FS) createFlowState(flowTypeName, initialFlowState, makeNewStateCurrent);
/* If you want tapestry stuff injected here...
// set default page to go to after flow if flow is successful
if (flowState.getDefaultAfterPage() == null ) {
IPage currentCyclePage;
try {
currentCyclePage = cycle.getPage();
} catch(NullPointerException e) {
// because of the way cycle is injected - it is impossible to see if the cycle is null.
// (normal java checks are looking at the proxy object)
currentCyclePage = null;
}
if ( currentCyclePage != null) {
flowState.setDefaultAfterPage(currentCyclePage.getPageName());
}
}
*/
return (FS) beginFlowState(flowState);
}
/**
* @param initialFlowState
* @param returnToFlow
* @return initialFlowState if existed otherwise a new map if returnToFlow was legal.
*/
protected Map<String, String> initReturnToFlow(Map<String, String> initialFlowState, Object returnToFlow) {
if ( returnToFlow != null) {
String returnToFlowLookupKey = null;
if ( returnToFlow instanceof Boolean) {
if ( ((Boolean)returnToFlow).booleanValue()) {
FlowState currentFlowState = getCurrentFlowState();
if ( currentFlowState != null) {
returnToFlowLookupKey = currentFlowState.getLookupKey();
}
}
} else if ( returnToFlow instanceof FlowState) {
returnToFlowLookupKey = ((FlowState)returnToFlow).getLookupKey();
} else {
returnToFlowLookupKey = returnToFlow.toString();
}
if ( isNotBlank(returnToFlowLookupKey)) {
if ( initialFlowState == null) {
initialFlowState = new HashMap<String, String>();
}
initialFlowState.put(FSRETURN_TO_FLOW, returnToFlowLookupKey);
}
}
return initialFlowState;
}
/**
* @see org.amplafi.flow.FlowManagement#continueFlowState(java.lang.String, boolean, java.util.Map)
*/
@SuppressWarnings("unchecked")
public <FS extends FlowState> FS continueFlowState(String lookupKey, boolean makeStateCurrent, Map<String, String> initialFlowState) {
FS flowState = (FS) getFlowState(lookupKey);
ApplicationIllegalArgumentException.notNull(lookupKey,": no flow with this lookupKey found");
if (isNotEmpty(initialFlowState)) {
for(Map.Entry<String, String> entry: initialFlowState.entrySet()) {
// HACK this looks bad. At the very least shouldn't FlowUtils.copyState be used
// more likely PropertyUsage/PropertyScope
((FlowStateImplementor)flowState).setRawProperty(entry.getKey(), entry.getValue());
}
}
if (makeStateCurrent) {
makeCurrent(flowState);
}
return flowState;
}
/**
* call flowState's {@link FlowState#begin()}. If flowState is now completed then see if the flow has transitioned to a new flow.
*
* @param flowState
* @return flowState if flowState has not completed, otherwise the continue flow or the return flow.
*/
@SuppressWarnings("unchecked")
protected <FS extends FlowState> FS beginFlowState(FlowState flowState) {
boolean success = false;
LapTimer.sLap(flowState, "beginning");
try {
flowState.begin();
success = true;
if ( flowState.isCompleted()) {
FS state = (FS) getNextFlowState(flowState);
if ( state != null) {
return state;
}
}
return (FS) flowState;
} finally {
if ( !success ) {
this.dropFlowState(flowState);
} else {
LapTimer.sLap(flowState, "begun");
}
}
}
/**
* @param flowState
* @return
*/
@SuppressWarnings("unchecked")
private <FS extends FlowState> FS getNextFlowState(FlowState flowState) {
String id = flowState.getProperty(FSCONTINUE_WITH_FLOW);
FS next = (FS) this.getFlowState(id);
if ( next == null ) {
id = flowState.getProperty(FSRETURN_TO_FLOW);
next = (FS) this.getFlowState(id);
}
return next;
}
@Override
public void wireDependencies(Object object) {
if (object instanceof FlowPropertyProvider) {
getFlowTranslatorResolver().resolve((FlowPropertyProvider)object);
}
if ( object instanceof FlowPropertyDefinition) {
// HACK : really should be handling the wiring issue without special casing.
FlowPropertyDefinition flowPropertyDefinition = (FlowPropertyDefinition) object;
for(FlowPropertyValueChangeListener flowPropertyValueChangeListener: flowPropertyDefinition.getFlowPropertyValueChangeListeners()) {
wireDependencies(flowPropertyValueChangeListener);
}
wireDependencies(flowPropertyDefinition.getTranslator());
wireDependencies(flowPropertyDefinition.getFlowPropertyValuePersister());
wireDependencies(flowPropertyDefinition.getFlowPropertyValueProvider());
}
}
/**
* @see org.amplafi.flow.FlowManagement#dropFlowStateByLookupKey(java.lang.String)
*/
public synchronized String dropFlowStateByLookupKey(String lookupKey) {
getLog().debug("Dropping flow "+lookupKey);
boolean successful = false;
try {
if ( !sessionFlows.isEmpty()) {
FlowStateImplementor fs = sessionFlows.getFirst();
boolean first = fs.hasLookupKey(lookupKey);
fs = (FlowStateImplementor) sessionFlows.removeByLookupKey(lookupKey);
if ( fs != null ) {
successful = true;
if ( !fs.getFlowStateLifecycle().isTerminalState()) {
fs.setFlowLifecycleState(FlowStateLifecycle.canceled);
}
// look for redirect before clearing the flow state
// why before cache clearing?
URI redirect = fs.getProperty(FSREDIRECT_URL);
String returnToFlowId = fs.getProperty(FSRETURN_TO_FLOW);
FlowState returnToFlow = getFlowState(returnToFlowId);
fs.clearCache();
if ( !first ) {
// dropped flow was not the current flow
// so we return the current flow's page.
return sessionFlows.getFirst().getCurrentPage();
} else if (redirect!=null) {
return redirect.toString();
} else if ( returnToFlow != null) {
return makeCurrent(returnToFlow);
} else if ( returnToFlowId != null ) {
getLog().warn("FlowState ("+fs.getLookupKey()+ ") trying to return to a flowState ("+returnToFlowId+") that could not be found.");
}
if ( !sessionFlows.isEmpty() ) {
return makeCurrent(sessionFlows.getFirst());
} else {
// no other flows...
return fs.getAfterPage();
}
}
}
return null;
} finally {
if ( !successful) {
getLog().info("Did not find flow to drop. key="+lookupKey);
}
}
}
/**
* Called by the {@link FlowState#finishFlow()}
* @param newFlowActive pass false if you already have flow to run.
*/
@Override
public String completeFlowState(FlowState flowState, boolean newFlowActive, FlowStateLifecycle flowStateLifecycle) {
return dropFlowState(flowState);
}
/**
* @see org.amplafi.flow.FlowManagement#makeCurrent(org.amplafi.flow.FlowState)
*/
@Override
public synchronized String makeCurrent(FlowState state) {
if ( !this.sessionFlows.isEmpty()) {
FlowStateImplementor oldFirst = this.sessionFlows.getFirst();
if ( oldFirst == state) {
// state is already the first state.
return state.getCurrentPage();
} else {
sessionFlows.remove((FlowStateImplementor)state);
if ( !oldFirst.isNotCurrentAllowed()) {
// the formerly first state is only supposed to be active if it is the first state.
// see if it this state is referenced as a return state -- otherwise the oldFirst will need to be dropped.
boolean notReferenced = state.isReferencing(oldFirst);
if ( !notReferenced ) {
for (FlowState flowState: this.sessionFlows) {
if( flowState.isReferencing(oldFirst)) {
notReferenced = false;
break;
}
}
}
if ( !notReferenced ) {
dropFlowState(oldFirst);
}
} else {
oldFirst.clearCache();
}
}
}
this.sessionFlows.makeFirst((FlowStateImplementor)state);
return state.getCurrentPage();
}
protected void makeLast(FlowState flowState) {
this.sessionFlows.addLast((FlowStateImplementor)flowState);
}
/**
* @see org.amplafi.flow.FlowManagement#makeAfter(org.amplafi.flow.FlowState, org.amplafi.flow.FlowState)
*/
@Override
public boolean makeAfter(FlowState flowState, FlowState nextFlowState) {
boolean wasFirst = this.sessionFlows.makeAfter((FlowStateImplementor)flowState, (FlowStateImplementor)nextFlowState) == 0;
if ( wasFirst) {
makeCurrent(this.sessionFlows.getFirst());
}
return wasFirst;
}
@Override
public <T> FlowPropertyDefinitionImplementor createFlowPropertyDefinition(FlowPropertyProviderImplementor flowPropertyProvider, String key, Class<T> expected, T sampleValue) {
Class<? extends T> expectedClass;
if ( expected == null) {
if ( this.getClassResolver() != null ) {
expectedClass = getClassResolver().getRealClass(sampleValue);
} else {
expectedClass = DefaultClassResolver.INSTANCE.getRealClass(sampleValue);
}
} else {
expectedClass = expected;
}
// something to be said for making it requestFlowLocal - because this would give flash persistence for free.
// but using global allows a property to be set that is really for the next flow to be run.
FlowPropertyDefinitionImpl propertyDefinition = new FlowPropertyDefinitionImpl(key).initAccess(PropertyScope.global, PropertyUsage.io);
if (expectedClass != null && !CharSequence.class.isAssignableFrom(expectedClass) ) {
// auto define property
// TODO save the definition when the flowState is persisted.
propertyDefinition.setDataClass(expectedClass);
if ( sampleValue != null) {
// actually going to be setting this property
+ getLog().warn("FlowState: Creating a dynamic FlowDefinition for key="+key+"(expected class="+expected+") might want to check situation. FlowState="+flowPropertyProvider );
flowPropertyProvider.addPropertyDefinitions(propertyDefinition);
}
}
- getLog().warn("FlowState: Creating a dynamic FlowDefinition for key="+key+"(expected class="+expected+") might want to check situation. FlowState="+flowPropertyProvider );
+ // HACK : don't think this should be a 'toString()' maybe flowProvidername ?
getFlowTranslatorResolver().resolve(flowPropertyProvider.toString(), propertyDefinition);
return propertyDefinition;
}
/**
* @see org.amplafi.flow.FlowManagement#getInstanceFromDefinition(java.lang.String)
*/
public FlowImplementor getInstanceFromDefinition(String flowTypeName) {
return getFlowManager().getInstanceFromDefinition(flowTypeName);
}
/**
* @see org.amplafi.flow.FlowManagement#registerForCacheClearing()
*/
public void registerForCacheClearing() {
}
public void setFlowTx(FlowTx flowTx) {
this.flowTx = flowTx;
}
public FlowTx getFlowTx() {
return flowTx;
}
public Log getLog() {
return LogFactory.getLog(this.getClass());
}
public void setFlowManager(FlowManager flowManager) {
this.flowManager = flowManager;
}
public FlowManager getFlowManager() {
return flowManager;
}
/**
* @param flowTranslatorResolver the flowTranslatorResolver to set
*/
public void setFlowTranslatorResolver(FlowTranslatorResolver flowTranslatorResolver) {
this.flowTranslatorResolver = flowTranslatorResolver;
}
/**
* @return the flowTranslatorResolver
*/
public FlowTranslatorResolver getFlowTranslatorResolver() {
return flowTranslatorResolver;
}
/**
* @see org.amplafi.flow.FlowManagement#getFlowPropertyDefinition(java.lang.String)
*/
@SuppressWarnings("unchecked")
@Override
public <T extends FlowPropertyDefinition> T getFlowPropertyDefinition(String key) {
return (T) this.getFlowTranslatorResolver().getFlowPropertyDefinition(key);
}
/**
* @see org.amplafi.flow.FlowManagement#getDefaultHomePage()
*/
@Override
public URI getDefaultHomePage() {
return this.defaultHomePage;
}
/**
* @param defaultHomePage the defaultHomePage to set
*/
public void setDefaultHomePage(URI defaultHomePage) {
this.defaultHomePage = defaultHomePage;
}
/**
* @see org.amplafi.flow.FlowManagement#addFlowStateListener(org.amplafi.flow.FlowStateListener)
*/
@Override
public void addFlowStateListener(FlowStateListener flowStateListener) {
if ( flowStateListener != null) {
this.getFlowStateListeners().add(flowStateListener);
}
}
public void lifecycleChange(FlowStateImplementor flowState, FlowStateLifecycle previousFlowStateLifecycle) {
//TODO synchronization issues if new listeners being added.
// TODO: allow FlowState specific listeners ( for example ExternalServiceConfigurationFlowActivity.finishFlow() )
// this would make the need to extend FA disappear even more.
for(FlowStateListener flowStateListener: this.getFlowStateListeners()) {
flowStateListener.lifecycleChange(flowState, previousFlowStateLifecycle);
}
}
public void activityChange(FlowStateImplementor flowState, FlowActivity flowActivity, FlowStepDirection flowStepDirection, FlowActivityPhase flowActivityPhase) {
//TODO synchronization issues if new listeners being added.
for(FlowStateListener flowStateListener: this.getFlowStateListeners()) {
flowStateListener.activityChange(flowState, flowActivity, flowStepDirection, flowActivityPhase);
}
}
/**
* @param pageProvider the pageProvider to set
*/
public void setPageProvider(PageProvider pageProvider) {
this.pageProvider = pageProvider;
}
/**
* @return the pageProvider
*/
public PageProvider getPageProvider() {
return pageProvider;
}
/**
* @param flowStateListeners the flowStateListeners to set
*/
public void setFlowStateListeners(Set<FlowStateListener> flowStateListeners) {
this.flowStateListeners.clear();
if ( isNotEmpty(flowStateListeners)) {
this.flowStateListeners.addAll(flowStateListeners);
}
}
/**
* @return the flowStateListeners
*/
public Set<FlowStateListener> getFlowStateListeners() {
return flowStateListeners;
}
/**
* @param valueFromBindingProvider the valueFromBindingProvider to set
*/
public void setValueFromBindingProvider(ValueFromBindingProvider valueFromBindingProvider) {
this.valueFromBindingProvider = valueFromBindingProvider;
}
/**
* @return the valueFromBindingProvider
*/
public ValueFromBindingProvider getValueFromBindingProvider() {
return valueFromBindingProvider;
}
/**
* @param classResolver the classResolver to set
*/
public void setClassResolver(ClassResolver classResolver) {
this.classResolver = classResolver;
}
/**
* @return the classResolver
*/
public ClassResolver getClassResolver() {
return classResolver;
}
}
diff --git a/src/main/java/org/amplafi/flow/impl/FlowImpl.java b/src/main/java/org/amplafi/flow/impl/FlowImpl.java
index fe86df6..f1fa5e7 100644
--- a/src/main/java/org/amplafi/flow/impl/FlowImpl.java
+++ b/src/main/java/org/amplafi/flow/impl/FlowImpl.java
@@ -1,494 +1,494 @@
/*
* 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.amplafi.flow.impl;
import java.io.Serializable;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import org.amplafi.flow.Flow;
import org.amplafi.flow.FlowActivity;
import org.amplafi.flow.FlowActivityImplementor;
import org.amplafi.flow.FlowGroup;
import org.amplafi.flow.FlowImplementor;
import org.amplafi.flow.FlowManagement;
import org.amplafi.flow.FlowPropertyDefinition;
import org.amplafi.flow.FlowState;
import org.amplafi.flow.FlowTransition;
import org.amplafi.flow.FlowUtils;
import org.amplafi.flow.flowproperty.CancelTextFlowPropertyValueProvider;
import org.amplafi.flow.flowproperty.FlowPropertyDefinitionImpl;
import org.amplafi.flow.flowproperty.MessageFlowPropertyValueProvider;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import static org.amplafi.flow.FlowConstants.*;
import static org.amplafi.flow.flowproperty.PropertyScope.*;
import static org.amplafi.flow.flowproperty.PropertyUsage.*;
import static org.apache.commons.lang.StringUtils.*;
/**
* defines a definition of a flow or a specific flow.
*
* <p>
* Flows consist of FlowActivities. FlowActivities can be shared across
* instances of Flows.
* <p>
* FlowActivities can create new objects. However it is the responsibility of
* the Flow to determine if the object created by FlowActivities should be
* actually persisted. (i.e. committed to the database.)
* <p>
* Flows are also responsible for connecting relationships. A FlowActivity may
* create a relationship object but it will not be aware of the endpoints of
* that relationship (a FlowActivity is not aware of the Flow nor its
* history/state.)
* <p>
* Flows should not keep references to objects that FlowActivities create or
* retrieve. The FlowActivity is responsible for that. This is important if a
* FlowActivity is shared amongst Flow instances.
* </p>
*/
public class FlowImpl extends BaseFlowPropertyProvider<FlowImplementor> implements Serializable, Cloneable, FlowImplementor, Iterable<FlowActivityImplementor> {
private static final long serialVersionUID = -985306244948511836L;
private FlowGroup primaryFlowGroup;
private List<FlowActivityImplementor> activities;
@Deprecated // use FlowPropertyDefinition
private String flowTitle;
@Deprecated // use FlowPropertyDefinition
private String continueFlowTitle;
@Deprecated // use FlowPropertyDefinition
private String linkTitle;
@Deprecated // use FlowPropertyDefinition
private String pageName;
@Deprecated // use FlowPropertyDefinition
private String defaultAfterPage;
@Deprecated // use FlowPropertyDefinition
private String mouseoverEntryPointText;
@Deprecated // use FlowPropertyDefinition
private String flowDescriptionText;
private transient FlowState flowState;
@Deprecated // use FlowPropertyDefinition
private boolean activatable;
/**
* False means {@link FlowState}s don't need to be current. True means that if a FlowState of this
* Flow type is no longer the current flow (after being the current flow), the FlowState
* is dropped.
*/
@Deprecated // use FlowPropertyDefinition
private boolean notCurrentAllowed;
/**
* Used to restore an existing definition or create an new definitions from XML
*/
public FlowImpl() {
// see #2179 #2192
this.addPropertyDefinitions(
new FlowPropertyDefinitionImpl(FSTITLE_TEXT).initAccess(flowLocal, use).initFlowPropertyValueProvider( MessageFlowPropertyValueProvider.INSTANCE ),
new FlowPropertyDefinitionImpl(FSNO_CANCEL, boolean.class).initAccess(flowLocal, use),
new FlowPropertyDefinitionImpl(FSFINISH_TEXT).initAccess(flowLocal, use).initFlowPropertyValueProvider( MessageFlowPropertyValueProvider.INSTANCE ),
new FlowPropertyDefinitionImpl(FSRETURN_TO_TEXT).initAccess(flowLocal, use).initFlowPropertyValueProvider( MessageFlowPropertyValueProvider.INSTANCE ),
// io -- for now because need to communicate the next page to be displayed
// TODO think about PropertyScope/PropertyUsage
new FlowPropertyDefinitionImpl(FSPAGE_NAME).initPropertyUsage(io),
// TODO think about PropertyScope/PropertyUsage
new FlowPropertyDefinitionImpl(FSAFTER_PAGE).initPropertyUsage(io),
new FlowPropertyDefinitionImpl(FSDEFAULT_AFTER_PAGE).initAccess(flowLocal, internalState),
new FlowPropertyDefinitionImpl(FSDEFAULT_AFTER_CANCEL_PAGE).initAccess(flowLocal, internalState),
new FlowPropertyDefinitionImpl(FSHIDE_FLOW_CONTROL, boolean.class).initPropertyScope(flowLocal),
new FlowPropertyDefinitionImpl(FSACTIVATABLE, boolean.class).initAccess(flowLocal, consume),
new FlowPropertyDefinitionImpl(FSIMMEDIATE_SAVE, boolean.class).initAccess(flowLocal, internalState),
new FlowPropertyDefinitionImpl(FSAPI_CALL, boolean.class).initAccess(flowLocal, io),
new FlowPropertyDefinitionImpl(FSAUTO_COMPLETE, boolean.class).initAccess(flowLocal, internalState),
new FlowPropertyDefinitionImpl(FSALT_FINISHED).initAccess(flowLocal, use),
new FlowPropertyDefinitionImpl(FSREDIRECT_URL, URI.class).initPropertyUsage(io),
new FlowPropertyDefinitionImpl(FSREFERRING_URL, URI.class).initPropertyUsage(use),
new FlowPropertyDefinitionImpl(FSCONTINUE_WITH_FLOW).initPropertyUsage(io),
new FlowPropertyDefinitionImpl(FSFLOW_TRANSITIONS, FlowTransition.class, Map.class).initAutoCreate().initAccess(flowLocal, use),
new FlowPropertyDefinitionImpl(FSFLOW_TRANSITION, FlowTransition.class).initAccess(flowLocal, initialize),
new FlowPropertyDefinitionImpl(FSRETURN_TO_FLOW).initPropertyUsage(io),
new FlowPropertyDefinitionImpl(FSRETURN_TO_FLOW_TYPE).initPropertyUsage(io),
new FlowPropertyDefinitionImpl(FSSUGGESTED_NEXT_FLOW_TYPE, FlowTransition.class, Map.class).initAutoCreate().initAccess(flowLocal, use),
// TODO think about PropertyScope/PropertyUsage
new FlowPropertyDefinitionImpl(FSNEXT_FLOW).initPropertyUsage(io)
);
CancelTextFlowPropertyValueProvider.INSTANCE.defineFlowPropertyDefinitions(this);
}
/**
* creates a instance Flow from a definition.
* @param definition
*/
public FlowImpl(FlowImplementor definition) {
super(definition);
this.setFlowPropertyProviderName(definition.getFlowPropertyProviderName());
}
/**
* Used to create a definition for testing.
*
* @param flowPropertyProviderName
*/
public FlowImpl(String flowPropertyProviderName) {
this();
this.setFlowPropertyProviderName(flowPropertyProviderName);
}
public FlowImpl(String flowTypeName, FlowActivityImplementor... flowActivities) {
this(flowTypeName);
for(FlowActivityImplementor flowActivity : flowActivities) {
addActivity(flowActivity);
}
}
@Override
public FlowImplementor createInstance() {
FlowImpl inst = new FlowImpl(this);
inst.activities = new ArrayList<FlowActivityImplementor>();
if ( CollectionUtils.isNotEmpty(this.activities)) {
for(FlowActivityImplementor activity: this.activities) {
FlowActivityImplementor fa = activity.createInstance();
if ( isActivatable() ) {
fa.setActivatable(true);
}
inst.addActivity(fa);
}
// need to always be able to start!
inst.activities.get(0).setActivatable(true);
}
return inst;
}
@Override
public void setActivities(List<FlowActivityImplementor> activities) {
this.activities = null;
for(FlowActivityImplementor activity: activities) {
this.addActivity(activity);
}
}
@SuppressWarnings("unchecked")
@Override
public List<FlowActivityImplementor> getActivities() {
return activities;
}
/**
* @see java.lang.Iterable#iterator()
*/
@Override
public ListIterator<FlowActivityImplementor> iterator() {
return this.activities.listIterator();
}
/**
* @see org.amplafi.flow.Flow#getActivity(int)
*/
@Override
@SuppressWarnings("unchecked")
public <T extends FlowActivity> T getActivity(int activityIndex) {
if ( activityIndex < 0 || activityIndex >= activities.size()) {
// this may be case if done with the flow or we haven't started it yet.
return null;
}
return (T) activities.get(activityIndex);
}
@Override
public void addActivity(FlowActivityImplementor activity) {
if ( activities == null ) {
activities = new ArrayList<FlowActivityImplementor>();
} else {
for(FlowActivityImplementor existing: activities) {
if (existing.isFlowPropertyProviderNameSet() && activity.isFlowPropertyProviderNameSet() && StringUtils.equalsIgnoreCase(existing.getFlowPropertyProviderName(), activity.getFlowPropertyProviderName())) {
throw new IllegalArgumentException(this.getFlowPropertyProviderName()+": A FlowActivity with the same name has already been added to this flow. existing="+existing+" new="+activity);
}
}
}
activity.setFlow(this);
activities.add(activity);
if ( !isInstance()) {
activity.processDefinitions();
}
}
@SuppressWarnings("unchecked")
@Override
public <T extends FlowActivity> List<T> getVisibleActivities() {
List<T> list = new ArrayList<T>();
for(FlowActivity flowActivity: this.activities) {
if (!flowActivity.isInvisible() ) {
list.add((T)flowActivity);
}
}
return list;
}
protected FlowManagement getFlowManagement() {
return this.getFlowState() == null ? null : this.getFlowState().getFlowManagement();
}
/**
* TODO -- copied from FlowActivityImpl -- not certain this is good idea.
* Need somewhat to find statically defined properties - not enough to always be looking at the flowState.
*/
protected <T> FlowPropertyDefinition getFlowPropertyDefinitionWithCreate(String key, Class<T> expected, T sampleValue) {
FlowPropertyDefinition flowPropertyDefinition = getFlowPropertyDefinition(key);
if (flowPropertyDefinition == null) {
- flowPropertyDefinition = getFlowManagement().createFlowPropertyDefinition(this, key, expected, sampleValue);
+ flowPropertyDefinition = getFlowManagement().createFlowPropertyDefinition((FlowImplementor)getFlow(), key, expected, sampleValue);
}
return flowPropertyDefinition;
}
@Override
public String getFlowPropertyProviderName() {
if ( super.getFlowPropertyProviderName() == null && isInstance()) {
return getDefinition().getFlowPropertyProviderName();
} else {
return super.getFlowPropertyProviderName();
}
}
@Override
public String getFlowTitle() {
if ( flowTitle == null && isInstance()) {
return getDefinition().getFlowTitle();
} else {
return this.flowTitle;
}
}
@Override
public void setFlowTitle(String flowTitle) {
this.flowTitle = flowTitle;
}
@Override
public String getContinueFlowTitle() {
if ( continueFlowTitle == null && isInstance()) {
return getDefinition().getContinueFlowTitle();
} else {
return this.continueFlowTitle;
}
}
@Override
public void setContinueFlowTitle(String continueFlowTitle) {
this.continueFlowTitle = continueFlowTitle;
}
@Override
public void setLinkTitle(String linkTitle) {
this.linkTitle = linkTitle;
}
@Override
public String getLinkTitle() {
if ( linkTitle != null ) {
return this.linkTitle;
} else if ( isInstance()) {
return getDefinition().getLinkTitle();
} else {
return "message:" + "flow." + FlowUtils.INSTANCE.toLowerCase(this.getFlowPropertyProviderName())+".link-title";
}
}
@Override
public String getMouseoverEntryPointText() {
if ( mouseoverEntryPointText == null && isInstance()) {
return getDefinition().getMouseoverEntryPointText();
} else {
return this.mouseoverEntryPointText;
}
}
@Override
public void setMouseoverEntryPointText(String mouseoverEntryPointText) {
this.mouseoverEntryPointText = mouseoverEntryPointText;
}
/**
* @see org.amplafi.flow.Flow#getFlowDescriptionText()
*/
@Override
public String getFlowDescriptionText() {
if ( flowDescriptionText == null && isInstance()) {
return getDefinition().getFlowDescriptionText();
} else {
return this.flowDescriptionText;
}
}
@Override
public void setFlowDescriptionText(String flowDescriptionText) {
this.flowDescriptionText = flowDescriptionText;
}
@Override
public void setPageName(String pageName) {
this.pageName = pageName;
}
/**
* @see org.amplafi.flow.Flow#getPageName()
*/
@Override
public String getPageName() {
return isInstance()&& pageName == null? getDefinition().getPageName() : pageName;
}
@Override
public void setDefaultAfterPage(String defaultAfterPage) {
this.defaultAfterPage = defaultAfterPage;
}
@Override
public String getDefaultAfterPage() {
return isInstance() && defaultAfterPage ==null? getDefinition().getDefaultAfterPage():defaultAfterPage;
}
@Override
public void refresh() {
int activityIndex = flowState.getCurrentActivityIndex();
FlowActivityImplementor flowActivity = getActivity(activityIndex);
if ( flowActivity != null ) {
flowActivity.refresh();
}
}
@Override
public void setFlowState(FlowState state) {
this.flowState = state;
}
@SuppressWarnings("unchecked")
@Override
public <FS extends FlowState> FS getFlowState() {
return (FS) this.flowState;
}
/**
* @see org.amplafi.flow.Flow#indexOf(org.amplafi.flow.FlowActivity)
*/
@Override
public int indexOf(FlowActivity activity) {
return this.activities.indexOf(activity);
}
/**
* @see org.amplafi.flow.Flow#setActivatable(boolean)
*/
@Override
public void setActivatable(boolean activatable) {
this.activatable = activatable;
}
/**
* @see org.amplafi.flow.Flow#isActivatable()
*/
@Override
public boolean isActivatable() {
return activatable;
}
/**
* @see org.amplafi.flow.Flow#setNotCurrentAllowed(boolean)
*/
@Override
public void setNotCurrentAllowed(boolean notCurrentAllowed) {
this.notCurrentAllowed = notCurrentAllowed;
}
/**
* @see org.amplafi.flow.Flow#isNotCurrentAllowed()
*/
public boolean isNotCurrentAllowed() {
return notCurrentAllowed;
}
@Override
public String toString() {
return getFlowPropertyProviderName()+ (isInstance()?"(instance)":"")+" activities=["+join(this.activities, ", ")+"]";
}
/**
* @see org.amplafi.flow.definitions.DefinitionSource#getFlowDefinition(java.lang.String)
*/
@Override
public FlowImplementor getFlowDefinition(String flowTypeName) {
if ( isFlowDefined(flowTypeName)) {
return this;
} else {
return null;
}
}
/**
* @see org.amplafi.flow.definitions.DefinitionSource#getFlowDefinitions()
*/
@Override
public Map<String, FlowImplementor> getFlowDefinitions() {
Map<String, FlowImplementor> map = new HashMap<String, FlowImplementor>();
map.put(this.getFlowPropertyProviderName(), this);
return map;
}
/**
* @see org.amplafi.flow.definitions.DefinitionSource#isFlowDefined(java.lang.String)
*/
@Override
public boolean isFlowDefined(String flowTypeName) {
return this.getFlowPropertyProviderName().equals(flowTypeName);
}
/**
* @param primaryFlowGroup the primaryFlowGroup to set
*/
public void setPrimaryFlowGroup(FlowGroup primaryFlowGroup) {
this.primaryFlowGroup = primaryFlowGroup;
}
/**
* @return the primaryFlowGroup
*/
public FlowGroup getPrimaryFlowGroup() {
return primaryFlowGroup;
}
/**
* @see org.amplafi.flow.FlowProvider#getFlow()
*/
@SuppressWarnings("unchecked")
@Override
public <F extends Flow> F getFlow() {
return (F) this;
}
}
| false | false | null | null |
diff --git a/hbase-firsthops/src/main/java/ch/x42/terye/value/BinaryImpl.java b/hbase-firsthops/src/main/java/ch/x42/terye/value/BinaryImpl.java
index c459c6b..aaae692 100644
--- a/hbase-firsthops/src/main/java/ch/x42/terye/value/BinaryImpl.java
+++ b/hbase-firsthops/src/main/java/ch/x42/terye/value/BinaryImpl.java
@@ -1,95 +1,94 @@
package ch.x42.terye.value;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.jcr.Binary;
import javax.jcr.RepositoryException;
public class BinaryImpl implements Binary {
// store contents in memory
private byte[] data;
// keep track of the opened input streams
- private List<InputStream> streams;
+ private List<InputStream> streams = new LinkedList<InputStream>();
private boolean isDisposed;
public BinaryImpl(InputStream stream) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try {
int nRead;
byte[] data = new byte[1048576];
while ((nRead = stream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
this.data = buffer.toByteArray();
- streams = new LinkedList<InputStream>();
isDisposed = false;
} finally {
buffer.close();
stream.close();
}
}
public BinaryImpl(byte[] data) {
this.data = data;
isDisposed = false;
}
private void checkDisposed() {
if (isDisposed) {
throw new IllegalStateException(
"Can't call any method on a disposed binary value");
}
}
@Override
public InputStream getStream() throws RepositoryException {
checkDisposed();
InputStream stream = new ByteArrayInputStream(data);
streams.add(stream);
return stream;
}
@Override
public int read(byte[] b, long position) throws IOException,
RepositoryException {
checkDisposed();
ByteArrayInputStream is = (ByteArrayInputStream) getStream();
try {
int res = is.read(b, (int) position, b.length);
return res;
} finally {
is.close();
}
}
@Override
public long getSize() throws RepositoryException {
return data.length;
}
@Override
public void dispose() {
isDisposed = true;
Iterator<InputStream> iterator = streams.iterator();
while (iterator.hasNext()) {
try {
iterator.next().close();
} catch (IOException e) {
// can't do nothing
}
}
}
public byte[] getByteArray() {
return data;
}
}
| false | false | null | null |
diff --git a/src/main/java/net/aufdemrand/denizen/objects/dPlayer.java b/src/main/java/net/aufdemrand/denizen/objects/dPlayer.java
index 8143df8bf..923f8cc62 100644
--- a/src/main/java/net/aufdemrand/denizen/objects/dPlayer.java
+++ b/src/main/java/net/aufdemrand/denizen/objects/dPlayer.java
@@ -1,786 +1,794 @@
package net.aufdemrand.denizen.objects;
import net.aufdemrand.denizen.flags.FlagManager;
import net.aufdemrand.denizen.tags.Attribute;
import net.aufdemrand.denizen.tags.core.PlayerTags;
import net.aufdemrand.denizen.utilities.DenizenAPI;
import net.aufdemrand.denizen.utilities.debugging.dB;
import net.aufdemrand.denizen.utilities.depends.Depends;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryType;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
public class dPlayer implements dObject {
/////////////////////
// STATIC METHODS
/////////////////
static Map<String, dPlayer> players = new HashMap<String, dPlayer>();
public static dPlayer mirrorBukkitPlayer(OfflinePlayer player) {
if (player == null) return null;
if (players.containsKey(player.getName())) return players.get(player.getName());
else return new dPlayer(player);
}
/////////////////////
// OBJECT FETCHER
/////////////////
@ObjectFetcher("p")
public static dPlayer valueOf(String string) {
if (string == null) return null;
string = string.replace("p@", "");
////////
// Match player name
OfflinePlayer returnable = null;
for (OfflinePlayer player : Bukkit.getOfflinePlayers())
if (player.getName().equalsIgnoreCase(string)) {
returnable = player;
break;
}
if (returnable != null) {
if (players.containsKey(returnable.getName())) return players.get(returnable.getName());
else return new dPlayer(returnable);
}
else dB.echoError("Invalid Player! '" + string
+ "' could not be found. Has the player logged off?");
return null;
}
public static boolean matches(String arg) {
arg = arg.replace("p@", "");
OfflinePlayer returnable = null;
for (OfflinePlayer player : Bukkit.getOfflinePlayers())
if (player.getName().equalsIgnoreCase(arg)) {
returnable = player;
break;
}
if (returnable != null) return true;
return false;
}
/////////////////////
// STATIC CONSTRUCTORS
/////////////////
public dPlayer(OfflinePlayer player) {
if (player == null) return;
this.player_name = player.getName();
// Keep in a map to avoid multiple instances of a dPlayer per player.
players.put(this.player_name, this);
}
/////////////////////
// INSTANCE FIELDS/METHODS
/////////////////
String player_name = null;
public boolean isValid() {
if (player_name == null) return false;
if (getPlayerEntity() == null && getOfflinePlayer() == null) return false;
return true;
}
public Player getPlayerEntity() {
if (player_name == null) return null;
return Bukkit.getPlayer(player_name);
}
public OfflinePlayer getOfflinePlayer() {
if (player_name == null) return null;
return Bukkit.getOfflinePlayer(player_name);
}
public dEntity getDenizenEntity() {
return new dEntity(getPlayerEntity());
}
public dNPC getSelectedNPC() {
if (getPlayerEntity().hasMetadata("selected"))
return dNPC.valueOf(getPlayerEntity().getMetadata("selected").get(0).asString());
else return null;
}
public String getName() {
return player_name;
}
public dLocation getLocation() {
if (isOnline()) return new dLocation(getPlayerEntity().getLocation());
else return null;
}
public dLocation getEyeLocation() {
if (isOnline()) return new dLocation(getPlayerEntity().getEyeLocation());
else return null;
}
public World getWorld() {
if (isOnline()) return getPlayerEntity().getWorld();
else return null;
}
public boolean isOnline() {
if (player_name == null) return false;
if (Bukkit.getPlayer(player_name) != null) return true;
return false;
}
/////////////////////
// dObject Methods
/////////////////
private String prefix = "Player";
@Override
public String getPrefix() {
return prefix;
}
@Override
public dPlayer setPrefix(String prefix) {
this.prefix = prefix;
return this;
}
@Override
public String debug() {
return (prefix + "='<A>" + identify() + "<G>' ");
}
@Override
public boolean isUnique() {
return true;
}
@Override
public String getType() {
return "Player";
}
@Override
public String identify() {
return "p@" + player_name;
}
@Override
public String toString() {
return identify();
}
@Override
public String getAttribute(Attribute attribute) {
if (attribute == null) return "null";
if (player_name == null) return "null";
// <--
// <player> -> dPlayer
// Returns the dPlayer of the player.
// -->
// <--
// <player.entity> -> dEntity
// returns the dEntity object of the player
// -->
if (attribute.startsWith("entity"))
return new dEntity(getPlayerEntity())
.getAttribute(attribute.fulfill(1));
// <--
// <player.has_played_before> -> Element(boolean)
// returns true if the player has played before
// -->
if (attribute.startsWith("has_played_before"))
return new Element(String.valueOf(getOfflinePlayer().hasPlayedBefore()))
.getAttribute(attribute.fulfill(1));
// <--
// <player.is_op> -> Element(boolean)
// returns true if the player has 'op status'
// -->
if (attribute.startsWith("is_op"))
return new Element(String.valueOf(getOfflinePlayer().isOp()))
.getAttribute(attribute.fulfill(1));
// <--
// <player.first_played> -> Element(number)
// returns the 'System.currentTimeMillis()' of when the player
// first logged on. Will return '0' if player has never played.
// -->
if (attribute.startsWith("first_played"))
return new Element(String.valueOf(getOfflinePlayer().getFirstPlayed()))
.getAttribute(attribute.fulfill(1));
// <--
// <player.last_played> -> Element(number)
// returns the 'System.currentTimeMillis()' of when the player
// was last seen. Will return '0' if player has never played.
// -->
if (attribute.startsWith("last_played"))
return new Element(String.valueOf(getOfflinePlayer().getLastPlayed()))
.getAttribute(attribute.fulfill(1));
// <--
// <player.is_banned> -> Element(boolean)
// returns true if the player is banned
// -->
if (attribute.startsWith("is_banned"))
return new Element(String.valueOf(getOfflinePlayer().isBanned()))
.getAttribute(attribute.fulfill(1));
// <--
// <player.is_whitelisted> -> Element(boolean)
// returns true if the player is whitelisted
// -->
if (attribute.startsWith("is_whitelisted"))
return new Element(String.valueOf(getOfflinePlayer().isWhitelisted()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("name") && !isOnline())
// This can be parsed later with more detail if the player is online, so only check for offline.
return new Element(player_name).getAttribute(attribute.fulfill(1));
// <--
// <player.is_online> -> Element(boolean)
// returns true if the player is currently online
// -->
if (attribute.startsWith("is_online"))
return new Element(String.valueOf(isOnline())).getAttribute(attribute.fulfill(1));
// Return player ip in format #.#.#.#
if (attribute.startsWith("ip"))
return getPlayerEntity().getAddress().getHostName();
if (attribute.startsWith("list")) {
List<String> players = new ArrayList<String>();
if (attribute.startsWith("list.online")) {
for(Player player : Bukkit.getOnlinePlayers())
players.add(player.getName());
return new dList(players).getAttribute(attribute.fulfill(2));
}
else if (attribute.startsWith("list.offline")) {
for(OfflinePlayer player : Bukkit.getOfflinePlayers()) {
if (!Bukkit.getOnlinePlayers().toString().contains(player.getName()))
players.add(player.getName());
}
return new dList(players).getAttribute(attribute.fulfill(2));
}
else {
for(OfflinePlayer player : Bukkit.getOfflinePlayers())
players.add(player.getName());
return new dList(players).getAttribute(attribute.fulfill(1));
}
}
// <--
// <player.chat_history_list> -> dList
// Returns a list of the last 10 things the player has said, less
// if the player hasn't said all that much.
// -->
if (attribute.startsWith("chat_history_list"))
return new dList(PlayerTags.playerChatHistory.get(player_name))
.getAttribute(attribute.fulfill(1));
// <--
// <player.chat_history> -> Element
// returns the last thing the player said.
// -->
if (attribute.startsWith("chat_history")) {
int x = 1;
if (attribute.hasContext(1) && aH.matchesInteger(attribute.getContext(1)))
x = attribute.getIntContext(1);
return new Element(PlayerTags.playerChatHistory.get(player_name).get(x - 1))
.getAttribute(attribute.fulfill(1));
}
// <--
// <player.bed_spawn> -> dLocation
// Returns a dLocation of the player's bed spawn location, 'null' if
// it doesn't exist.
// -->
if (attribute.startsWith("bed_spawn"))
return new dLocation(getOfflinePlayer().getBedSpawnLocation())
.getAttribute(attribute.fulfill(2));
// <--
// <player.money> -> Element(number)
// returns the amount of money the player has with the registered
// Economy system.
// -->
if (attribute.startsWith("money")) {
if(Depends.economy != null) {
// <--
// <player.money.currency_singular> -> Element
// returns the 'singular currency' string, if supported by the
// registered Economy system.
// -->
if (attribute.startsWith("money.currency_singular"))
return new Element(Depends.economy.currencyNameSingular())
.getAttribute(attribute.fulfill(2));
// <--
// <player.money.currency> -> Element
// returns the 'currency' string, if supported by the
// registered Economy system.
// -->
if (attribute.startsWith("money.currency"))
return new Element(Depends.economy.currencyNamePlural())
.getAttribute(attribute.fulfill(2));
return new Element(String.valueOf(Depends.economy.getBalance(player_name)))
.getAttribute(attribute.fulfill(1));
} else {
dB.echoError("No economy loaded! Have you installed Vault and a compatible economy plugin?");
return null;
}
}
if (!isOnline()) return new Element(identify()).getAttribute(attribute);
// Player is required to be online after this point...
// <--
+ // <player.xp.to_next_level> -> Element(number)
+ // returns the amount of experience to the next level.
+ // -->
+ if (attribute.startsWith("xp.to_next_level"))
+ return new Element(String.valueOf(getPlayerEntity().getExpToLevel()))
+ .getAttribute(attribute.fulfill(2));
+
+ // <--
// <player.xp.total> -> Element(number)
// returns the total amount of experience points.
// -->
if (attribute.startsWith("xp.total"))
return new Element(String.valueOf(getPlayerEntity().getTotalExperience()))
.getAttribute(attribute.fulfill(2));
// <--
// <player.xp.level> -> Element(number)
// returns the number of levels the player has.
// -->
if (attribute.startsWith("xp.level"))
return new Element(getPlayerEntity().getLevel())
.getAttribute(attribute.fulfill(2));
// <--
// <player.xp> -> Element(number)
// returns the percentage of experience points to the next level.
// -->
if (attribute.startsWith("xp"))
return new Element(String.valueOf(getPlayerEntity().getExp() * 100))
.getAttribute(attribute.fulfill(1));
// <--
// <player.equipment.boots> -> dItem
// returns the item the player is wearing as boots, or null
// if none.
// -->
if (attribute.startsWith("equipment.boots"))
if (getPlayerEntity().getInventory().getBoots() != null)
return new dItem(getPlayerEntity().getInventory().getBoots())
.getAttribute(attribute.fulfill(2));
// <--
// <player.equipment.chestplate> -> dItem
// returns the item the player is wearing as a chestplate, or null
// if none.
// -->
if (attribute.startsWith("equipment.chestplate"))
if (getPlayerEntity().getInventory().getChestplate() != null)
return new dItem(getPlayerEntity().getInventory().getChestplate())
.getAttribute(attribute.fulfill(2));
// <--
// <player.equipment.helmet> -> dItem
// returns the item the player is wearing as a helmet, or null
// if none.
// -->
if (attribute.startsWith("equipment.helmet"))
if (getPlayerEntity().getInventory().getHelmet() != null)
return new dItem(getPlayerEntity().getInventory().getHelmet())
.getAttribute(attribute.fulfill(2));
// <--
// <player.equipment.leggings> -> dItem
// returns the item the player is wearing as leggings, or null
// if none.
// -->
if (attribute.startsWith("equipment.leggings"))
if (getPlayerEntity().getInventory().getLeggings() != null)
return new dItem(getPlayerEntity().getInventory().getLeggings())
.getAttribute(attribute.fulfill(2));
// <--
// <player.equipment> -> dInventory
// returns a dInventory containing the player's equipment
// -->
if (attribute.startsWith("equipment"))
// The only way to return correct size for dInventory
// created from equipment is to use a CRAFTING type
// that has the expected 4 slots
return new dInventory(InventoryType.CRAFTING).add(getPlayerEntity().getInventory().getArmorContents())
.getAttribute(attribute.fulfill(1));
// <--
// <player.inventory> -> dInventory
// returns a dInventory of the player's current inventory.
// -->
if (attribute.startsWith("inventory"))
return new dInventory(getPlayerEntity().getInventory())
.getAttribute(attribute.fulfill(1));
// <--
// <player.item_in_hand> -> dItem
// returns the item the player is holding, or null
// if none.
// -->
if (attribute.startsWith("item_in_hand"))
return new dItem(getPlayerEntity().getItemInHand())
.getAttribute(attribute.fulfill(1));
// <--
// <player.name.display> -> Element
// returns the 'display name' of the player, which may contain
// prefixes and suffixes/color, etc.
// -->
if (attribute.startsWith("name.display"))
return new Element(getPlayerEntity().getDisplayName())
.getAttribute(attribute.fulfill(2));
// <--
// <player.name.list> -> Element
// returns the name of the player as shown in the 'player list'.
// -->
if (attribute.startsWith("name.list"))
return new Element(getPlayerEntity().getPlayerListName())
.getAttribute(attribute.fulfill(2));
// <--
// <player.name> -> Element
// returns the name of the player.
// -->
if (attribute.startsWith("name"))
return new Element(player_name).getAttribute(attribute.fulfill(1));
// <--
// <player.eyes> -> dLocation
// returns a dLocation of the player's eyes.
// -->
if (attribute.startsWith("eyes"))
return new dLocation(getEyeLocation())
.getAttribute(attribute.fulfill(1));
// <--
// <player.compass.target> -> dLocation
// returns a dLocation of the player's 'compass target'.
// -->
if (attribute.startsWith("compass_target"))
return new dLocation(getPlayerEntity().getCompassTarget())
.getAttribute(attribute.fulfill(2));
// <--
// <player.food_level.formatted> -> Element
// returns a 'formatted' value of the player's current food level.
// May be 'starving', 'famished', 'parched, 'hungry' or 'healthy'
// -->
if (attribute.startsWith("food_level.formatted")) {
double maxHunger = getPlayerEntity().getMaxHealth();
if (attribute.hasContext(2))
maxHunger = attribute.getIntContext(2);
if ((float) getPlayerEntity().getFoodLevel() / maxHunger < .10)
return new Element("starving").getAttribute(attribute.fulfill(2));
else if ((float) getPlayerEntity().getFoodLevel() / maxHunger < .40)
return new Element("famished").getAttribute(attribute.fulfill(2));
else if ((float) getPlayerEntity().getFoodLevel() / maxHunger < .75)
return new Element("parched").getAttribute(attribute.fulfill(2));
else if ((float) getPlayerEntity().getFoodLevel() / maxHunger < 1)
return new Element("hungry").getAttribute(attribute.fulfill(2));
else return new Element("healthy").getAttribute(attribute.fulfill(2));
}
// <--
// <player.food_level> -> Element(number)
// returns the current food level of the player.
// -->
if (attribute.startsWith("food_level"))
return new Element(String.valueOf(getPlayerEntity().getFoodLevel()))
.getAttribute(attribute.fulfill(1));
// <--
// <player.has_permission[permission.node]> -> Element(boolean)
// returns true if the player has the specified node, false otherwise
// -->
if (attribute.startsWith("permission")
|| attribute.startsWith("has_permission")) {
if (Depends.permissions == null) {
dB.echoError("No permission system loaded! Have you installed Vault and a compatible permissions plugin?");
return null;
}
String permission = attribute.getContext(1);
// <--
// <player.has_permission[permission.node].global> -> Element(boolean)
// returns true if the player has the specified node, regardless of world.
// this may or may not be functional with your permissions system.
// -->
// Non-world specific permission
if (attribute.getAttribute(2).startsWith("global"))
return new Element(String.valueOf(Depends.permissions.has((World) null, player_name, permission)))
.getAttribute(attribute.fulfill(2));
// Permission in certain world
else if (attribute.getAttribute(2).startsWith("world"))
return new Element(String.valueOf(Depends.permissions.has(attribute.getContext(2), player_name, permission)))
.getAttribute(attribute.fulfill(2));
// <--
// <player.has_permission[permission.node].world> -> Element(boolean)
// returns true if the player has the specified node in regards to the
// player's current world. This may or may not be functional with your
// permissions system.
// -->
// Permission in current world
return new Element(String.valueOf(Depends.permissions.has(getPlayerEntity(), permission)))
.getAttribute(attribute.fulfill(1));
}
// <--
// <player.flag[flag_name]> -> Flag dList
// returns 'flag dList' of the player's flag_name specified.
// -->
if (attribute.startsWith("flag")) {
String flag_name;
if (attribute.hasContext(1)) flag_name = attribute.getContext(1);
else return "null";
attribute.fulfill(1);
if (attribute.startsWith("is_expired")
|| attribute.startsWith("isexpired"))
return new Element(!FlagManager.playerHasFlag(this, flag_name))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("size") && !FlagManager.playerHasFlag(this, flag_name))
return new Element(0).getAttribute(attribute.fulfill(1));
if (FlagManager.playerHasFlag(this, flag_name))
return new dList(DenizenAPI.getCurrentInstance().flagManager()
.getPlayerFlag(getName(), flag_name))
.getAttribute(attribute);
else return "null";
}
// <--
// <player.in_group[group_name]> -> Element(boolean)
// returns true if the player has the specified group, false otherwise
// -->
if (attribute.startsWith("group")
|| attribute.startsWith("in_group")) {
if (Depends.permissions == null) {
dB.echoError("No permission system loaded! Have you installed Vault and a compatible permissions plugin?");
return "null";
}
String group = attribute.getContext(1);
// <--
// <player.in_group[group_name].global> -> Element(boolean)
// returns true if the player has the group with no regard to the
// player's current world. This may or may not be functional with your
// permissions system.
// -->
// Non-world specific permission
if (attribute.getAttribute(2).startsWith("global"))
return new Element(String.valueOf(Depends.permissions.playerInGroup((World) null, player_name, group)))
.getAttribute(attribute.fulfill(2));
// Permission in certain world
else if (attribute.getAttribute(2).startsWith("world"))
return new Element(String.valueOf(Depends.permissions.playerInGroup(attribute.getContext(2), player_name, group)))
.getAttribute(attribute.fulfill(2));
// <--
// <player.in_group[group_name].world> -> Element(boolean)
// returns true if the player has the group in regards to the
// player's current world. This may or may not be functional with your
// permissions system.
// -->
// Permission in current world
return new Element(String.valueOf(Depends.permissions.playerInGroup(getPlayerEntity(), group)))
.getAttribute(attribute.fulfill(1));
}
// <--
// <player.is_flying> -> Element(boolean)
// returns true if the player is currently flying, false otherwise
// -->
if (attribute.startsWith("is_flying"))
return new Element(String.valueOf(getPlayerEntity().isFlying()))
.getAttribute(attribute.fulfill(1));
// <--
// <player.is_sneaking> -> Element(boolean)
// returns true if the player is currently sneaking, false otherwise
// -->
if (attribute.startsWith("is_sneaking"))
return new Element(String.valueOf(getPlayerEntity().isSneaking()))
.getAttribute(attribute.fulfill(1));
// <--
// <player.is_blocking> -> Element(boolean)
// returns true if the player is currently blocking, false otherwise
// -->
if (attribute.startsWith("is_blocking"))
return new Element(String.valueOf(getPlayerEntity().isBlocking()))
.getAttribute(attribute.fulfill(1));
// <--
// <player.is_sleeping> -> Element(boolean)
// returns true if the player is currently sleeping, false otherwise
// -->
if (attribute.startsWith("is_sleeping"))
return new Element(String.valueOf(getPlayerEntity().isSleeping()))
.getAttribute(attribute.fulfill(1));
// <--
// <player.is_sprinting> -> Element(boolean)
// returns true if the player is currently sprinting, false otherwise
// -->
if (attribute.startsWith("is_sprinting"))
return new Element(String.valueOf(getPlayerEntity().isSprinting()))
.getAttribute(attribute.fulfill(1));
// <--
// <player.gamemode.id> -> Element(number)
// returns 'gamemode id' of the player. 0 = survival, 1 = creative, 2 = adventure
// -->
if (attribute.startsWith("gamemode.id"))
return new Element(String.valueOf(getPlayerEntity().getGameMode().getValue()))
.getAttribute(attribute.fulfill(1));
// <--
// <player.gamemode> -> Element
// returns the name of the gamemode the player is currently set to.
// -->
if (attribute.startsWith("gamemode"))
return new Element(String.valueOf(getPlayerEntity().getGameMode().toString()))
.getAttribute(attribute.fulfill(1));
// <--
// <player.item_on_cursor> -> dItem
// returns a dItem that the player's cursor is on, if any. This includes
// chest interfaces, inventories, and hotbars, etc.
// -->
if (attribute.startsWith("item_on_cursor"))
return new dItem(getPlayerEntity().getItemOnCursor())
.getAttribute(attribute.fulfill(1));
// <--
// <player.selected_npc> -> dNPC
// returns the dNPC that the player currently has selected with
// '/npc sel', null if no player selected.
// -->
if (attribute.startsWith("selected_npc")) {
if (getPlayerEntity().hasMetadata("selected"))
return dNPC.valueOf(getPlayerEntity().getMetadata("selected").get(0).asString())
.getAttribute(attribute.fulfill(1));
else return "null";
}
// <--
// <player.allowed_flight> -> Element(boolean)
// returns true if the player is allowed to fly, and false otherwise
// -->
if (attribute.startsWith("allowed_flight"))
return new Element(String.valueOf(getPlayerEntity().getAllowFlight()))
.getAttribute(attribute.fulfill(1));
// <--
// <player.host_name> -> Element
// returns the player's 'host name'.
// -->
if (attribute.startsWith("host_name"))
return new Element(String.valueOf(getPlayerEntity().getAddress().getHostName()))
.getAttribute(attribute.fulfill(1));
// <--
// <player.time_asleep> -> Duration
// returns a Duration of the time the player has been asleep.
// -->
if (attribute.startsWith("time_asleep"))
return new Duration(getPlayerEntity().getSleepTicks() / 20)
.getAttribute(attribute.fulfill(1));
// <--
// <player.player_time> -> Element
// returns the time, specific to the player
// -->
if (attribute.startsWith("player_time"))
return new Element(String.valueOf(getPlayerEntity().getPlayerTime()))
.getAttribute(attribute.fulfill(1));
// <--
// <player.player_time_offset> -> Element
// returns the player's 'offset' of time vs. the real time.
// -->
if (attribute.startsWith("player_time_offset"))
return new Element(String.valueOf(getPlayerEntity().getPlayerTimeOffset()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("prefix"))
return new Element(prefix)
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("debug.log")) {
dB.log(debug());
return new Element(Boolean.TRUE.toString())
.getAttribute(attribute.fulfill(2));
}
if (attribute.startsWith("debug.no_color")) {
return new Element(ChatColor.stripColor(debug()))
.getAttribute(attribute.fulfill(2));
}
if (attribute.startsWith("debug")) {
return new Element(debug())
.getAttribute(attribute.fulfill(1));
}
return new dEntity(getPlayerEntity()).getAttribute(attribute.fulfill(0));
}
}
| true | false | null | null |
diff --git a/cal10n-ant-task/src/main/java/ch/qos/cal10n/ant/VerifyTask.java b/cal10n-ant-task/src/main/java/ch/qos/cal10n/ant/VerifyTask.java
index 34bb331..bf50e2e 100644
--- a/cal10n-ant-task/src/main/java/ch/qos/cal10n/ant/VerifyTask.java
+++ b/cal10n-ant-task/src/main/java/ch/qos/cal10n/ant/VerifyTask.java
@@ -1,129 +1,129 @@
/*
* Copyright (c) 2009 QOS.ch All rights reserved.
*
* 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 ch.qos.cal10n.ant;
-import ch.qos.cal10n.Cal10nConstants;
+import ch.qos.cal10n.CAL10NConstants;
import ch.qos.cal10n.verifier.IMessageKeyVerifier;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.LogLevel;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.types.Reference;
import org.apache.tools.ant.util.ClasspathUtils;
import java.lang.reflect.Constructor;
import java.text.MessageFormat;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
public class VerifyTask extends Task {
private List<StringElement> enumTypes;
private Path classpath;
@Override
public void init() throws BuildException {
this.enumTypes = new LinkedList<StringElement>();
}
@Override
public void execute() throws BuildException {
if (this.enumTypes.isEmpty()) {
- throw new BuildException(Cal10nConstants.MISSING_ENUM_TYPES_MSG);
+ throw new BuildException(CAL10NConstants.MISSING_ENUM_TYPES_MSG);
}
for (StringElement enumType : this.enumTypes) {
IMessageKeyVerifier imcv = getMessageKeyVerifierInstance(enumType.getText());
log("Checking all resource bundles for enum type [" + enumType + "]", LogLevel.INFO.getLevel());
checkAllLocales(imcv);
}
}
public void checkAllLocales(IMessageKeyVerifier mcv) {
String enumClassAsStr = mcv.getEnumTypeAsStr();
String[] localeNameArray = mcv.getLocaleNames();
if (localeNameArray == null || localeNameArray.length == 0) {
- String errMsg = MessageFormat.format(Cal10nConstants.MISSING_LD_ANNOTATION_MESSAGE, enumClassAsStr);
+ String errMsg = MessageFormat.format(CAL10NConstants.MISSING_LOCALE_DATA_ANNOTATION_MESSAGE, enumClassAsStr);
log(errMsg, LogLevel.ERR.getLevel());
throw new BuildException(errMsg);
}
boolean failure = false;
for (String localeName : localeNameArray) {
Locale locale = new Locale(localeName);
List<String> errorList = mcv.typeIsolatedVerify(locale);
if (errorList.size() == 0) {
String resourceBundleName = mcv.getBaseName();
log("SUCCESSFUL verification for resource bundle [" + resourceBundleName + "] for locale [" + locale + "]", LogLevel.INFO.getLevel());
} else {
failure = true;
log("FAILURE during verification of resource bundle for locale ["
+ locale + "] enum class [" + enumClassAsStr + "]", LogLevel.ERR.getLevel());
for (String error : errorList) {
log(error, LogLevel.ERR.getLevel());
}
}
}
if (failure) {
throw new BuildException("FAIL Verification of [" + enumClassAsStr + "] keys.");
}
}
IMessageKeyVerifier getMessageKeyVerifierInstance(String enumClassAsStr) {
String errMsg = "Failed to instantiate MessageKeyVerifier class";
try {
ClassLoader classLoader = ClasspathUtils.getClassLoaderForPath(this.getProject(), this.classpath, "cal10n.VerifyTask");
Class<?> mkvClass = Class.forName(
- Cal10nConstants.MessageKeyVerifier_FQCN, true, classLoader);
+ CAL10NConstants.MessageKeyVerifier_FQCN, true, classLoader);
Constructor<?> mkvCons = mkvClass.getConstructor(String.class);
return (IMessageKeyVerifier) mkvCons.newInstance(enumClassAsStr);
} catch (ClassNotFoundException e) {
throw new BuildException(errMsg, e);
} catch (NoClassDefFoundError e) {
throw new BuildException(errMsg, e);
} catch (Exception e) {
throw new BuildException(errMsg, e);
}
}
public void addClasspath(Path classpath) {
this.classpath = classpath;
}
public void addConfiguredEnumTypes(EnumTypesElement enumTypes) {
this.enumTypes.addAll(enumTypes.getEnumTypes());
}
public void setClasspath(Path classpath) {
this.classpath = classpath;
}
public void setClasspathRef(Reference refId) {
Path cp = new Path(this.getProject());
cp.setRefid(refId);
this.setClasspath(cp);
}
public void setEnumType(String enumType) {
this.enumTypes.add(new StringElement(enumType));
}
}
| false | false | null | null |
diff --git a/core/step-editor/src/main/java/org/aperteworkflow/editor/ui/permission/PrivilegeNameEditor.java b/core/step-editor/src/main/java/org/aperteworkflow/editor/ui/permission/PrivilegeNameEditor.java
index 4507aeb1..1090f271 100644
--- a/core/step-editor/src/main/java/org/aperteworkflow/editor/ui/permission/PrivilegeNameEditor.java
+++ b/core/step-editor/src/main/java/org/aperteworkflow/editor/ui/permission/PrivilegeNameEditor.java
@@ -1,194 +1,210 @@
package org.aperteworkflow.editor.ui.permission;
+import com.liferay.portal.kernel.exception.SystemException;
+import com.liferay.portal.model.Role;
+import com.liferay.portal.model.RoleConstants;
+import com.liferay.portal.service.PortalServiceUtil;
+import com.liferay.portal.service.RoleLocalServiceUtil;
+import com.liferay.portal.util.PortalUtil;
import com.vaadin.ui.*;
import org.aperteworkflow.editor.domain.Permission;
import pl.net.bluesoft.rnd.pt.ext.vaadin.DataHandler;
import pl.net.bluesoft.rnd.util.i18n.I18NSource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
+import java.util.logging.Level;
+import java.util.logging.Logger;
import static pl.net.bluesoft.rnd.pt.ext.stepeditor.Messages.getString;
/**
* Component used to edit role names inside single privilege name
*/
public class PrivilegeNameEditor extends GridLayout implements PermissionWrapperHandler, DataHandler {
+ public static final Logger LOGGER = Logger.getLogger(PrivilegeNameEditor.class.getName());
private PermissionDefinition permissionDefinition;
private PermissionProvider provider;
private Label privilegeDescriptionLabel;
private Label roleNameDescriptionLabel;
private RoleNameComboBox roleNameComboBox;
private Layout roleNameLayout;
public PrivilegeNameEditor(PermissionDefinition permissionDefinition) {
super(2, 3);
setSpacing(true);
this.permissionDefinition = permissionDefinition;
initComponent();
initLayout();
}
private void initComponent() {
I18NSource messages = I18NSource.ThreadUtil.getThreadI18nSource();
privilegeDescriptionLabel = new Label(getDescription(permissionDefinition));
privilegeDescriptionLabel.setContentMode(Label.CONTENT_XHTML);
roleNameDescriptionLabel = new Label(messages.getMessage("permission.editor.assigned.roles"));
roleNameComboBox = new RoleNameComboBox();
roleNameComboBox.setHandler(this);
roleNameLayout = new CssLayout() {
@Override
protected String getCss(Component c) {
if (c instanceof PermissionWrapperBox) {
String basicCss = "float: left; margin: 3px; margin-bottom: 8px; padding: 3px; display: inline; font-weight: bold; border: 2px solid ";
return basicCss + "#287ece; -moz-border-radius: 5px; border-radius: 5px; padding-left: 6px; padding-right: 6px;";
}
return super.getCss(c);
}
};
// roleNameLayout.setMargin(true);
roleNameLayout.setWidth("100%");
}
private String getDescription(PermissionDefinition definition) {
StringBuilder builder = new StringBuilder();
builder.append("<h2>");
builder.append(definition.getKey());
builder.append("</h2>");
if (definition.getDescription() != null && !definition.getDescription().trim().isEmpty()) {
builder.append("<i>");
builder.append(getString(definition.getDescription()));
builder.append("</i>");
}
return builder.toString();
}
private void initLayout() {
setWidth("100%");
setSpacing(true);
addComponent(privilegeDescriptionLabel, 0, 0);
addComponent(roleNameComboBox, 1, 0);
addComponent(roleNameDescriptionLabel, 0, 1, 1, 1);
addComponent(roleNameLayout, 0, 2, 1, 2);
setComponentAlignment(privilegeDescriptionLabel, Alignment.MIDDLE_LEFT);
setComponentAlignment(roleNameComboBox, Alignment.BOTTOM_RIGHT);
setColumnExpandRatio(0, 1);
setColumnExpandRatio(1, 0);
}
@Override
public void addPermissionWrapper(PermissionWrapper permissionWrapper) {
- System.out.println("aPW: " + permissionWrapper);
// ensure the privilege name
permissionWrapper.setPrivilegeName(permissionDefinition.getKey());
PermissionWrapperBox box = getPermissionWrapperBoxByRoleName(permissionWrapper.getRoleName());
if (box == null) {
box = new PermissionWrapperBox(permissionWrapper, this);
roleNameLayout.addComponent(box);
}
if (roleNameComboBox.containsId(permissionWrapper.getRoleName())) {
roleNameComboBox.removeItem(permissionWrapper.getRoleName());
}
Permission permission = new Permission();
permission.setPrivilegeName(permissionWrapper.getPrivilegeName());
permission.setRoleName(permissionWrapper.getRoleName());
provider.addPermission(permission);
}
@Override
public boolean removePermissionWrapper(PermissionWrapper permissionWrapper) {
PermissionWrapperBox box = getPermissionWrapperBoxByRoleName(permissionWrapper.getRoleName());
if (box == null) {
// Nothing to remove
return false;
}
roleNameLayout.removeComponent(box);
roleNameLayout.requestRepaint();
roleNameComboBox.addItem(permissionWrapper.getRoleName());
Permission permission = new Permission();
permission.setPrivilegeName(permissionWrapper.getPrivilegeName());
permission.setRoleName(permissionWrapper.getRoleName());
provider.removePermission(permission);
return true;
}
private PermissionWrapperBox getPermissionWrapperBoxByRoleName(String roleName) {
Iterator<Component> it = roleNameLayout.getComponentIterator();
while (it.hasNext()) {
Component c = it.next();
if ((c instanceof PermissionWrapperBox)) {
PermissionWrapperBox box = (PermissionWrapperBox) c;
if (roleName.equals(box.getPermissionWrapper().getRoleName())) {
return box;
}
}
}
return null;
}
@Override
public void loadData() {
roleNameComboBox.removeAllItems();
- // TODO get roles from liferay
-
+ roleNameComboBox.addItem(".*");
+ try {
+ List<Role> roles = RoleLocalServiceUtil.getRoles(PortalUtil.getDefaultCompanyId());
+ for (Role r : roles) {
+ if (r.getType() == RoleConstants.TYPE_REGULAR)
+ roleNameComboBox.addItem(r.getName());
+ }
+ } catch (SystemException e) {
+ LOGGER.log(Level.SEVERE, e.getMessage(), e);
+ }
roleNameLayout.removeAllComponents();
if (provider.getPermissions() != null) {
for (Permission permission : provider.getPermissions()) {
addPermissionWrapper(new PermissionWrapper(permission));
}
}
}
@Override
public void saveData() {
}
@Override
public Collection<String> validateData() {
return null;
}
public PermissionProvider getProvider() {
return provider;
}
public void setProvider(PermissionProvider provider) {
this.provider = provider;
}
public PermissionDefinition getPermissionDefinition() {
return permissionDefinition;
}
public List<Permission> getPermissions() {
List<Permission> list = new ArrayList<Permission>();
Iterator<Component> it = roleNameLayout.getComponentIterator();
while (it.hasNext()) {
Component c = it.next();
if ((c instanceof PermissionWrapperBox)) {
PermissionWrapperBox box = (PermissionWrapperBox) c;
list.add(box.getPermissionWrapper().toPermission());
}
}
return list;
}
}
| false | false | null | null |
diff --git a/zendserver-sdk-java/org.zend.sdk/sdklib/org/zend/sdklib/ZendProject.java b/zendserver-sdk-java/org.zend.sdk/sdklib/org/zend/sdklib/ZendProject.java
index 2a1aaa82..45aa513e 100644
--- a/zendserver-sdk-java/org.zend.sdk/sdklib/org/zend/sdklib/ZendProject.java
+++ b/zendserver-sdk-java/org.zend.sdk/sdklib/org/zend/sdklib/ZendProject.java
@@ -1,52 +1,54 @@
/*******************************************************************************
* Copyright (c) May 16, 2011 Zend Technologies Ltd.
* 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.zend.sdklib;
import java.io.File;
import java.io.IOException;
import org.zend.sdklib.internal.library.AbstractLibrary;
import org.zend.sdklib.internal.project.template.TemplateWriter;
/**
* Sample library class
*
* @author Roy, 2011
*
*/
public class ZendProject extends AbstractLibrary {
protected String name;
protected boolean withScripts;
protected String destination;
public ZendProject(String name, boolean withScripts, String destination) {
this.name = name;
this.withScripts = withScripts;
this.destination = destination;
}
/**
* Writes project to file system.
*
* @return true on success, false otherwise.
*/
public boolean create() {
TemplateWriter tw = new TemplateWriter();
+ File dest = destination == null ? new File(".") : new File(destination);
+
try {
- tw.writeTemplate(name, withScripts, new File(destination));
+ tw.writeTemplate(name, withScripts, dest);
} catch (IOException e) {
log.error(e.getMessage());
return false;
}
return true;
}
}
diff --git a/zendserver-sdk-java/org.zend.sdk/sdklib/org/zend/sdklib/internal/project/template/TemplateWriter.java b/zendserver-sdk-java/org.zend.sdk/sdklib/org/zend/sdklib/internal/project/template/TemplateWriter.java
index 8031fdf9..edd84565 100644
--- a/zendserver-sdk-java/org.zend.sdk/sdklib/org/zend/sdklib/internal/project/template/TemplateWriter.java
+++ b/zendserver-sdk-java/org.zend.sdk/sdklib/org/zend/sdklib/internal/project/template/TemplateWriter.java
@@ -1,92 +1,103 @@
package org.zend.sdklib.internal.project.template;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.net.URL;
public class TemplateWriter {
public static final String DESCRIPTOR = "descriptor.xml";
public static String[] resources = {
"public/index.html",
};
public static String[] scripts = {
"scripts/post_activate.php",
"scripts/post_deactivate.php",
"scripts/post_stage.php",
"scripts/post_unstage.php",
"scripts/pre_activate.php",
"scripts/pre_deactivate.php",
"scripts/pre_stage.php",
"scripts/pre_unstage.php" };
public void writeTemplate(String name, boolean withScripts, File destination) throws IOException {
writeDescriptor(name, withScripts, new FileWriter(new File(destination, DESCRIPTOR)));
for (int i = 0; i < resources.length; i++) {
writeStaticResource(resources[i], destination);
}
if (withScripts) {
for (int i = 0; i < scripts.length; i++) {
writeStaticResource(scripts[i], destination);
}
}
}
private void writeDescriptor(String name, boolean withScripts, Writer out) throws IOException {
out.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
out.append("<package version=\"1.4.11\" xmlns=\"http://www.zend.com/server/deployment-descriptor/1.0\" xmlns:xsi=\">http://www.w3.org/2001/XMLSchema-instance\">\n");
out.append(" <name>").append(xmlEscape(name)).append("</name>\n");
out.append(" <summary>short description</summary>\n");
out.append(" <description>long description</description>\n");
out.append(" <version>\n");
out.append(" <release>1.0.0.0/release>\n");
out.append(" </version>\n");
out.append(" <eula></eula>\n");
out.append(" <docroot></docroot>\n");
if (withScripts) {
out.append(" <scriptsdir>scripts</scriptsdir>\n");
}
out.append("</package>\n");
+ out.close();
}
private CharSequence xmlEscape(String name) {
for (int i = 0; i < name.length(); i++) {
char c = name.charAt(i);
if (c == '&' || c== '<' || c == '>') {
return "<![CDATA[" + name.replaceAll("]]>", "]]>]]><![CDATA[") + "]]>";
}
}
return name;
}
private void writeStaticResource(String resourceName, File destination) throws IOException {
URL url = getClass().getResource(resourceName);
File destFile = new File(destination, resourceName);
File dir = destFile.getParentFile();
if (! dir.exists()) {
dir.mkdir();
}
FileOutputStream out = new FileOutputStream(destFile);
- InputStream is = url.openStream();
- byte[] buf = new byte[4098];
- int c;
- while ((c = is.read(buf)) > 0) {
- out.write(buf, 0, c);
+ InputStream is = null;
+ try {
+ is = url.openStream();
+ byte[] buf = new byte[4098];
+ int c;
+ while ((c = is.read(buf)) > 0) {
+ out.write(buf, 0, c);
+ }
+ } finally {
+ if (is != null) {
+ is.close();
+ }
+ if (out != null) {
+ out.close();
+ }
}
}
public static void main(String[] args) throws IOException {
TemplateWriter tw = new TemplateWriter();
tw.writeStaticResource(resources[0], new File("."));
}
}
| false | false | null | null |
diff --git a/core/plugins/org.eclipse.dltk.ui/src/org/eclipse/dltk/ui/text/completion/CompletionProposalLabelProvider.java b/core/plugins/org.eclipse.dltk.ui/src/org/eclipse/dltk/ui/text/completion/CompletionProposalLabelProvider.java
index 91c0c26f8..879e12578 100644
--- a/core/plugins/org.eclipse.dltk.ui/src/org/eclipse/dltk/ui/text/completion/CompletionProposalLabelProvider.java
+++ b/core/plugins/org.eclipse.dltk.ui/src/org/eclipse/dltk/ui/text/completion/CompletionProposalLabelProvider.java
@@ -1,438 +1,438 @@
/*******************************************************************************
* Copyright (c) 2005, 2007 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
*
*******************************************************************************/
package org.eclipse.dltk.ui.text.completion;
import org.eclipse.core.runtime.Assert;
import org.eclipse.dltk.core.CompletionContext;
import org.eclipse.dltk.core.CompletionProposal;
import org.eclipse.dltk.core.Flags;
import org.eclipse.dltk.core.IField;
import org.eclipse.dltk.core.ILocalVariable;
import org.eclipse.dltk.core.IMethod;
import org.eclipse.dltk.core.IModelElement;
import org.eclipse.dltk.core.IType;
import org.eclipse.dltk.core.ModelException;
import org.eclipse.dltk.ui.DLTKPluginImages;
import org.eclipse.dltk.ui.ScriptElementImageDescriptor;
import org.eclipse.dltk.ui.ScriptElementImageProvider;
import org.eclipse.dltk.ui.ScriptElementLabels;
import org.eclipse.jface.resource.ImageDescriptor;
/**
* Provides labels forscriptcontent assist proposals. The functionality is
* similar to the one provided by {@link org.eclipse.dltk.ui.ModelElementLabels}
* , but based on signatures and {@link CompletionProposal}s.
*
*/
public class CompletionProposalLabelProvider {
/**
* The completion context.
*/
// private CompletionContext fContext;
/**
* Creates a new label provider.
*/
public CompletionProposalLabelProvider() {
}
/**
* Creates and returns a parameter list of the given method proposal
* suitable for display. The list does not include parentheses. The lower
* bound of parameter types is returned.
* <p>
* Examples:
*
* <pre>
* "void method(int i, Strings)" -> "int i, String s"
* "? extends Number method(java.lang.String s, ? super Number n)" -> "String s, Number n"
* </pre>
*
* </p>
*
* @param methodProposal
* the method proposal to create the parameter list for. Must be
* of kind {@link CompletionProposal#METHOD_REF}.
* @return the list of comma-separated parameters suitable for display
*/
public String createParameterList(CompletionProposal methodProposal) {
Assert.isTrue(methodProposal.getKind() == CompletionProposal.METHOD_REF);
return appendParameterList(new StringBuffer(), methodProposal)
.toString();
}
/**
* Appends the parameter list to <code>buffer</code>. See
* <code>createUnboundedParameterList</code> for details.
*
* @param buffer
* the buffer to append to
* @param methodProposal
* the method proposal
* @return the modified <code>buffer</code>
*/
protected StringBuffer appendParameterList(StringBuffer buffer,
CompletionProposal methodProposal) {
String[] parameterNames = methodProposal.findParameterNames(null);
String[] parameterTypes = null;
return appendParameterSignature(buffer, parameterTypes, parameterNames);
}
/**
* Creates a display string of a parameter list (without the parentheses)
* for the given parameter types and names.
*
* @param parameterTypes
* the parameter types
* @param parameterNames
* the parameter names
* @return the display string of the parameter list defined by the passed
* arguments
*/
protected StringBuffer appendParameterSignature(StringBuffer buffer,
String[] parameterTypes, String[] parameterNames) {
if (parameterNames != null) {
for (int i = 0; i < parameterNames.length; i++) {
if (i > 0) {
buffer.append(',');
buffer.append(' ');
}
buffer.append(parameterNames[i]);
}
}
return buffer;
}
/**
* Creates a display label for the given method proposal. The display label
* consists of:
* <ul>
* <li>the method name</li>
* <li>the parameter list (see
* {@link #createParameterList(CompletionProposal)})</li>
* <li>the raw simple name of the declaring type</li>
* </ul>
* <p>
* Examples: For the <code>get(int)</code> method of a variable of type
* <code>List<? extends Number></code>, the following display name is
* returned: <code>get(int index) Number - List</code>.<br>
* For the <code>add(E)</code> method of a variable of type returned:
* <code>add(Number o) void - List</code>.<br>
* <code>List<? super Number></code>, the following display name is
* </p>
*
* @param methodProposal
* the method proposal to display
* @return the display label for the given method proposal
*/
protected String createMethodProposalLabel(CompletionProposal methodProposal) {
StringBuffer buffer = new StringBuffer();
// method name
buffer.append(methodProposal.getName());
// parameters
buffer.append('(');
appendParameterList(buffer, methodProposal);
buffer.append(')');
IModelElement element = methodProposal.getModelElement();
if (element != null && element.getElementType() == IModelElement.METHOD
&& element.exists()) {
final IMethod method = (IMethod) element;
try {
if (!method.isConstructor()) {
String type = method.getType();
if (type != null) {
buffer.append(": ").append(type);
}
IType declaringType = method.getDeclaringType();
if (declaringType != null) {
buffer.append(" - ").append(
declaringType.getElementName());
}
}
} catch (ModelException e) {
// ignore
}
}
return buffer.toString();
}
protected String createOverrideMethodProposalLabel(
CompletionProposal methodProposal) {
StringBuffer nameBuffer = new StringBuffer();
// method name
nameBuffer.append(methodProposal.getName());
// parameters
nameBuffer.append('(');
appendParameterList(nameBuffer, methodProposal);
nameBuffer.append(") "); //$NON-NLS-1$
return nameBuffer.toString();
}
/**
* Creates a display label for a given type proposal. The display label
* consists of:
* <ul>
* <li>the simple type name (erased when the context is in javadoc)</li>
* <li>the package name</li>
* </ul>
* <p>
* Examples: A proposal for the generic type
* <code>java.util.List<E></code>, the display label is:
* <code>List<E> - java.util</code>.
* </p>
*
* @param typeProposal
* the method proposal to display
* @return the display label for the given type proposal
*/
public String createTypeProposalLabel(CompletionProposal typeProposal) {
return createTypeProposalLabel(typeProposal.getName());
}
protected String createTypeProposalLabel(String fullName) {
int qIndex = findSimpleNameStart(fullName);
StringBuffer buf = new StringBuffer();
- buf.append(fullName, qIndex, fullName.length() - qIndex);
+ buf.append(fullName, qIndex, fullName.length());
if (qIndex > 0) {
buf.append(ScriptElementLabels.CONCAT_STRING);
buf.append(fullName, 0, qIndex - 1);
}
return buf.toString();
}
private int findSimpleNameStart(String array) {
int lastDot = 0;
for (int i = 0, len = array.length(); i < len; i++) {
char ch = array.charAt(i);
if (ch == '<') {
return lastDot;
} else if (ch == '.') {
lastDot = i + 1;
}
}
return lastDot;
}
protected String createSimpleLabelWithType(CompletionProposal proposal) {
IModelElement element = proposal.getModelElement();
if (element != null
&& element.getElementType() == IModelElement.LOCAL_VARIABLE
&& element.exists()) {
final ILocalVariable var = (ILocalVariable) element;
String type = var.getType();
if (type != null) {
return proposal.getName() + ": " + type;
}
}
return proposal.getName();
}
protected String createFieldProposalLabel(CompletionProposal proposal) {
IModelElement element = proposal.getModelElement();
if (element != null && element.getElementType() == IModelElement.FIELD
&& element.exists()) {
final IField field = (IField) element;
try {
String type = field.getType();
if (type != null) {
return proposal.getName() + ": " + type;
}
} catch (ModelException e) {
// ignore
}
}
return proposal.getName();
}
public String createSimpleLabel(CompletionProposal proposal) {
return String.valueOf(proposal.getName());
}
public String createKeywordLabel(CompletionProposal proposal) {
return String.valueOf(proposal.getName());
}
/**
* Creates the display label for a given <code>CompletionProposal</code>.
*
* @param proposal
* the completion proposal to create the display label for
* @return the display label for <code>proposal</code>
*/
public String createLabel(CompletionProposal proposal) {
switch (proposal.getKind()) {
case CompletionProposal.METHOD_NAME_REFERENCE:
case CompletionProposal.METHOD_REF:
case CompletionProposal.POTENTIAL_METHOD_DECLARATION:
return createMethodProposalLabel(proposal);
case CompletionProposal.METHOD_DECLARATION:
return createOverrideMethodProposalLabel(proposal);
case CompletionProposal.TYPE_REF:
return createTypeProposalLabel(proposal);
// case CompletionProposal.JAVADOC_TYPE_REF:
// return createJavadocTypeProposalLabel(proposal);
// case CompletionProposal.JAVADOC_FIELD_REF:
// case CompletionProposal.JAVADOC_VALUE_REF:
// case CompletionProposal.JAVADOC_BLOCK_TAG:
// case CompletionProposal.JAVADOC_INLINE_TAG:
// case CompletionProposal.JAVADOC_PARAM_REF:
// return createJavadocSimpleProposalLabel(proposal);
// case CompletionProposal.JAVADOC_METHOD_REF:
// return createJavadocMethodProposalLabel(proposal);
case CompletionProposal.FIELD_REF:
return createFieldProposalLabel(proposal);
case CompletionProposal.LOCAL_VARIABLE_REF:
case CompletionProposal.VARIABLE_DECLARATION:
return createSimpleLabelWithType(proposal);
case CompletionProposal.KEYWORD:
return createKeywordLabel(proposal);
case CompletionProposal.PACKAGE_REF:
case CompletionProposal.LABEL_REF:
return createSimpleLabel(proposal);
default:
Assert.isTrue(false);
return null;
}
}
/**
* Creates and returns a decorated image descriptor for a completion
* proposal.
*
* @param proposal
* the proposal for which to create an image descriptor
* @return the created image descriptor, or <code>null</code> if no image is
* available
*/
public ImageDescriptor createImageDescriptor(CompletionProposal proposal) {
ImageDescriptor descriptor;
switch (proposal.getKind()) {
case CompletionProposal.METHOD_DECLARATION:
case CompletionProposal.METHOD_NAME_REFERENCE:
case CompletionProposal.METHOD_REF:
case CompletionProposal.POTENTIAL_METHOD_DECLARATION:
return createMethodImageDescriptor(proposal);
case CompletionProposal.TYPE_REF:
descriptor = DLTKPluginImages.DESC_OBJS_CLASSALT;
break;
case CompletionProposal.FIELD_REF:
descriptor = DLTKPluginImages.DESC_FIELD_DEFAULT;
break;
case CompletionProposal.LOCAL_VARIABLE_REF:
case CompletionProposal.VARIABLE_DECLARATION:
descriptor = DLTKPluginImages.DESC_OBJS_LOCAL_VARIABLE;
break;
case CompletionProposal.PACKAGE_REF:
descriptor = DLTKPluginImages.DESC_OBJS_PACKAGE;
break;
case CompletionProposal.KEYWORD:
descriptor = DLTKPluginImages.DESC_OBJS_KEYWORD;
break;
case CompletionProposal.LABEL_REF:
descriptor = null;
break;
// case CompletionProposal.JAVADOC_METHOD_REF:
// case CompletionProposal.JAVADOC_TYPE_REF:
// case CompletionProposal.JAVADOC_FIELD_REF:
// case CompletionProposal.JAVADOC_VALUE_REF:
// case CompletionProposal.JAVADOC_BLOCK_TAG:
// case CompletionProposal.JAVADOC_INLINE_TAG:
// case CompletionProposal.JAVADOC_PARAM_REF:
// descriptor = JavaPluginImages.DESC_OBJS_JAVADOCTAG;
// break;
default:
descriptor = null;
Assert.isTrue(false);
}
if (descriptor == null)
return null;
return decorateImageDescriptor(descriptor, proposal);
}
public ImageDescriptor createMethodImageDescriptor(
CompletionProposal proposal) {
return decorateImageDescriptor(
ScriptElementImageProvider.getMethodImageDescriptor(proposal
.getFlags()), proposal);
}
public ImageDescriptor createTypeImageDescriptor(
CompletionProposal proposal) {
// boolean isInterfaceOrAnnotation= Flags.isInterface(flags) ||
// Flags.isAnnotation(flags);
return decorateImageDescriptor(
ScriptElementImageProvider.getTypeImageDescriptor(
proposal.getFlags(), false), proposal);
}
protected ImageDescriptor createFieldImageDescriptor(
CompletionProposal proposal) {
return decorateImageDescriptor(
ScriptElementImageProvider.getFieldImageDescriptor(proposal
.getFlags()), proposal);
}
protected ImageDescriptor createLocalImageDescriptor(
CompletionProposal proposal) {
return decorateImageDescriptor(
DLTKPluginImages.DESC_OBJS_LOCAL_VARIABLE, proposal);
}
protected ImageDescriptor createPackageImageDescriptor(
CompletionProposal proposal) {
return decorateImageDescriptor(DLTKPluginImages.DESC_OBJS_PACKAGE,
proposal);
}
/**
* Returns a version of <code>descriptor</code> decorated according to the
* passed <code>modifier</code> flags.
*
* @param descriptor
* the image descriptor to decorate
* @param proposal
* the proposal
* @return an image descriptor for a method proposal
* @see Flags
*/
protected ImageDescriptor decorateImageDescriptor(
ImageDescriptor descriptor, CompletionProposal proposal) {
int adornmentFlags = ScriptElementImageProvider.computeAdornmentFlags(
proposal.getModelElement(),
ScriptElementImageProvider.SMALL_ICONS
| ScriptElementImageProvider.OVERLAY_ICONS);
if (proposal.isConstructor()) {
adornmentFlags |= ScriptElementImageDescriptor.CONSTRUCTOR;
}
return new ScriptElementImageDescriptor(descriptor, adornmentFlags,
ScriptElementImageProvider.SMALL_SIZE);
}
/**
* Sets the completion context.
*
* @param context
* the completion context
*
*/
void setContext(CompletionContext context) {
// fContext = context;
}
}
| true | false | null | null |
diff --git a/org.eclipse.gmf.tests.runtime.diagram.ui/src/org/eclipse/gmf/tests/runtime/diagram/ui/logic/LogicTransientViewsTests.java b/org.eclipse.gmf.tests.runtime.diagram.ui/src/org/eclipse/gmf/tests/runtime/diagram/ui/logic/LogicTransientViewsTests.java
index 8d3b7e0d..ca86f5f5 100644
--- a/org.eclipse.gmf.tests.runtime.diagram.ui/src/org/eclipse/gmf/tests/runtime/diagram/ui/logic/LogicTransientViewsTests.java
+++ b/org.eclipse.gmf.tests.runtime.diagram.ui/src/org/eclipse/gmf/tests/runtime/diagram/ui/logic/LogicTransientViewsTests.java
@@ -1,404 +1,401 @@
/******************************************************************************
* Copyright (c) 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
****************************************************************************/
package org.eclipse.gmf.tests.runtime.diagram.ui.logic;
/**
* Tests the Transient Views functionality
* @author mmostafa
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.operations.OperationHistoryFactory;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.draw2d.geometry.Rectangle;
-import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.emf.workspace.AbstractEMFOperation;
import org.eclipse.gef.ConnectionEditPart;
-import org.eclipse.gmf.examples.runtime.diagram.logic.internal.editparts.CircuitEditPart;
import org.eclipse.gmf.examples.runtime.diagram.logic.model.Circuit;
import org.eclipse.gmf.examples.runtime.diagram.logic.model.LED;
import org.eclipse.gmf.examples.runtime.diagram.logic.model.Terminal;
import org.eclipse.gmf.runtime.common.core.command.ICommand;
import org.eclipse.gmf.runtime.diagram.core.util.ViewUtil;
import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramGraphicalViewer;
import org.eclipse.gmf.runtime.emf.type.core.ElementTypeRegistry;
import org.eclipse.gmf.runtime.emf.type.core.IElementType;
import org.eclipse.gmf.runtime.emf.type.core.requests.CreateRelationshipRequest;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.gmf.tests.runtime.diagram.ui.AbstractTestBase;
public class LogicTransientViewsTests extends AbstractTestBase{
/**
* Defines the statechart diagram test suite.
*
* @return the test suite.
*/
public static Test suite() {
TestSuite s = new TestSuite(LogicTransientViewsTests.class);
return s;
}
/** Create an instance. */
public LogicTransientViewsTests() {
super("Transient View Test Suite");//$NON-NLS-1$
}
/** installs the composite state test fixture. */
protected void setTestFixture() {
testFixture = new CanonicalTestFixture();
}
/** Return <code>(CanonicalTestFixture)getTestFixture();</code> */
protected CanonicalTestFixture getCanonicalTestFixture() {
return (CanonicalTestFixture)getTestFixture();
}
public void testTransientWiresCreation_AcrossTransientLeds(){
try {
println("testTransientWiresCreation_AcrossTransientLeds() starting ...");//$NON-NLS-1$
CanonicalTestFixture _testFixture = getCanonicalTestFixture();
IGraphicalEditPart logicCompartment = _testFixture.getCanonicalCompartment(0);
LED led1 = _testFixture.createLED(ViewUtil.resolveSemanticElement(logicCompartment.getNotationView()));
LED led2 = _testFixture.createLED(ViewUtil.resolveSemanticElement(logicCompartment.getNotationView()));
Terminal term1 = (Terminal)led1.getOutputTerminals().get(0);
Terminal term2 = (Terminal)led2.getInputTerminals().get(0);
IElementType typeWire = ElementTypeRegistry.getInstance().getType("logic.wire"); //$NON-NLS-1$
IElementType typeCircuit = ElementTypeRegistry.getInstance().getType("logic.circuit"); //$NON-NLS-1$
CreateRelationshipRequest crr = new CreateRelationshipRequest(getTestFixture().getEditingDomain(), term1, term2, typeWire);
ICommand createWire = typeCircuit.getEditHelper().getEditCommand(crr);
_testFixture.execute(createWire);
flushEventQueue();
List connectorEPs = getDiagramEditPart().getConnections();
assertEquals( "Unexpected Wire count.", 1, connectorEPs.size()); //$NON-NLS-1$
final ConnectionEditPart ep = (ConnectionEditPart)connectorEPs.get(0);
assertTransient((View)ep.getSource().getModel());
assertTransient((View)ep.getTarget().getModel());
assertTransient((View)ep.getModel());
final TransactionalEditingDomain editingDomain = ((IGraphicalEditPart)ep).getEditingDomain();
AbstractEMFOperation operation = new AbstractEMFOperation(
editingDomain, "") { //$NON-NLS-1$
protected IStatus doExecute(IProgressMonitor monitor,
IAdaptable info)
throws ExecutionException {
((View)ep.getModel()).setVisible(false);
return Status.OK_STATUS;
};
};
try {
OperationHistoryFactory.getOperationHistory().execute(operation,
new NullProgressMonitor(), null);
} catch (ExecutionException e) {
e.printStackTrace();
assertFalse(false);
}
//
// editingDomain.runInUndoInterval(new Runnable() {
// public void run() {
// try {
// editingDomain.runAsWrite(new MRunnable() {
// public Object run() {
// ((View)ep.getModel()).setVisible(false);
// return null;
// }});
// } catch (MSLActionAbandonedException e) {
// // do nothing
// }
// }});
assertPersisted((View)ep.getSource().getModel());
assertPersisted((View)ep.getTarget().getModel());
assertPersisted((View)ep.getModel());
}
finally {
println("testTransientWiresCreation_AcrossTransientLeds() complete.");//$NON-NLS-1$
}
}
private GraphicalEditPart _editPartForSemanticElement(GraphicalEditPart container, Object element){
List children = container.getChildren();
for (Iterator iter = children.iterator(); iter.hasNext();) {
GraphicalEditPart ep = (GraphicalEditPart) iter.next();
if (ep.getNotationView().getElement()==element){
return ep;
}else {
ep = _editPartForSemanticElement(ep,element);
if (ep !=null)
return ep;
}
}
return null;
}
public void testTransientWiresCreation_AcrossPersistedLeds(){
try {
println("testTransientWiresCreation_AcrossPersistedLeds() starting ...");//$NON-NLS-1$
CanonicalTestFixture _testFixture = getCanonicalTestFixture();
IGraphicalEditPart logicCompartment = _testFixture.getCanonicalCompartment(0);
LED led1 = _testFixture.createLED(ViewUtil.resolveSemanticElement(logicCompartment.getNotationView()));
LED led2 = _testFixture.createLED(ViewUtil.resolveSemanticElement(logicCompartment.getNotationView()));
GraphicalEditPart ledEditPart = (GraphicalEditPart)getDiagramEditPart().getChildren().get(0);
Terminal term1 = (Terminal)led1.getOutputTerminals().get(0);
Terminal term2 = (Terminal)led2.getInputTerminals().get(0);
flushEventQueue();
final GraphicalEditPart ep1 = _editPartForSemanticElement(ledEditPart,term1);
// force the led to be persisted
final TransactionalEditingDomain editingDomain = ledEditPart.getEditingDomain();
AbstractEMFOperation operation = new AbstractEMFOperation(
editingDomain, "") { //$NON-NLS-1$
protected IStatus doExecute(IProgressMonitor monitor,
IAdaptable info)
throws ExecutionException {
((View)((View)ep1.getModel()).eContainer()).persistChildren();
return Status.OK_STATUS;
};
};
try {
getDiagramEditPart().getDiagramEditDomain().getActionManager()
.getOperationHistory().execute(operation,
new NullProgressMonitor(), null);
} catch (ExecutionException e) {
e.printStackTrace();
assertFalse(false);
}
assertPersisted((View)ep1.getModel());
IElementType typeWire = ElementTypeRegistry.getInstance().getType("logic.wire"); //$NON-NLS-1$
IElementType typeCircuit = ElementTypeRegistry.getInstance().getType("logic.circuit"); //$NON-NLS-1$
CreateRelationshipRequest crr = new CreateRelationshipRequest(editingDomain, term1, term2, typeWire);
ICommand createWire = typeCircuit.getEditHelper().getEditCommand(crr);
_testFixture.execute(createWire);
flushEventQueue();
List connectorEPs = getDiagramEditPart().getConnections();
assertEquals( "Unexpected Wire count.", 1, connectorEPs.size()); //$NON-NLS-1$
final ConnectionEditPart ep = (ConnectionEditPart)connectorEPs.get(0);
assertTransient((View)ep.getModel());
}
finally {
println("testTransientWiresCreation_AcrossPersistedLeds() complete.");//$NON-NLS-1$
}
}
public void testTransientLEDsCreation(){
try {
println("testTransientLEDsCreation() starting ...");//$NON-NLS-1$
CanonicalTestFixture _testFixture = getCanonicalTestFixture();
IGraphicalEditPart logicCompartment = _testFixture.getCanonicalCompartment(0);
List properties = new ArrayList();
int size = logicCompartment.getChildren().size();
int count = 5;
for ( int i = 0; i < count; i++ ) {
properties.add( _testFixture.createLED(ViewUtil.resolveSemanticElement(logicCompartment.getNotationView())));
size++;
assertEquals( "Unexpected LED count.", size, logicCompartment.getChildren().size() );//$NON-NLS-1$
}
assertTransient(logicCompartment.getChildren());
Rectangle rect = new Rectangle(logicCompartment.getFigure().getBounds());
logicCompartment.getFigure().translateToAbsolute(rect);
IElementType typeLED = ElementTypeRegistry.getInstance().getType("logic.led"); //$NON-NLS-1$
getCanonicalTestFixture().createShapeUsingTool(typeLED, rect.getCenter(), logicCompartment);
assertPersisted(logicCompartment.getChildren());
LED led = _testFixture.createLED(ViewUtil.resolveSemanticElement(logicCompartment.getNotationView()));
List children = logicCompartment.getChildren();
for (Iterator iter = children.iterator(); iter.hasNext();) {
GraphicalEditPart element = (GraphicalEditPart) iter.next();
View view = element.getNotationView();
if (view !=null){
Object _led = view.getElement();
if (_led == led){
assertTransient(view);
} else {
assertPersisted(view);
}
}
}
}
finally {
println("testTransientLEDsCreation() complete.");//$NON-NLS-1$
}
}
public void testTransientCircuitsCreation(){
try {
println("testTransientCircuitsCreation() starting ...");//$NON-NLS-1$
CanonicalTestFixture _testFixture = getCanonicalTestFixture();
IGraphicalEditPart logicCompartment = _testFixture.getCanonicalCompartment(0);
List properties = new ArrayList();
int size = logicCompartment.getChildren().size();
int count = 5;
for ( int i = 0; i < count; i++ ) {
properties.add( _testFixture.createCircuit(ViewUtil.resolveSemanticElement(logicCompartment.getNotationView())));
size++;
assertEquals( "Unexpected Circuit count.", size, logicCompartment.getChildren().size() );//$NON-NLS-1$
}
assertTransient(logicCompartment.getChildren());
Rectangle rect = new Rectangle(logicCompartment.getFigure().getBounds());
logicCompartment.getFigure().translateToAbsolute(rect);
IElementType typeCircuit = ElementTypeRegistry.getInstance().getType("logic.circuit"); //$NON-NLS-1$
getCanonicalTestFixture().createShapeUsingTool(typeCircuit, rect.getCenter(), logicCompartment);
assertPersisted(logicCompartment.getChildren());
Circuit circuit = _testFixture.createCircuit(ViewUtil.resolveSemanticElement(logicCompartment.getNotationView()));
List children = logicCompartment.getChildren();
for (Iterator iter = children.iterator(); iter.hasNext();) {
GraphicalEditPart element = (GraphicalEditPart) iter.next();
View view = element.getNotationView();
if (view !=null){
Object _circuit = view.getElement();
if (_circuit == circuit){
assertTransient(view);
assertTransient(element.getChildren());
} else {
assertPersisted(view);
}
}
}
}
finally {
println("testTransientCircuitsCreation() complete.");//$NON-NLS-1$
}
}
// /**
// * Test that moving a transient LED will cause it to be persisted.
// */
// public void testPersistedAfterMove(){
// try {
// println("test_testPersistedAfterMove() starting ...");//$NON-NLS-1$
// CanonicalTestFixture _testFixture = getCanonicalTestFixture();
// IGraphicalEditPart logicCompartment = _testFixture.getCanonicalCompartment(0);
//
// _testFixture.createLED(ViewUtil.resolveSemanticElement(logicCompartment.getNotationView()));
// assertEquals( "Unexpected LED count.", 1, logicCompartment.getChildren().size() );//$NON-NLS-1$
//
// // Starts out as being transient.
// assertTransient(logicCompartment.getChildren());
//
// // Move LED.
// IGraphicalEditPart ledEP = (IGraphicalEditPart) logicCompartment.getChildren().get(0);
// Point oldLocation = ledEP.getFigure().getBounds().getLocation();
// ChangeBoundsRequest request = new ChangeBoundsRequest(
// RequestConstants.REQ_MOVE);
// request.setEditParts(ledEP);
// request.setMoveDelta(new Point(100, 100));
// Command cmd = ledEP.getCommand(request);
// cmd.execute();
// flushEventQueue();
// assertFalse(oldLocation.equals(ledEP.getFigure().getBounds().getLocation()));
//
// // Should be persisted after a move.
// assertPersisted(logicCompartment.getChildren());
// }
// finally {
// println("test_testPersistedAfterMove() complete.");//$NON-NLS-1$
// }
// }
private void assertPersisted(View view) {
if (view != null){
EStructuralFeature feature = view.eContainingFeature();
if (feature!=null){
assertFalse("Expected a Persisted View", feature.isTransient()); //$NON-NLS-1$
}
}
}
private void assertTransient(View view) {
if (view != null){
EStructuralFeature feature = view.eContainingFeature();
if (feature!=null){
assertTrue("Expected a Transient View", feature.isTransient()); //$NON-NLS-1$
}
}
}
private void assertPersisted(List children) {
for (Iterator iter = children.iterator(); iter.hasNext();) {
GraphicalEditPart element = (GraphicalEditPart) iter.next();
View view = element.getNotationView();
if (view != null){
EStructuralFeature feature = view.eContainingFeature();
if (feature!=null){
assertFalse("Expected a Persisted View", feature.isTransient()); //$NON-NLS-1$
}
}
}
}
private void assertTransient(List children) {
for (Iterator iter = children.iterator(); iter.hasNext();) {
GraphicalEditPart element = (GraphicalEditPart) iter.next();
View view = element.getNotationView();
if (view != null){
EStructuralFeature feature = view.eContainingFeature();
if (feature!=null){
assertTrue("Expected a Transient View", feature.isTransient()); //$NON-NLS-1$
}
}
}
}
}
| false | false | null | null |
diff --git a/src/main/java/be/Balor/Manager/Permissions/Plugins/PermissionsEx.java b/src/main/java/be/Balor/Manager/Permissions/Plugins/PermissionsEx.java
index 925eb499..49061b1f 100644
--- a/src/main/java/be/Balor/Manager/Permissions/Plugins/PermissionsEx.java
+++ b/src/main/java/be/Balor/Manager/Permissions/Plugins/PermissionsEx.java
@@ -1,99 +1,112 @@
/************************************************************************
* This file is part of AdminCmd.
*
* AdminCmd 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.
*
* AdminCmd 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 AdminCmd. If not, see <http://www.gnu.org/licenses/>.
************************************************************************/
package be.Balor.Manager.Permissions.Plugins;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permission;
import ru.tehkode.permissions.PermissionGroup;
import ru.tehkode.permissions.PermissionManager;
import be.Balor.Manager.Permissions.AbstractPermission;
+import be.Balor.Tools.Utils;
/**
* @author Balor (aka Antoine Aflalo)
*
*/
public class PermissionsEx extends AbstractPermission {
private PermissionManager PEX;
/**
*
*/
public PermissionsEx(PermissionManager PEX) {
this.PEX = PEX;
haveInfoNode = true;
}
/*
* (non-Javadoc)
*
* @see
* be.Balor.Manager.Permissions.AbstractPermission#hasPerm(org.bukkit.command
* .CommandSender, java.lang.String, boolean)
*/
@Override
public boolean hasPerm(CommandSender player, String perm, boolean errorMsg) {
if (!(player instanceof Player))
return true;
- return PEX.has((Player) player, perm);
+ if (PEX.has((Player) player, perm))
+ return true;
+ else {
+ if (errorMsg)
+ Utils.sI18n(player, "errorNotPerm", "p", perm);
+ return false;
+ }
}
/*
* (non-Javadoc)
*
* @see
* be.Balor.Manager.Permissions.AbstractPermission#hasPerm(org.bukkit.command
* .CommandSender, org.bukkit.permissions.Permission, boolean)
*/
@Override
public boolean hasPerm(CommandSender player, Permission perm, boolean errorMsg) {
if (!(player instanceof Player))
return true;
- return PEX.has((Player) player, perm.getName());
+ if (PEX.has((Player) player, perm.getName()))
+ return true;
+ else {
+ if (errorMsg)
+ Utils.sI18n(player, "errorNotPerm", "p", perm.getName());
+ return false;
+ }
}
/*
* (non-Javadoc)
*
* @see
* be.Balor.Manager.Permissions.AbstractPermission#getPermissionLimit(org
* .bukkit.entity.Player, java.lang.String)
*/
@Override
public String getPermissionLimit(Player p, String limit) {
return PEX.getUser(p).getOption("admincmd." + limit);
}
/*
* (non-Javadoc)
*
* @see
* be.Balor.Manager.Permissions.AbstractPermission#getPrefix(java.lang.String
* , java.lang.String)
*/
@Override
public String getPrefix(Player player) {
String prefix = "";
for (PermissionGroup group : PEX.getUser(player).getGroups())
if ((prefix = group.getPrefix()) != null && !prefix.isEmpty())
break;
return prefix;
}
}
| false | false | null | null |
diff --git a/SeriesGuide/src/com/battlelancer/seriesguide/ui/ShowsActivity.java b/SeriesGuide/src/com/battlelancer/seriesguide/ui/ShowsActivity.java
index 958272bb3..52cfef331 100644
--- a/SeriesGuide/src/com/battlelancer/seriesguide/ui/ShowsActivity.java
+++ b/SeriesGuide/src/com/battlelancer/seriesguide/ui/ShowsActivity.java
@@ -1,1156 +1,1158 @@
package com.battlelancer.seriesguide.ui;
import com.battlelancer.seriesguide.AddShow;
import com.battlelancer.seriesguide.R;
import com.battlelancer.seriesguide.SeriesDatabase;
import com.battlelancer.seriesguide.SeriesGuideApplication;
import com.battlelancer.seriesguide.SeriesGuideData;
import com.battlelancer.seriesguide.SeriesGuideData.ShowSorting;
import com.battlelancer.seriesguide.SeriesGuidePreferences;
import com.battlelancer.seriesguide.ShowInfo;
import com.battlelancer.seriesguide.provider.SeriesContract;
import com.battlelancer.seriesguide.provider.SeriesContract.Shows;
import com.battlelancer.seriesguide.util.AnalyticsUtils;
import com.battlelancer.seriesguide.util.EulaHelper;
import com.battlelancer.seriesguide.util.UIUtils;
import com.battlelancer.seriesguide.util.UpdateTask;
import com.battlelancer.thetvdbapi.TheTVDB;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
+import android.content.pm.PackageManager;
+import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.BaseColumns;
import android.support.v4.app.ActionBar;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.view.Menu;
import android.support.v4.view.MenuItem;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class ShowsActivity extends BaseActivity implements AbsListView.OnScrollListener,
LoaderManager.LoaderCallbacks<Cursor>, ActionBar.OnNavigationListener {
private boolean mBusy;
private static final int UPDATE_SUCCESS = 100;
private static final int UPDATE_INCOMPLETE = 104;
private static final int CONTEXT_DELETE_ID = 200;
private static final int CONTEXT_UPDATESHOW_ID = 201;
private static final int CONTEXT_SHOWINFO = 202;
private static final int CONTEXT_MARKNEXT = 203;
private static final int CONTEXT_FAVORITE = 204;
private static final int CONTEXT_UNFAVORITE = 205;
public static final int UPDATE_OFFLINE_DIALOG = 300;
public static final int UPDATE_SAXERROR_DIALOG = 302;
private static final int CONFIRM_DELETE_DIALOG = 304;
private static final int WHATS_NEW_DIALOG = 305;
private static final int SORT_DIALOG = 306;
private static final int BETA_WARNING_DIALOG = 307;
private static final int LOADER_ID = 900;
// Background Task States
private static final String STATE_UPDATE_IN_PROGRESS = "seriesguide.update.inprogress";
private static final String STATE_UPDATE_SHOWS = "seriesguide.update.shows";
private static final String STATE_UPDATE_INDEX = "seriesguide.update.index";
private static final String STATE_UPDATE_FAILEDSHOWS = "seriesguide.update.failedshows";
private static final String STATE_ART_IN_PROGRESS = "seriesguide.art.inprogress";
private static final String STATE_ART_PATHS = "seriesguide.art.paths";
private static final String STATE_ART_INDEX = "seriesguide.art.index";
// Show Filter Ids
private static final int SHOWFILTER_ALL = 0;
private static final int SHOWFILTER_FAVORITES = 1;
private static final int SHOWFILTER_UNSEENEPISODES = 2;
private static final String FILTER_ID = "filterid";
- private static final int VER_TRAKT_SEC_CHANGES = 138;
+ private static final int VER_TRAKT_SEC_CHANGES = 129;
private Bundle mSavedState;
private UpdateTask mUpdateTask;
private FetchArtTask mArtTask;
private SlowAdapter mAdapter;
private String mFailedShowsString;
private ShowSorting mSorting;
private long mToDeleteId;
private boolean mIsPreventLoaderRestart;
/**
* Google Analytics helper method for easy event tracking.
*
* @param label
*/
public void fireTrackerEvent(String label) {
AnalyticsUtils.getInstance(this).trackEvent("Shows", "Click", label, 0);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shows);
if (!EulaHelper.hasAcceptedEula(this)) {
EulaHelper.showEula(false, this);
}
final SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
// setup action bar filter list (! use different layouts for ABS)
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
ArrayAdapter<CharSequence> mActionBarList = ArrayAdapter.createFromResource(this,
R.array.showfilter_list, R.layout.abs__simple_spinner_item);
mActionBarList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
actionBar.setListNavigationCallbacks(mActionBarList, this);
// try to restore previously set show filter
int showfilter = prefs.getInt(SeriesGuidePreferences.KEY_SHOWFILTER, 0);
actionBar.setSelectedNavigationItem(showfilter);
// prevent the onNavigationItemSelected listener from reacting
mIsPreventLoaderRestart = true;
updatePreferences(prefs);
// setup show adapter
String[] from = new String[] {
SeriesContract.Shows.TITLE, SeriesContract.Shows.NEXTTEXT,
SeriesContract.Shows.AIRSTIME, SeriesContract.Shows.NETWORK,
SeriesContract.Shows.POSTER
};
int[] to = new int[] {
R.id.seriesname, R.id.TextViewShowListNextEpisode, R.id.TextViewShowListAirtime,
R.id.TextViewShowListNetwork, R.id.showposter
};
int layout = R.layout.show_rowairtime;
mAdapter = new SlowAdapter(this, layout, null, from, to, 0);
GridView list = (GridView) findViewById(android.R.id.list);
list.setAdapter(mAdapter);
list.setFastScrollEnabled(true);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Intent i = new Intent(ShowsActivity.this, OverviewActivity.class);
i.putExtra(Shows._ID, String.valueOf(id));
startActivity(i);
}
});
list.setOnScrollListener(this);
// TODO: make new empty view, move current to a welcome dialog
View emptyView = findViewById(android.R.id.empty);
if (emptyView != null) {
list.setEmptyView(emptyView);
}
// start loading data
Bundle args = new Bundle();
args.putInt(FILTER_ID, showfilter);
getSupportLoaderManager().initLoader(LOADER_ID, args, this);
registerForContextMenu(list);
}
@Override
protected void onStart() {
super.onStart();
AnalyticsUtils.getInstance(this).trackPageView("/Shows");
}
@Override
protected void onResume() {
super.onResume();
updateLatestEpisode();
if (mSavedState != null) {
restoreLocalState(mSavedState);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
onCancelTasks();
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
restoreLocalState(savedInstanceState);
mSavedState = null;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveUpdateTask(outState);
saveArtTask(outState);
mSavedState = outState;
}
private void restoreLocalState(Bundle savedInstanceState) {
restoreUpdateTask(savedInstanceState);
restoreArtTask(savedInstanceState);
}
private void restoreArtTask(Bundle savedInstanceState) {
if (savedInstanceState.getBoolean(STATE_ART_IN_PROGRESS)) {
ArrayList<String> paths = savedInstanceState.getStringArrayList(STATE_ART_PATHS);
int index = savedInstanceState.getInt(STATE_ART_INDEX);
if (paths != null) {
mArtTask = (FetchArtTask) new FetchArtTask(paths, index).execute();
AnalyticsUtils.getInstance(this).trackEvent("Shows", "Task Lifecycle",
"Art Task Restored", 0);
}
}
}
private void saveArtTask(Bundle outState) {
final FetchArtTask task = mArtTask;
if (task != null && task.getStatus() != AsyncTask.Status.FINISHED) {
task.cancel(true);
outState.putBoolean(STATE_ART_IN_PROGRESS, true);
outState.putStringArrayList(STATE_ART_PATHS, task.mPaths);
outState.putInt(STATE_ART_INDEX, task.mFetchCount.get());
mArtTask = null;
AnalyticsUtils.getInstance(this).trackEvent("Shows", "Task Lifecycle",
"Art Task Saved", 0);
}
}
private void restoreUpdateTask(Bundle savedInstanceState) {
if (savedInstanceState.getBoolean(STATE_UPDATE_IN_PROGRESS)) {
String[] shows = savedInstanceState.getStringArray(STATE_UPDATE_SHOWS);
int index = savedInstanceState.getInt(STATE_UPDATE_INDEX);
String failedShows = savedInstanceState.getString(STATE_UPDATE_FAILEDSHOWS);
if (shows != null) {
mUpdateTask = (UpdateTask) new UpdateTask(shows, index, failedShows, this)
.execute();
AnalyticsUtils.getInstance(this).trackEvent("Shows", "Task Lifecycle",
"Update Task Restored", 0);
}
}
}
private void saveUpdateTask(Bundle outState) {
final UpdateTask task = mUpdateTask;
if (task != null && task.getStatus() != AsyncTask.Status.FINISHED) {
task.cancel(true);
outState.putBoolean(STATE_UPDATE_IN_PROGRESS, true);
outState.putStringArray(STATE_UPDATE_SHOWS, task.mShows);
outState.putInt(STATE_UPDATE_INDEX, task.mUpdateCount.get());
outState.putString(STATE_UPDATE_FAILEDSHOWS, task.mFailedShows);
mUpdateTask = null;
AnalyticsUtils.getInstance(this).trackEvent("Shows", "Task Lifecycle",
"Update Task Saved", 0);
}
}
@Override
protected Dialog onCreateDialog(int id) {
String message = "";
switch (id) {
case UPDATE_SAXERROR_DIALOG:
if (getFailedShowsString() != null && getFailedShowsString().length() != 0) {
message += getString(R.string.update_incomplete1) + " "
+ getFailedShowsString() + getString(R.string.update_incomplete2)
+ getString(R.string.saxerror);
} else {
message += getString(R.string.update_error) + " "
+ getString(R.string.saxerror);
}
return new AlertDialog.Builder(this).setTitle(getString(R.string.saxerror_title))
.setMessage(message).setPositiveButton(android.R.string.ok, null).create();
case UPDATE_OFFLINE_DIALOG:
return new AlertDialog.Builder(this)
.setTitle(getString(R.string.offline_title))
.setMessage(
getString(R.string.update_error) + " "
+ getString(R.string.offline))
.setPositiveButton(android.R.string.ok, null).create();
case CONFIRM_DELETE_DIALOG:
return new AlertDialog.Builder(this).setMessage(getString(R.string.confirm_delete))
.setPositiveButton(getString(R.string.delete_show), new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
final ProgressDialog progress = new ProgressDialog(
ShowsActivity.this);
progress.setCancelable(false);
progress.show();
new Thread(new Runnable() {
public void run() {
SeriesDatabase.deleteShow(getApplicationContext(),
String.valueOf(mToDeleteId));
if (progress.isShowing()) {
progress.dismiss();
}
}
}).start();
}
}).setNegativeButton(getString(R.string.dontdelete_show), null).create();
case WHATS_NEW_DIALOG:
return new AlertDialog.Builder(this).setTitle(getString(R.string.whatsnew_title))
.setIcon(android.R.drawable.ic_dialog_info)
.setMessage(getString(R.string.whatsnew_content))
.setPositiveButton(android.R.string.ok, null).create();
case BETA_WARNING_DIALOG:
/* Used for unstable beta releases */
return new AlertDialog.Builder(this)
.setTitle(getString(R.string.whatsnew_title))
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(getString(R.string.betawarning))
.setPositiveButton(R.string.gobreak, null)
.setNeutralButton(getString(R.string.download_stable),
new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
Intent myIntent = new Intent(
Intent.ACTION_VIEW,
Uri.parse("market://details?id=com.battlelancer.seriesguide"));
startActivity(myIntent);
} catch (ActivityNotFoundException e) {
Intent myIntent = new Intent(
Intent.ACTION_VIEW,
Uri.parse("http://market.android.com/details?id=com.battlelancer.seriesguide"));
startActivity(myIntent);
}
finish();
}
}).create();
case SORT_DIALOG:
final CharSequence[] items = getResources().getStringArray(R.array.shsorting);
return new AlertDialog.Builder(this)
.setTitle(getString(R.string.pref_showsorting))
.setSingleChoiceItems(items, mSorting.index(),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
SharedPreferences.Editor prefEditor = PreferenceManager
.getDefaultSharedPreferences(
getApplicationContext()).edit();
prefEditor
.putString(
SeriesGuidePreferences.KEY_SHOWSSORTORDER,
(getResources()
.getStringArray(R.array.shsortingData))[item]);
prefEditor.commit();
removeDialog(SORT_DIALOG);
}
}).create();
}
return null;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menuInfo.toString();
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
final Cursor show = getContentResolver().query(Shows.buildShowUri(String.valueOf(info.id)),
new String[] {
Shows.FAVORITE
}, null, null, null);
show.moveToFirst();
if (show.getInt(0) == 0) {
menu.add(0, CONTEXT_FAVORITE, 0, R.string.context_favorite);
} else {
menu.add(0, CONTEXT_UNFAVORITE, 0, R.string.context_unfavorite);
}
show.close();
menu.add(0, CONTEXT_SHOWINFO, 1, R.string.context_showinfo);
menu.add(0, CONTEXT_MARKNEXT, 2, R.string.context_marknext);
menu.add(0, CONTEXT_UPDATESHOW_ID, 3, R.string.context_updateshow);
menu.add(0, CONTEXT_DELETE_ID, 4, R.string.delete_show);
}
@Override
public boolean onContextItemSelected(android.view.MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case CONTEXT_FAVORITE: {
fireTrackerEvent("Favorite show");
ContentValues values = new ContentValues();
values.put(Shows.FAVORITE, true);
getContentResolver().update(Shows.buildShowUri(String.valueOf(info.id)), values,
null, null);
Toast.makeText(this, getString(R.string.favorited), Toast.LENGTH_SHORT).show();
return true;
}
case CONTEXT_UNFAVORITE: {
fireTrackerEvent("Unfavorite show");
ContentValues values = new ContentValues();
values.put(Shows.FAVORITE, false);
getContentResolver().update(Shows.buildShowUri(String.valueOf(info.id)), values,
null, null);
Toast.makeText(this, getString(R.string.unfavorited), Toast.LENGTH_SHORT).show();
return true;
}
case CONTEXT_DELETE_ID:
fireTrackerEvent("Delete show");
if (!isUpdateTaskRunning()) {
mToDeleteId = info.id;
showDialog(CONFIRM_DELETE_DIALOG);
}
return true;
case CONTEXT_UPDATESHOW_ID:
fireTrackerEvent("Update show");
if (!isUpdateTaskRunning()) {
performUpdateTask(false, String.valueOf(info.id));
}
return true;
case CONTEXT_SHOWINFO:
fireTrackerEvent("Display show info");
Intent i = new Intent(this, ShowInfo.class);
i.putExtra(Shows._ID, String.valueOf(info.id));
startActivity(i);
return true;
case CONTEXT_MARKNEXT:
fireTrackerEvent("Mark next episode");
SeriesDatabase.markNextEpisode(this, info.id);
Thread t = new UpdateLatestEpisodeThread(this, String.valueOf(info.id));
t.start();
return true;
}
return super.onContextItemSelected(item);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.seriesguide_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (android.os.Build.VERSION.SDK_INT >= 11) {
final CharSequence[] items = getResources().getStringArray(R.array.shsorting);
menu.findItem(R.id.menu_showsortby).setTitle(
getString(R.string.sort) + ": " + items[mSorting.index()]);
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_search:
fireTrackerEvent("Search");
onSearchRequested();
return true;
case R.id.menu_update:
fireTrackerEvent("Update all shows");
if (!isUpdateTaskRunning() && !isArtTaskRunning()) {
performUpdateTask(false, null);
}
return true;
case R.id.menu_upcoming:
startActivity(new Intent(this, UpcomingRecentActivity.class));
return true;
case R.id.menu_new_show:
startActivity(new Intent(this, AddShow.class));
return true;
case R.id.menu_showsortby:
fireTrackerEvent("Sort shows");
showDialog(SORT_DIALOG);
return true;
case R.id.menu_updateart:
fireTrackerEvent("Fetch missing posters");
if (isArtTaskRunning() || isUpdateTaskRunning()) {
return true;
}
// already fail if there is no external storage
if (!UIUtils.isExtStorageAvailable()) {
Toast.makeText(this, getString(R.string.update_nosdcard), Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(this, getString(R.string.update_inbackground), Toast.LENGTH_LONG)
.show();
mArtTask = (FetchArtTask) new FetchArtTask().execute();
}
return true;
case R.id.menu_preferences:
startActivity(new Intent(this, SeriesGuidePreferences.class));
return true;
case R.id.menu_fullupdate:
fireTrackerEvent("Full Update");
if (!isUpdateTaskRunning() && !isArtTaskRunning()) {
performUpdateTask(true, null);
}
return true;
default: {
return super.onOptionsItemSelected(item);
}
}
}
/**
* Update the latest episode fields for all existing shows.
*/
public void updateLatestEpisode() {
Thread t = new UpdateLatestEpisodeThread(this);
t.start();
}
private static class UpdateLatestEpisodeThread extends Thread {
private Context mContext;
private String mShowId;
public UpdateLatestEpisodeThread(Context context) {
mContext = context;
this.setName("UpdateLatestEpisode");
}
public UpdateLatestEpisodeThread(Context context, String showId) {
this(context);
mShowId = showId;
}
public void run() {
if (mShowId != null) {
// update single show
SeriesDatabase.updateLatestEpisode(mContext, mShowId);
} else {
// update all shows
final Cursor shows = mContext.getContentResolver().query(Shows.CONTENT_URI,
new String[] {
Shows._ID
}, null, null, null);
while (shows.moveToNext()) {
String id = shows.getString(0);
SeriesDatabase.updateLatestEpisode(mContext, id);
}
shows.close();
}
// Adapter gets notified by ContentProvider
}
}
private void performUpdateTask(boolean isFullUpdate, String showId) {
int messageId;
if (isFullUpdate) {
messageId = R.string.update_full;
mUpdateTask = (UpdateTask) new UpdateTask(true, this).execute();
} else {
if (showId == null) {
// (delta) update all shows
messageId = R.string.update_delta;
mUpdateTask = (UpdateTask) new UpdateTask(false, this).execute();
} else {
// update a single show
messageId = R.string.update_inbackground;
mUpdateTask = (UpdateTask) new UpdateTask(new String[] {
showId
}, 0, "", this).execute();
}
}
Toast.makeText(this, getString(messageId), Toast.LENGTH_SHORT).show();
}
/**
* If the updateThread is already running, shows a toast telling the user to
* wait.
*
* @return true if an update is in progress and toast was shown, false
* otherwise
*/
private boolean isUpdateTaskRunning() {
if (mUpdateTask != null && mUpdateTask.getStatus() != AsyncTask.Status.FINISHED) {
Toast.makeText(this, getString(R.string.update_inprogress), Toast.LENGTH_LONG).show();
return true;
} else {
return false;
}
}
private class FetchArtTask extends AsyncTask<Void, Void, Integer> {
final AtomicInteger mFetchCount = new AtomicInteger();
ArrayList<String> mPaths;
private View mProgressOverlay;
protected FetchArtTask() {
}
protected FetchArtTask(ArrayList<String> paths, int index) {
mPaths = paths;
mFetchCount.set(index);
}
@Override
protected void onPreExecute() {
// see if we already inflated the progress overlay
mProgressOverlay = findViewById(R.id.overlay_update);
if (mProgressOverlay == null) {
mProgressOverlay = ((ViewStub) findViewById(R.id.stub_update)).inflate();
}
showOverlay(mProgressOverlay);
// setup the progress overlay
TextView mUpdateStatus = (TextView) mProgressOverlay
.findViewById(R.id.textViewUpdateStatus);
mUpdateStatus.setText("");
ProgressBar updateProgress = (ProgressBar) mProgressOverlay
.findViewById(R.id.ProgressBarShowListDet);
updateProgress.setIndeterminate(true);
View cancelButton = mProgressOverlay.findViewById(R.id.overlayCancel);
cancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onCancelTasks();
}
});
}
@Override
protected Integer doInBackground(Void... params) {
// fetch all available poster paths
if (mPaths == null) {
Cursor shows = getContentResolver().query(Shows.CONTENT_URI, new String[] {
Shows.POSTER
}, null, null, null);
// finish fast if there is no image to download
if (shows.getCount() == 0) {
shows.close();
return UPDATE_SUCCESS;
}
mPaths = new ArrayList<String>();
while (shows.moveToNext()) {
String imagePath = shows.getString(shows.getColumnIndexOrThrow(Shows.POSTER));
if (imagePath.length() != 0) {
mPaths.add(imagePath);
}
}
shows.close();
}
int resultCode = UPDATE_SUCCESS;
final List<String> list = mPaths;
final int count = list.size();
final AtomicInteger fetchCount = mFetchCount;
// try to fetch image for each path
for (int i = fetchCount.get(); i < count; i++) {
if (isCancelled()) {
// code doesn't matter as onPostExecute will not be called
return UPDATE_INCOMPLETE;
}
if (!TheTVDB.fetchArt(list.get(i), true, ShowsActivity.this)) {
resultCode = UPDATE_INCOMPLETE;
}
fetchCount.incrementAndGet();
}
getContentResolver().notifyChange(Shows.CONTENT_URI, null);
return resultCode;
}
@Override
protected void onPostExecute(Integer resultCode) {
switch (resultCode) {
case UPDATE_SUCCESS:
AnalyticsUtils.getInstance(ShowsActivity.this).trackEvent("Shows",
"Fetch missing posters", "Success", 0);
Toast.makeText(getApplicationContext(), getString(R.string.update_success),
Toast.LENGTH_SHORT).show();
break;
case UPDATE_INCOMPLETE:
AnalyticsUtils.getInstance(ShowsActivity.this).trackEvent("Shows",
"Fetch missing posters", "Incomplete", 0);
Toast.makeText(getApplicationContext(),
getString(R.string.imagedownload_incomplete), Toast.LENGTH_LONG).show();
break;
}
hideOverlay(mProgressOverlay);
}
@Override
protected void onCancelled() {
hideOverlay(mProgressOverlay);
}
}
private boolean isArtTaskRunning() {
if (mArtTask != null && mArtTask.getStatus() == AsyncTask.Status.RUNNING) {
Toast.makeText(this, getString(R.string.update_inprogress), Toast.LENGTH_LONG).show();
return true;
} else {
return false;
}
}
public void onCancelTasks() {
if (mUpdateTask != null && mUpdateTask.getStatus() == AsyncTask.Status.RUNNING) {
mUpdateTask.cancel(true);
mUpdateTask = null;
AnalyticsUtils.getInstance(this).trackEvent("Shows", "Task Lifecycle",
"Update Task Canceled", 0);
}
if (mArtTask != null && mArtTask.getStatus() == AsyncTask.Status.RUNNING) {
mArtTask.cancel(true);
mArtTask = null;
AnalyticsUtils.getInstance(this).trackEvent("Shows", "Task Lifecycle",
"Art Task Canceled", 0);
}
}
public void showOverlay(View overlay) {
overlay.startAnimation(AnimationUtils
.loadAnimation(getApplicationContext(), R.anim.fade_in));
overlay.setVisibility(View.VISIBLE);
}
public void hideOverlay(View overlay) {
overlay.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.fade_out));
overlay.setVisibility(View.GONE);
}
private void requery() {
int filterId = getSupportActionBar().getSelectedNavigationIndex();
// just reuse the onNavigationItemSelected callback method
onNavigationItemSelected(filterId, filterId);
}
final OnSharedPreferenceChangeListener mPrefsListener = new OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
boolean isAffectingChange = false;
if (key.equalsIgnoreCase(SeriesGuidePreferences.KEY_SHOWSSORTORDER)) {
updateSorting(sharedPreferences);
isAffectingChange = true;
}
// TODO: maybe don't requery every time a pref changes (possibly
// problematic if you change a setting in the settings activity)
if (isAffectingChange) {
requery();
}
}
};
/**
* Called once on activity creation to load initial settings and display
* one-time information dialogs.
*/
private void updatePreferences(SharedPreferences prefs) {
updateSorting(prefs);
// between-version upgrade code
int lastVersion = prefs.getInt(SeriesGuideData.KEY_VERSION, -1);
try {
int currentVersion = getPackageManager().getPackageInfo(getPackageName(),
PackageManager.GET_META_DATA).versionCode;
if (currentVersion > lastVersion) {
switch (currentVersion) {
case VER_TRAKT_SEC_CHANGES:
prefs.edit().putString(SeriesGuidePreferences.PREF_TRAKTPWD, "").commit();
}
// BETA warning dialog switch
// showDialog(BETA_WARNING_DIALOG);
// showDialog(WHATS_NEW_DIALOG);
// set this as lastVersion
prefs.edit().putInt(SeriesGuideData.KEY_VERSION, currentVersion).commit();
}
} catch (NameNotFoundException e) {
// this should never happen
}
prefs.registerOnSharedPreferenceChangeListener(mPrefsListener);
}
/**
* Fetch the sorting preference and store it in this class.
*
* @param prefs
* @return Returns true if the value changed, false otherwise.
*/
private boolean updateSorting(SharedPreferences prefs) {
final ShowSorting oldSorting = mSorting;
final CharSequence[] items = getResources().getStringArray(R.array.shsortingData);
final String sortsetting = prefs.getString(SeriesGuidePreferences.KEY_SHOWSSORTORDER,
"favorites");
for (int i = 0; i < items.length; i++) {
if (sortsetting.equals(items[i])) {
mSorting = ShowSorting.values()[i];
break;
}
}
AnalyticsUtils.getInstance(ShowsActivity.this).trackEvent("Shows", "Sorting",
mSorting.name(), 0);
return oldSorting != mSorting;
}
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String selection = null;
String[] selectionArgs = null;
int filterId = args.getInt(FILTER_ID);
switch (filterId) {
case SHOWFILTER_ALL:
// do nothing, leave selection null
break;
case SHOWFILTER_FAVORITES:
selection = Shows.FAVORITE + "=?";
selectionArgs = new String[] {
"1"
};
break;
case SHOWFILTER_UNSEENEPISODES:
selection = Shows.NEXTAIRDATE + "!=? AND julianday(" + Shows.NEXTAIRDATE
+ ") <= julianday('now')";
selectionArgs = new String[] {
SeriesDatabase.UNKNOWN_NEXT_AIR_DATE
};
break;
}
return new CursorLoader(this, Shows.CONTENT_URI, ShowsQuery.PROJECTION, selection,
selectionArgs, mSorting.query());
}
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Swap the new cursor in. (The framework will take care of closing the
// old cursor once we return.)
mAdapter.swapCursor(data);
}
public void onLoaderReset(Loader<Cursor> arg0) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
mAdapter.swapCursor(null);
}
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
// only handle events after the event caused when creating the activity
if (mIsPreventLoaderRestart) {
mIsPreventLoaderRestart = false;
} else {
// requery with the new filter
Bundle args = new Bundle();
args.putInt(FILTER_ID, itemPosition);
getSupportLoaderManager().restartLoader(LOADER_ID, args, this);
// save the selected filter back to settings
Editor editor = PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
.edit();
editor.putInt(SeriesGuidePreferences.KEY_SHOWFILTER, itemPosition);
editor.commit();
}
return true;
}
public void setFailedShowsString(String mFailedShowsString) {
this.mFailedShowsString = mFailedShowsString;
}
public String getFailedShowsString() {
return mFailedShowsString;
}
private interface ShowsQuery {
String[] PROJECTION = {
BaseColumns._ID, Shows.TITLE, Shows.NEXTTEXT, Shows.AIRSTIME, Shows.NETWORK,
Shows.POSTER, Shows.AIRSDAYOFWEEK, Shows.STATUS, Shows.NEXTAIRDATETEXT
};
// int _ID = 0;
int TITLE = 1;
int NEXTTEXT = 2;
int AIRSTIME = 3;
int NETWORK = 4;
int POSTER = 5;
int AIRSDAYOFWEEK = 6;
int STATUS = 7;
int NEXTAIRDATETEXT = 8;
}
private class SlowAdapter extends SimpleCursorAdapter {
private LayoutInflater mLayoutInflater;
private int mLayout;
public SlowAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
mLayoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mLayout = layout;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (!mDataValid) {
throw new IllegalStateException(
"this should only be called when the cursor is valid");
}
if (!mCursor.moveToPosition(position)) {
throw new IllegalStateException("couldn't move cursor to position " + position);
}
ViewHolder viewHolder;
if (convertView == null) {
convertView = mLayoutInflater.inflate(mLayout, null);
viewHolder = new ViewHolder();
viewHolder.name = (TextView) convertView.findViewById(R.id.seriesname);
viewHolder.network = (TextView) convertView
.findViewById(R.id.TextViewShowListNetwork);
viewHolder.next = (TextView) convertView.findViewById(R.id.next);
viewHolder.episode = (TextView) convertView
.findViewById(R.id.TextViewShowListNextEpisode);
viewHolder.episodeTime = (TextView) convertView.findViewById(R.id.episodetime);
viewHolder.airsTime = (TextView) convertView
.findViewById(R.id.TextViewShowListAirtime);
viewHolder.poster = (ImageView) convertView.findViewById(R.id.showposter);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// set text properties immediately
viewHolder.name.setText(mCursor.getString(ShowsQuery.TITLE));
viewHolder.network.setText(mCursor.getString(ShowsQuery.NETWORK));
// next episode info
String fieldValue = mCursor.getString(ShowsQuery.NEXTTEXT);
if (fieldValue.length() == 0) {
// show show status if there are currently no more
// episodes
int status = mCursor.getInt(ShowsQuery.STATUS);
// Continuing == 1 and Ended == 0
if (status == 1) {
viewHolder.next.setText(getString(R.string.show_isalive));
} else if (status == 0) {
viewHolder.next.setText(getString(R.string.show_isnotalive));
} else {
viewHolder.next.setText("");
}
viewHolder.episode.setText("");
viewHolder.episodeTime.setText("");
} else {
viewHolder.next.setText(getString(R.string.nextepisode));
viewHolder.episode.setText(fieldValue);
fieldValue = mCursor.getString(ShowsQuery.NEXTAIRDATETEXT);
viewHolder.episodeTime.setText(fieldValue);
}
// airday
String[] values = SeriesGuideData.parseMillisecondsToTime(
mCursor.getLong(ShowsQuery.AIRSTIME),
mCursor.getString(ShowsQuery.AIRSDAYOFWEEK), ShowsActivity.this);
viewHolder.airsTime.setText(values[1] + " " + values[0]);
// set poster only when not busy scrolling
final String path = mCursor.getString(ShowsQuery.POSTER);
if (!mBusy) {
// load poster
setPosterBitmap(viewHolder.poster, path, false);
// Null tag means the view has the correct data
viewHolder.poster.setTag(null);
} else {
// only load in-memory poster
setPosterBitmap(viewHolder.poster, path, true);
}
return convertView;
}
}
public final class ViewHolder {
public TextView name;
public TextView network;
public TextView next;
public TextView episode;
public TextView episodeTime;
public TextView airsTime;
public ImageView poster;
}
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
switch (scrollState) {
case OnScrollListener.SCROLL_STATE_IDLE:
mBusy = false;
int count = view.getChildCount();
for (int i = 0; i < count; i++) {
final ViewHolder holder = (ViewHolder) view.getChildAt(i).getTag();
final ImageView poster = holder.poster;
if (poster.getTag() != null) {
setPosterBitmap(poster, (String) poster.getTag(), false);
poster.setTag(null);
}
}
break;
case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
mBusy = false;
break;
case OnScrollListener.SCROLL_STATE_FLING:
mBusy = true;
break;
}
}
/**
* If {@code isBusy} is {@code true}, then the image is only loaded if it is
* in memory. In every other case a place-holder is shown.
*
* @param poster
* @param path
* @param isBusy
*/
private void setPosterBitmap(ImageView poster, String path, boolean isBusy) {
Bitmap bitmap = null;
if (path.length() != 0) {
bitmap = ((SeriesGuideApplication) getApplication()).getImageCache().getThumb(path,
isBusy);
}
if (bitmap != null) {
poster.setImageBitmap(bitmap);
poster.setTag(null);
} else {
// set placeholder
poster.setImageResource(R.drawable.show_generic);
// Non-null tag means the view still needs to load it's data
poster.setTag(path);
}
}
}
| false | false | null | null |
diff --git a/bundles/initiator/src/main/java/org/jscsi/initiator/connection/state/CapacityRequestState.java b/bundles/initiator/src/main/java/org/jscsi/initiator/connection/state/CapacityRequestState.java
index b27db6c8..b75b667a 100644
--- a/bundles/initiator/src/main/java/org/jscsi/initiator/connection/state/CapacityRequestState.java
+++ b/bundles/initiator/src/main/java/org/jscsi/initiator/connection/state/CapacityRequestState.java
@@ -1,128 +1,128 @@
/**
* Copyright (c) 2011, University of Konstanz, Distributed Systems Group
* 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 University of Konstanz nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.jscsi.initiator.connection.state;
+import org.jscsi.exception.InternetSCSIException;
import org.jscsi.initiator.connection.Connection;
import org.jscsi.initiator.connection.TargetCapacityInformations;
import org.jscsi.parser.OperationCode;
import org.jscsi.parser.ProtocolDataUnit;
import org.jscsi.parser.datasegment.OperationalTextKey;
-import org.jscsi.parser.exception.InternetSCSIException;
import org.jscsi.parser.scsi.SCSICommandDescriptorBlockParser;
import org.jscsi.parser.scsi.SCSICommandParser;
import org.jscsi.parser.scsi.SCSICommandParser.TaskAttributes;
/**
* <h1>CapacityRequestState</h1>
* <p/>
* This state handles a Capacity Request to retrieve the block size and the size
* of the iSCSI Device.
*
* @author Volker Wildi
*/
public final class CapacityRequestState extends AbstractState {
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
/** The sent command has a fixed size of <code>8</code> bytes. */
private static final int EXPECTED_DATA_TRANSFER_LENGTH = 0x08;
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
/**
* This object contains the informations about the capacity of the connected
* target.
*/
private final TargetCapacityInformations capacityInformation;
private final TaskAttributes taskAttributes;
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
/**
* Constructor to create a new, empty <code>CapacityRequestState</code>
* instance.
*
* @param initConnection
* This is the connection, which is used for the network
* transmission.
* @param initCapacityInformation
* Store the informations about that iSCSI Device in this
* instance.
* @param initTaskAttributes
* The task attributes, which are used with task.
*/
public CapacityRequestState(final Connection initConnection,
final TargetCapacityInformations initCapacityInformation,
final TaskAttributes initTaskAttributes) {
super(initConnection);
capacityInformation = initCapacityInformation;
taskAttributes = initTaskAttributes;
}
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
/** {@inheritDoc} */
public final void execute() throws InternetSCSIException {
final ProtocolDataUnit protocolDataUnit = protocolDataUnitFactory
.create(false,
true,
OperationCode.SCSI_COMMAND,
connection.getSetting(OperationalTextKey.HEADER_DIGEST),
connection.getSetting(OperationalTextKey.DATA_DIGEST));
final SCSICommandParser scsi = (SCSICommandParser) protocolDataUnit
.getBasicHeaderSegment().getParser();
scsi.setReadExpectedFlag(true);
scsi.setWriteExpectedFlag(false);
scsi.setTaskAttributes(taskAttributes);
scsi.setExpectedDataTransferLength(EXPECTED_DATA_TRANSFER_LENGTH);
scsi.setCommandDescriptorBlock(SCSICommandDescriptorBlockParser
.createReadCapacityMessage());
connection.send(protocolDataUnit);
connection.nextState(new CapacityResponseState(connection,
capacityInformation));
super.stateFollowing = true;
// return true;
}
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
}
| false | false | null | null |
diff --git a/structure/src/main/java/org/biojava/bio/structure/align/client/FarmJobParameters.java b/structure/src/main/java/org/biojava/bio/structure/align/client/FarmJobParameters.java
index e2faa68a1..dcae16311 100644
--- a/structure/src/main/java/org/biojava/bio/structure/align/client/FarmJobParameters.java
+++ b/structure/src/main/java/org/biojava/bio/structure/align/client/FarmJobParameters.java
@@ -1,146 +1,146 @@
package org.biojava.bio.structure.align.client;
import org.biojava.bio.structure.align.util.ResourceManager;
public class FarmJobParameters {
public static final int DEFAULT_JOB_TIME = -1;
public static final int DEFAULT_NR_ALIGNMENTS = -1;
public static final int DEFAULT_NR_THREADS = 1;
public static final String DEFAULT_SERVER_URL;
private static ResourceManager resourceManager;
static {
resourceManager = ResourceManager.getResourceManager("jfatcat");
String server = resourceManager.getString("server.url");
DEFAULT_SERVER_URL = server;
}
public static final String DEFAULT_PDB_PATH = "/tmp/";
public static final boolean DEFAULT_DIR_SPLIT = true;
public static final int DEFAULT_BATCH_SIZE = 100;
private static final String DEFAULT_BATCH_SIZE_PROP = "request.pair.size";
int nrAlignments;
int time;
int threads;
String server;
String pdbFilePath;
boolean pdbDirSplit;
String username;
boolean runBackground;
int stepSize;
public FarmJobParameters(){
nrAlignments = DEFAULT_NR_ALIGNMENTS;
time = DEFAULT_JOB_TIME;
threads = DEFAULT_NR_THREADS;
server = DEFAULT_SERVER_URL;
pdbFilePath = DEFAULT_PDB_PATH;
pdbDirSplit = DEFAULT_DIR_SPLIT;
runBackground = false;
String nrPairsProp = resourceManager.getString(DEFAULT_BATCH_SIZE_PROP);
stepSize = DEFAULT_BATCH_SIZE;
if ( nrPairsProp != null){
try {
stepSize = Integer.parseInt(nrPairsProp);
} catch (NumberFormatException ex){
ex.printStackTrace();
}
}
}
public String getPdbFilePath() {
return pdbFilePath;
}
public void setPdbFilePath(String pdbFilePath) {
this.pdbFilePath = pdbFilePath;
}
public String toString() {
return "FarmJobParameters [nrAlignments=" + nrAlignments + ", server="
+ server + ", threads=" + threads + ", time=" + time + ", username=" + username +"]";
}
public int getNrAlignments() {
return nrAlignments;
}
public void setNrAlignments(int nrAlignments) {
this.nrAlignments = nrAlignments;
}
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
public int getThreads() {
return threads;
}
public void setThreads(int threads) {
this.threads = threads;
}
public String getServer() {
return server;
}
public void setServer(String server) {
this.server = server;
}
public boolean isPdbDirSplit() {
return pdbDirSplit;
}
public void setPdbDirSplit(boolean pdbDirSplit) {
this.pdbDirSplit = pdbDirSplit;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
/** Flag if a job that only runs one parallell job should be run in its own thread or in the main thread.
* For User interface related apps should be set to true. Default: false;
- * @return
+ * @return flag
*/
public boolean isRunBackground() {
return runBackground;
}
public void setRunBackground(boolean runBackground) {
this.runBackground = runBackground;
}
/** how many pairs should be requested for alignment from server?
*
- * @return
+ * @return stepsize
*/
public int getStepSize() {
return stepSize;
}
public void setStepSize(int stepSize) {
this.stepSize = stepSize;
}
}
| false | false | null | null |
diff --git a/src/main/java/org/iq80/leveldb/impl/DbImpl.java b/src/main/java/org/iq80/leveldb/impl/DbImpl.java
index cc891cd..7216e46 100644
--- a/src/main/java/org/iq80/leveldb/impl/DbImpl.java
+++ b/src/main/java/org/iq80/leveldb/impl/DbImpl.java
@@ -1,1048 +1,1064 @@
package org.iq80.leveldb.impl;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.iq80.leveldb.SeekingIterable;
import org.iq80.leveldb.SeekingIterator;
import org.iq80.leveldb.Snapshot;
import org.iq80.leveldb.impl.Filename.FileInfo;
import org.iq80.leveldb.impl.Filename.FileType;
import org.iq80.leveldb.impl.WriteBatch.Handler;
import org.iq80.leveldb.table.BasicUserComparator;
import org.iq80.leveldb.table.Options;
import org.iq80.leveldb.table.TableBuilder;
import org.iq80.leveldb.util.SeekingIterators;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.Thread.UncaughtExceptionHandler;
import java.nio.channels.FileChannel;
import java.util.Collections;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import static com.google.common.collect.Lists.newArrayList;
import static org.iq80.leveldb.impl.DbConstants.L0_SLOWDOWN_WRITES_TRIGGER;
import static org.iq80.leveldb.impl.DbConstants.L0_STOP_WRITES_TRIGGER;
import static org.iq80.leveldb.impl.DbConstants.MAX_MEM_COMPACT_LEVEL;
import static org.iq80.leveldb.impl.DbConstants.NUM_LEVELS;
import static org.iq80.leveldb.impl.InternalKey.INTERNAL_KEY_TO_USER_KEY;
import static org.iq80.leveldb.impl.InternalKey.createUserKeyToInternalKeyFunction;
import static org.iq80.leveldb.impl.SequenceNumber.MAX_SEQUENCE_NUMBER;
import static org.iq80.leveldb.impl.ValueType.DELETION;
import static org.iq80.leveldb.impl.ValueType.VALUE;
import static org.iq80.leveldb.util.Buffers.writeLengthPrefixedBytes;
// todo needs a close method
// todo implement remaining compaction methods
// todo make thread safe and concurrent
public class DbImpl implements SeekingIterable<ChannelBuffer, ChannelBuffer>
{
private final Options options;
private final File databaseDir;
private final TableCache tableCache;
private final DbLock dbLock;
private final VersionSet versions;
private final AtomicBoolean shuttingDown = new AtomicBoolean();
private final ReentrantLock mutex = new ReentrantLock();
private final Condition backgroundCondition = mutex.newCondition();
private final List<Long> pendingOutputs = newArrayList(); // todo
private FileChannel logChannel;
private long logFileNumber;
private LogWriter log;
private MemTable memTable;
private MemTable immutableMemTable;
private final InternalKeyComparator internalKeyComparator;
private ExecutorService compactionExecutor;
private Future<?> backgroundCompaction;
private ManualCompaction manualCompaction;
public DbImpl(Options options, File databaseDir)
throws IOException
{
Preconditions.checkNotNull(options, "options is null");
Preconditions.checkNotNull(databaseDir, "databaseDir is null");
this.options = options;
this.databaseDir = databaseDir;
internalKeyComparator = new InternalKeyComparator(new BasicUserComparator());
memTable = new MemTable(internalKeyComparator);
immutableMemTable = null;
ThreadFactory compactionThreadFactory = new ThreadFactoryBuilder()
.setNameFormat("leveldb-compaction-%s")
.setUncaughtExceptionHandler(new UncaughtExceptionHandler()
{
@Override
public void uncaughtException(Thread t, Throwable e)
{
// todo need a real UncaughtExceptionHandler
System.out.printf("%s%n", t);
e.printStackTrace();
}
})
.build();
compactionExecutor = Executors.newCachedThreadPool(compactionThreadFactory);
// Reserve ten files or so for other uses and give the rest to TableCache.
int tableCacheSize = options.getMaxOpenFiles() - 10;
tableCache = new TableCache(databaseDir, tableCacheSize, new InternalUserComparator(internalKeyComparator), options.isVerifyChecksums());
// create the version set
versions = new VersionSet(options, databaseDir, tableCache, internalKeyComparator);
// create the database dir if it does not already exist
databaseDir.mkdirs();
Preconditions.checkArgument(databaseDir.isDirectory(), "Database directory '%s' is not a directory");
mutex.lock();
try {
// lock the database dir
dbLock = new DbLock(new File(databaseDir, Filename.lockFileName()));
// verify the "current" file
File currentFile = new File(databaseDir, Filename.currentFileName());
if (!currentFile.canRead()) {
Preconditions.checkArgument(options.isCreateIfMissing(), "Database '%s' does not exist and the create if missing option is disabled", databaseDir);
}
else {
Preconditions.checkArgument(!options.isErrorIfExists(), "Database '%s' exists and the error if exists option is enabled", databaseDir);
}
// load (and recover) current version
versions.recover();
// Recover from all newer log files than the ones named in the
// descriptor (new log files may have been added by the previous
// incarnation without registering them in the descriptor).
//
// Note that PrevLogNumber() is no longer used, but we pay
// attention to it in case we are recovering a database
// produced by an older version of leveldb.
long minLogNumber = versions.getLogNumber();
long previousLogNumber = versions.getPrevLogNumber();
List<File> filenames = Filename.listFiles(databaseDir);
List<Long> logs = Lists.newArrayList();
for (File filename : filenames) {
FileInfo fileInfo = Filename.parseFileName(filename);
if (fileInfo != null &&
fileInfo.getFileType() == FileType.LOG &&
((fileInfo.getFileNumber() >= minLogNumber) || (fileInfo.getFileNumber() == previousLogNumber))) {
logs.add(fileInfo.getFileNumber());
}
}
// Recover in the order in which the logs were generated
VersionEdit edit = new VersionEdit();
Collections.sort(logs);
for (Long fileNumber : logs) {
// long maxSequence = recoverLogFile(fileNumber, edit);
// if (versions.getLastSequence() < maxSequence) {
// versions.setLastSequence(maxSequence);
// }
}
// open transaction log
long newLogNumber = versions.getNextFileNumber();
File logFile = new File(databaseDir, Filename.logFileName(newLogNumber));
FileChannel logChannel = new FileOutputStream(logFile).getChannel();
edit.setLogNumber(newLogNumber);
this.logChannel = logChannel;
this.logFileNumber = newLogNumber;
this.log = new LogWriter(logChannel);
// apply recovered edits
versions.logAndApply(edit);
// cleanup unused files
deleteObsoleteFiles();
// schedule compactions
maybeScheduleCompaction();
}
finally {
mutex.unlock();
}
}
public void close() {
if (shuttingDown.getAndSet(true)) {
return;
}
mutex.lock();
try {
+ makeRoomForWrite(true);
while (backgroundCompaction != null) {
backgroundCondition.awaitUninterruptibly();
}
} finally {
mutex.unlock();
}
+ compactionExecutor.shutdown();
+ try {
+ compactionExecutor.awaitTermination(1, TimeUnit.DAYS);
+ }
+ catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+
dbLock.release();
}
private void deleteObsoleteFiles()
{
// Make a set of all of the live files
List<Long> live = newArrayList(this.pendingOutputs);
for (FileMetaData fileMetaData : versions.getLiveFiles()) {
live.add(fileMetaData.getNumber());
}
for (File file : Filename.listFiles(databaseDir)) {
FileInfo fileInfo = Filename.parseFileName(file);
long number = fileInfo.getFileNumber();
boolean keep = true;
switch (fileInfo.getFileType()) {
case LOG:
keep = ((number >= versions.getLogNumber()) ||
(number == versions.getPrevLogNumber()));
break;
case DESCRIPTOR:
// Keep my manifest file, and any newer incarnations'
// (in case there is a race that allows other incarnations)
keep = (number >= versions.getManifestFileNumber());
break;
case TABLE:
keep = live.contains(number);
break;
case TEMP:
// Any temp files that are currently being written to must
// be recorded in pending_outputs_, which is inserted into "live"
keep = live.contains(number);
break;
case CURRENT:
case DB_LOCK:
case INFO_LOG:
keep = true;
break;
}
if (!keep) {
if (fileInfo.getFileType() == FileType.TABLE) {
tableCache.evict(number);
}
// todo info logging system needed
// Log(options_.info_log, "Delete type=%d #%lld\n",
// int(type),
// static_cast < unsigned long long>(number));
file.delete();
}
}
}
public void flushMemTable()
{
mutex.lock();
try {
// force compaction
makeRoomForWrite(true);
// todo bg_error code
while(immutableMemTable != null) {
backgroundCondition.awaitUninterruptibly();
}
} finally {
mutex.unlock();
}
}
public void compactRange(int level, ChannelBuffer start, ChannelBuffer end)
{
Preconditions.checkArgument(level >= 0, "level is negative");
Preconditions.checkArgument(level + 1 < NUM_LEVELS, "level is greater than %s", NUM_LEVELS);
Preconditions.checkNotNull(start, "start is null");
Preconditions.checkNotNull(end, "end is null");
mutex.lock();
try {
while (this.manualCompaction != null) {
backgroundCondition.awaitUninterruptibly();
}
ManualCompaction manualCompaction = new ManualCompaction(level, start, end);
this.manualCompaction = manualCompaction;
maybeScheduleCompaction();
while (this.manualCompaction == manualCompaction) {
backgroundCondition.awaitUninterruptibly();
}
}
finally {
mutex.unlock();
}
}
private void maybeScheduleCompaction()
{
Preconditions.checkState(mutex.isHeldByCurrentThread());
if (backgroundCompaction != null) {
// Already scheduled
}
else if (shuttingDown.get()) {
// DB is being shutdown; no more background compactions
}
else if (immutableMemTable == null &&
manualCompaction == null &&
!versions.needsCompaction()) {
// No work to be done
}
else {
backgroundCompaction = compactionExecutor.submit(new Callable<Void>()
{
@Override
public Void call()
throws Exception
{
- backgroundCall();
+ try {
+ backgroundCall();
+ }
+ catch (Throwable e) {
+ // todo add logging system
+ e.printStackTrace();
+ }
return null;
}
});
}
}
private void backgroundCall()
throws IOException
{
mutex.lock();
try {
if (backgroundCompaction == null) {
return;
}
try {
if (!shuttingDown.get()) {
backgroundCompaction();
}
}
finally {
backgroundCompaction = null;
}
// Previous compaction may have produced too many files in a level,
// so reschedule another compaction if needed.
maybeScheduleCompaction();
}
finally {
try {
backgroundCondition.signalAll();
}
finally {
mutex.unlock();
}
}
}
private void backgroundCompaction()
throws IOException
{
Preconditions.checkState(mutex.isHeldByCurrentThread());
if (immutableMemTable != null) {
compactMemTable();
}
Compaction compaction;
if (manualCompaction != null) {
compaction = versions.compactRange(manualCompaction.level,
new InternalKey(manualCompaction.begin, MAX_SEQUENCE_NUMBER, ValueType.VALUE),
new InternalKey(manualCompaction.end, 0, ValueType.DELETION));
} else {
compaction = versions.pickCompaction();
}
if (compaction == null) {
// no compaction
} else if (/* !isManual && */ compaction.isTrivialMove()) {
// Move file to next level
Preconditions.checkState(compaction.getLevelInputs().size() == 1);
FileMetaData fileMetaData = compaction.getLevelInputs().get(0);
compaction.getEdit().deleteFile(compaction.getLevel(), fileMetaData.getNumber());
compaction.getEdit().addFile(compaction.getLevel() + 1, fileMetaData);
versions.logAndApply(compaction.getEdit());
// log
} else {
CompactionState compactionState = new CompactionState(compaction);
doCompactionWork(compactionState);
cleanupCompaction(compactionState);
}
// manual compaction complete
if (manualCompaction != null) {
manualCompaction = null;
}
}
private void cleanupCompaction(CompactionState compactionState)
{
Preconditions.checkState(mutex.isHeldByCurrentThread());
if (compactionState.builder != null) {
compactionState.builder.abandon();
} else {
Preconditions.checkArgument(compactionState.outfile == null);
}
for (FileMetaData output : compactionState.outputs) {
pendingOutputs.remove(output.getNumber());
}
}
private long recoverLogFile(long fileNumber, VersionEdit edit)
{
// todo implement tx log and recovery
throw new UnsupportedOperationException();
}
public ChannelBuffer get(ChannelBuffer key)
{
return get(new ReadOptions(), key);
}
public ChannelBuffer get(ReadOptions options, ChannelBuffer key)
{
LookupKey lookupKey;
mutex.lock();
try {
long snapshot = getSnapshotNumber(options);
lookupKey = new LookupKey(key, snapshot);
// First look in the memtable, then in the immutable memtable (if any).
LookupResult lookupResult = memTable.get(lookupKey);
if (lookupResult != null) {
return lookupResult.getValue();
}
if (immutableMemTable != null) {
lookupResult = immutableMemTable.get(lookupKey);
if (lookupResult != null) {
return lookupResult.getValue();
}
}
}
finally {
mutex.unlock();
}
// Not in memTables; try live files in level order
LookupResult lookupResult = versions.get(lookupKey);
if (lookupResult != null) {
return lookupResult.getValue();
}
// todo schedule compaction
return null;
}
public void put(ChannelBuffer key, ChannelBuffer value)
{
put(new WriteOptions(), key, value);
}
public void put(WriteOptions options, ChannelBuffer key, ChannelBuffer value)
{
write(options, new WriteBatch().put(key, value));
}
public void delete(ChannelBuffer key)
{
write(new WriteOptions(), new WriteBatch().delete(key));
}
public void delete(WriteOptions options, ChannelBuffer key)
{
write(options, new WriteBatch().delete(key));
}
public Snapshot write(WriteOptions options, WriteBatch updates)
{
mutex.lock();
try {
makeRoomForWrite(false);
// Get sequence numbers for this change set
final long sequenceBegin = versions.getLastSequence() + 1;
final long sequenceEnd = sequenceBegin + updates.size() - 1;
// Reserve this sequence in the version set
versions.setLastSequence(sequenceEnd);
// Log write
final ChannelBuffer record = ChannelBuffers.dynamicBuffer();
record.writeLong(sequenceBegin);
record.writeInt(updates.size());
updates.forEach(new Handler()
{
@Override
public void put(ChannelBuffer key, ChannelBuffer value)
{
record.writeByte(VALUE.getPersistentId());
writeLengthPrefixedBytes(record, key.slice());
writeLengthPrefixedBytes(record, value.slice());
}
@Override
public void delete(ChannelBuffer key)
{
record.writeByte(DELETION.getPersistentId());
writeLengthPrefixedBytes(record, key.slice());
}
});
try {
log.addRecord(record);
if (options.isSync()) {
logChannel.force(false);
}
}
catch (IOException e) {
throw Throwables.propagate(e);
}
// Update memtable
final MemTable memTable = this.memTable;
updates.forEach(new Handler()
{
private long sequence = sequenceBegin;
@Override
public void put(ChannelBuffer key, ChannelBuffer value)
{
memTable.add(sequence++, VALUE, key, value);
}
@Override
public void delete(ChannelBuffer key)
{
memTable.add(sequence++, DELETION, key, ChannelBuffers.EMPTY_BUFFER);
}
});
return new SnapshotImpl(sequenceEnd);
}
finally {
mutex.unlock();
}
}
@Override
public SeekingIterator<ChannelBuffer, ChannelBuffer> iterator()
{
return iterator(new ReadOptions());
}
public SeekingIterator<ChannelBuffer, ChannelBuffer> iterator(ReadOptions options)
{
mutex.lock();
try {
// merge together the memTable, immutableMemTable, and tables in version set
ImmutableList.Builder<SeekingIterator<InternalKey, ChannelBuffer>> iterators = ImmutableList.builder();
if (memTable != null && !memTable.isEmpty()) {
iterators.add(memTable.iterator());
}
if (immutableMemTable != null && !immutableMemTable.isEmpty()) {
iterators.add(immutableMemTable.iterator());
}
// todo only add if versions is not empty... makes debugging the iterators easier
iterators.add(versions.iterator());
SeekingIterator<InternalKey, ChannelBuffer> rawIterator = SeekingIterators.merge(iterators.build(), internalKeyComparator);
// filter any entries not visible in our snapshot
long snapshot = getSnapshotNumber(options);
SeekingIterator<InternalKey, ChannelBuffer> snapshotIterator = new SnapshotSeekingIterator(rawIterator, snapshot, internalKeyComparator.getUserComparator());
// transform the keys user space
SeekingIterator<ChannelBuffer, ChannelBuffer> userIterator = SeekingIterators.transformKeys(snapshotIterator,
INTERNAL_KEY_TO_USER_KEY,
createUserKeyToInternalKeyFunction(snapshot));
return userIterator;
}
finally {
mutex.unlock();
}
}
public Snapshot getSnapshot()
{
mutex.lock();
try {
return new SnapshotImpl(versions.getLastSequence());
}
finally {
mutex.unlock();
}
}
private long getSnapshotNumber(ReadOptions options)
{
long snapshot;
if (options.getSnapshot() != null) {
snapshot = ((SnapshotImpl) options.getSnapshot()).snapshot;
}
else {
snapshot = versions.getLastSequence();
}
return snapshot;
}
private void makeRoomForWrite(boolean force)
{
Preconditions.checkState(mutex.isHeldByCurrentThread());
boolean allowDelay = !force;
while (true) {
// todo background processing system need work
// if (!bg_error_.ok()) {
// // Yield previous error
// s = bg_error_;
// break;
// } else
if (allowDelay && versions.numberOfFilesInLevel(0) > L0_SLOWDOWN_WRITES_TRIGGER) {
// We are getting close to hitting a hard limit on the number of
// L0 files. Rather than delaying a single write by several
// seconds when we hit the hard limit, start delaying each
// individual write by 1ms to reduce latency variance. Also,
// this delay hands over some CPU to the compaction thread in
// case it is sharing the same core as the writer.
try {
mutex.unlock();
Thread.sleep(1);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
} finally {
mutex.lock();
}
// Do not delay a single write more than once
allowDelay = false;
}
else if (!force && memTable.approximateMemoryUsage() <= options.getWriteBufferSize()) {
// There is room in current memtable
break;
}
else if (immutableMemTable != null) {
// We have filled up the current memtable, but the previous
// one is still being compacted, so we wait.
backgroundCondition.awaitUninterruptibly();
}
else if (versions.numberOfFilesInLevel(0) >= L0_STOP_WRITES_TRIGGER) {
// There are too many level-0 files.
// Log(options_.info_log, "waiting...\n");
backgroundCondition.awaitUninterruptibly();
}
else {
// Attempt to switch to a new memtable and trigger compaction of old
Preconditions.checkState(versions.getPrevLogNumber() == 0);
// open a new log
long logNumber = versions.getNextFileNumber();
File file = new File(databaseDir, Filename.logFileName(logNumber));
FileChannel channel;
try {
channel = new FileOutputStream(file).getChannel();
}
catch (FileNotFoundException e) {
throw new RuntimeException("Unable to open new log file " + file.getAbsoluteFile(), e);
}
this.log = new LogWriter(channel);
this.logChannel = channel;
this.logFileNumber = logNumber;
// create a new mem table
immutableMemTable = memTable;
memTable = new MemTable(internalKeyComparator);
// Do not force another compaction there is space available
force = false;
maybeScheduleCompaction();
}
}
}
private void compactMemTable()
throws IOException
{
Preconditions.checkState(mutex.isHeldByCurrentThread());
Preconditions.checkState(immutableMemTable != null);
// Save the contents of the memtable as a new Table
VersionEdit edit = new VersionEdit();
Version base = versions.getCurrent();
writeLevel0Table(immutableMemTable, edit, base);
- if (shuttingDown.get()) {
- throw new IOException("Database shutdown during memtable compaction");
- }
+// if (shuttingDown.get()) {
+// throw new IOException("Database shutdown during memtable compaction");
+// }
// Replace immutable memtable with the generated Table
edit.setPreviousLogNumber(0);
edit.setLogNumber(logFileNumber); // Earlier logs no longer needed
versions.logAndApply(edit);
immutableMemTable = null;
deleteObsoleteFiles();
}
private void writeLevel0Table(MemTable memTable, VersionEdit edit, Version base)
throws IOException
{
Preconditions.checkState(mutex.isHeldByCurrentThread());
if (memTable.isEmpty()) {
return;
}
// write the memtable to a new sstable
FileMetaData fileMetaData;
mutex.unlock();
try {
fileMetaData = buildTable(memTable);
}
finally {
mutex.lock();
}
ChannelBuffer minUserKey = fileMetaData.getSmallest().getUserKey();
ChannelBuffer maxUserKey = fileMetaData.getLargest().getUserKey();
int level = 0;
if (base != null && !base.overlapInLevel(0, minUserKey, maxUserKey)) {
// Push the new sstable to a higher level if possible to reduce
// expensive manifest file ops.
while (level < MAX_MEM_COMPACT_LEVEL && !base.overlapInLevel(level + 1, minUserKey, maxUserKey)) {
level++;
}
}
edit.addFile(level, fileMetaData);
}
private FileMetaData buildTable(SeekingIterable<InternalKey, ChannelBuffer> data)
throws IOException
{
long fileNumber = versions.getNextFileNumber();
pendingOutputs.add(fileNumber);
File file = new File(databaseDir, Filename.tableFileName(fileNumber));
try {
FileChannel channel = new FileOutputStream(file).getChannel();
TableBuilder tableBuilder = new TableBuilder(options, channel, new InternalUserComparator(internalKeyComparator));
InternalKey smallest = null;
InternalKey largest = null;
for (Entry<InternalKey, ChannelBuffer> entry : data) {
// update keys
InternalKey key = entry.getKey();
if (smallest == null) {
smallest = key;
}
largest = key;
tableBuilder.add(key.encode(), entry.getValue());
}
tableBuilder.finish();
channel.force(true);
channel.close();
if (smallest == null) {
return null;
}
FileMetaData fileMetaData = new FileMetaData(fileNumber, file.length(), smallest, largest);
// verify table can be opened
tableCache.newIterator(fileMetaData);
pendingOutputs.remove(fileNumber);
return fileMetaData;
}
catch (IOException e) {
file.delete();
throw e;
}
}
private void doCompactionWork(CompactionState compactionState)
throws IOException
{
Preconditions.checkState(mutex.isHeldByCurrentThread());
Preconditions.checkArgument(versions.numberOfBytesInLevel(compactionState.getCompaction().getLevel()) > 0);
Preconditions.checkArgument(compactionState.builder == null);
Preconditions.checkArgument(compactionState.outfile == null);
// todo track snapshots
compactionState.smallestSnapshot = versions.getLastSequence();
// Release mutex while we're actually doing the compaction work
mutex.unlock();
try {
SeekingIterator<InternalKey, ChannelBuffer> iterator = versions.makeInputIterator(compactionState.compaction);
ChannelBuffer currentUserKey = null;
boolean hasCurrentUserKey = false;
long lastSequenceForKey = MAX_SEQUENCE_NUMBER;
while (iterator.hasNext() && !shuttingDown.get()) {
// always give priority to compacting the current mem table
if (immutableMemTable != null) {
mutex.lock();
try {
compactMemTable();
}
finally {
try {
backgroundCondition.signalAll();
}
finally {
mutex.unlock();
}
}
}
InternalKey key = iterator.peek().getKey();
if (compactionState.compaction.shouldStopBefore(key) && compactionState.builder != null) {
finishCompactionOutputFile(compactionState, iterator);
}
// Handle key/value, add to state, etc.
boolean drop = false;
// todo if key doesn't parse (it is corrupted),
if (false /*!ParseInternalKey(key, &ikey)*/) {
// do not hide error keys
currentUserKey = null;
hasCurrentUserKey = false;
lastSequenceForKey = MAX_SEQUENCE_NUMBER;
}
else {
if (!hasCurrentUserKey || internalKeyComparator.getUserComparator().compare(key.getUserKey(), currentUserKey) != 0) {
// First occurrence of this user key
currentUserKey = key.getUserKey();
hasCurrentUserKey = true;
lastSequenceForKey = MAX_SEQUENCE_NUMBER;
}
if (lastSequenceForKey <= compactionState.smallestSnapshot) {
// Hidden by an newer entry for same user key
drop = true; // (A)
}
else if (key.getValueType() == ValueType.DELETION &&
key.getSequenceNumber() <= compactionState.smallestSnapshot &&
compactionState.compaction.isBaseLevelForKey(key.getUserKey())) {
// For this user key:
// (1) there is no data in higher levels
// (2) data in lower levels will have larger sequence numbers
// (3) data in layers that are being compacted here and have
// smaller sequence numbers will be dropped in the next
// few iterations of this loop (by rule (A) above).
// Therefore this deletion marker is obsolete and can be dropped.
drop = true;
}
lastSequenceForKey = key.getSequenceNumber();
}
if (!drop) {
// Open output file if necessary
if (compactionState.builder == null) {
openCompactionOutputFile(compactionState);
}
if (compactionState.builder.getEntryCount() == 0) {
compactionState.currentSmallest = key;
}
compactionState.currentLargest = key;
compactionState.builder.add(key.encode(), iterator.peek().getValue());
// Close output file if it is big enough
if (compactionState.builder.getFileSize() >=
compactionState.compaction.MaxOutputFileSize()) {
finishCompactionOutputFile(compactionState, iterator);
}
}
iterator.next();
}
- if (shuttingDown.get()) {
- throw new IOException("DB shutdown during compaction");
- }
+// if (shuttingDown.get()) {
+// throw new IOException("DB shutdown during compaction");
+// }
if (compactionState.builder != null) {
finishCompactionOutputFile(compactionState, iterator);
}
}
finally {
mutex.lock();
}
// todo port CompactionStats code
installCompactionResults(compactionState);
}
private void openCompactionOutputFile(CompactionState compactionState)
throws FileNotFoundException
{
Preconditions.checkNotNull(compactionState, "compactionState is null");
Preconditions.checkArgument(compactionState.builder == null, "compactionState builder is not null");
mutex.lock();
try {
long fileNumber = versions.getNextFileNumber();
pendingOutputs.add(fileNumber);
compactionState.currentFileNumber = fileNumber;
compactionState.currentFileSize = 0;
compactionState.currentSmallest = null;
compactionState.currentLargest = null;
File file = new File(databaseDir, Filename.tableFileName(fileNumber));
compactionState.outfile = new FileOutputStream(file).getChannel();
compactionState.builder = new TableBuilder(options, compactionState.outfile, internalKeyComparator.getUserComparator());
}
finally {
mutex.unlock();
}
}
private void finishCompactionOutputFile(CompactionState compactionState, SeekingIterator<InternalKey, ChannelBuffer> input)
throws IOException
{
Preconditions.checkNotNull(compactionState, "compactionState is null");
Preconditions.checkArgument(compactionState.outfile != null);
Preconditions.checkArgument(compactionState.builder != null);
long outputNumber = compactionState.currentFileNumber;
Preconditions.checkArgument(outputNumber != 0);
long currentEntries = compactionState.builder.getEntryCount();
compactionState.builder.finish();
long currentBytes = compactionState.builder.getFileSize();
compactionState.currentFileSize = currentBytes;
compactionState.totalBytes += currentBytes;
FileMetaData currentFileMetaData = new FileMetaData(compactionState.currentFileNumber,
compactionState.currentFileSize,
compactionState.currentSmallest,
compactionState.currentLargest);
compactionState.outputs.add(currentFileMetaData);
compactionState.builder = null;
compactionState.outfile.force(true);
compactionState.outfile.close();
compactionState.outfile = null;
if (currentEntries > 0) {
// Verify that the table is usable
tableCache.newIterator(outputNumber);
}
}
private void installCompactionResults(CompactionState compact)
throws IOException
{
Preconditions.checkState(mutex.isHeldByCurrentThread());
// Add compaction outputs
compact.compaction.addInputDeletions(compact.compaction.getEdit());
int level = compact.compaction.getLevel();
for (FileMetaData output : compact.outputs) {
compact.compaction.getEdit().addFile(level + 1, output);
pendingOutputs.remove(output.getNumber());
}
compact.outputs.clear();
try {
versions.logAndApply(compact.compaction.getEdit());
deleteObsoleteFiles();
}
catch (IOException e) {
// Discard any files we may have created during this failed compaction
for (FileMetaData output : compact.outputs) {
new File(databaseDir, Filename.tableFileName(output.getNumber())).delete();
}
}
}
int numberOfFilesInLevel(int level)
{
return versions.getCurrent().numberOfFilesInLevel(level);
}
private static class CompactionState
{
private final Compaction compaction;
private final List<FileMetaData> outputs = newArrayList();
private long smallestSnapshot;
// State kept for output being generated
private FileChannel outfile;
private TableBuilder builder;
// Current file being generated
private long currentFileNumber;
private long currentFileSize;
private InternalKey currentSmallest;
private InternalKey currentLargest;
private long totalBytes;
private CompactionState(Compaction compaction)
{
this.compaction = compaction;
}
public Compaction getCompaction()
{
return compaction;
}
}
private static class ManualCompaction
{
private final int level;
private final ChannelBuffer begin;
private final ChannelBuffer end;
private ManualCompaction(int level, ChannelBuffer begin, ChannelBuffer end)
{
this.level = level;
this.begin = begin;
this.end = end;
}
}
}
| false | false | null | null |
diff --git a/spring-mvc-cache-control/src/main/java/net/rossillo/spring/web/mvc/CacheControlHandlerInterceptor.java b/spring-mvc-cache-control/src/main/java/net/rossillo/spring/web/mvc/CacheControlHandlerInterceptor.java
index 70151c3..5b8be21 100644
--- a/spring-mvc-cache-control/src/main/java/net/rossillo/spring/web/mvc/CacheControlHandlerInterceptor.java
+++ b/spring-mvc-cache-control/src/main/java/net/rossillo/spring/web/mvc/CacheControlHandlerInterceptor.java
@@ -1,168 +1,172 @@
package net.rossillo.spring.web.mvc;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
/**
* Provides a cache control handler interceptor to assign cache-control
* headers to HTTP responses.
*
* @author Scott Rossillo
*
*/
public class CacheControlHandlerInterceptor extends HandlerInterceptorAdapter implements HandlerInterceptor {
private static final String HEADER_EXPIRES = "Expires";
private static final String HEADER_CACHE_CONTROL = "Cache-Control";
private boolean useExpiresHeader = true;
/**
* Creates a new cache control handler interceptor.
*/
public CacheControlHandlerInterceptor() {
super();
}
/**
* Assigns a <code>CacheControl</code> header to the given <code>response</code>.
*
* @param request the <code>HttpServletRequest</code>
* @param response the <code>HttpServletResponse</code>
* @param handler the handler for the given <code>request</code>
*/
protected final void assignCacheControlHeader(
final HttpServletRequest request,
final HttpServletResponse response,
final Object handler) {
final CacheControl cacheControl = this.getCacheControl(request, response, handler);
final String cacheControlHeader = this.createCacheControlHeader(cacheControl);
if (cacheControlHeader != null) {
response.setHeader(HEADER_CACHE_CONTROL, cacheControlHeader);
if (useExpiresHeader) {
response.setDateHeader(HEADER_EXPIRES, createExpiresHeader(cacheControl));
}
}
}
/**
* Returns cache control header value from the given {@link CacheControl}
* annotation.
*
* @param cacheControl the <code>CacheControl</code> annotation from which to
* create the returned cache control header value
*
* @return the cache control header value
*/
protected final String createCacheControlHeader(final CacheControl cacheControl) {
final StringBuilder builder = new StringBuilder();
if (cacheControl == null) {
return null;
}
final CachePolicy[] policies = cacheControl.policy();
if (cacheControl.maxAge() >= 0) {
builder.append("max-age=").append(cacheControl.maxAge());
}
if (cacheControl.sharedMaxAge() >= 0) {
if (builder.length() > 0) {
builder.append(", ");
}
builder.append("s-maxage=").append(cacheControl.sharedMaxAge());
}
if (policies != null) {
for (final CachePolicy policy : policies) {
if (builder.length() > 0) {
builder.append(", ");
}
builder.append(policy.policy());
}
}
return (builder.length() > 0 ? builder.toString() : null);
}
/**
* Returns an expires header value generated from the given
* {@link CacheControl} annotation.
*
* @param cacheControl the <code>CacheControl</code> annotation from which to
* create the returned expires header value
*
* @return the expires header value
*/
protected final long createExpiresHeader(final CacheControl cacheControl) {
- Calendar expires = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
+ final Calendar expires = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
if (cacheControl.maxAge() >= 0) {
expires.add(Calendar.SECOND, cacheControl.maxAge());
}
return expires.getTime().getTime();
}
/**
* Returns the {@link CacheControl} annotation specified for the
* given request, response and handler.
*
* @param request the current <code>HttpServletRequest</code>
* @param response the current <code>HttpServletResponse</code>
* @param handler the current request handler
*
* @return the <code>CacheControl</code> annotation specified by
* the given <code>handler</code> if present; <code>null</code> otherwise
*/
protected final CacheControl getCacheControl(
final HttpServletRequest request,
final HttpServletResponse response,
final Object handler) {
if (handler == null || !(handler instanceof HandlerMethod)) {
return null;
}
final HandlerMethod handlerMethod = (HandlerMethod) handler;
- final CacheControl cacheControl = handlerMethod.getMethodAnnotation(CacheControl.class);
+ CacheControl cacheControl = handlerMethod.getMethodAnnotation(CacheControl.class);
+
+ if (cacheControl == null) {
+ return handlerMethod.getBeanType().getAnnotation(CacheControl.class);
+ }
return cacheControl;
}
@Override
public final boolean preHandle(
final HttpServletRequest request,
final HttpServletResponse response,
final Object handler) throws Exception {
this.assignCacheControlHeader(request, response, handler);
return super.preHandle(request, response, handler);
}
/**
* True to set an expires header when a {@link CacheControl} annotation is present
* on a handler; false otherwise. Defaults to true.
*
* @param useExpiresHeader <code>true</code> to set an expires header when a
* <code>CacheControl</code> annotation is present on a handler; <code>false</code> otherwise
*/
public final void setUseExpiresHeader(final boolean useExpiresHeader) {
this.useExpiresHeader = useExpiresHeader;
}
}
diff --git a/spring-mvc-cache-control/src/test/java/net/rossillo/spring/web/mvc/CacheControlAnnotatedTestController.java b/spring-mvc-cache-control/src/test/java/net/rossillo/spring/web/mvc/CacheControlAnnotatedTestController.java
index 0dc7b95..c129961 100644
--- a/spring-mvc-cache-control/src/test/java/net/rossillo/spring/web/mvc/CacheControlAnnotatedTestController.java
+++ b/spring-mvc-cache-control/src/test/java/net/rossillo/spring/web/mvc/CacheControlAnnotatedTestController.java
@@ -1,29 +1,33 @@
package net.rossillo.spring.web.mvc;
import org.springframework.stereotype.Controller;
@CacheControl(policy = CachePolicy.PRIVATE)
@Controller
final class CacheControlAnnotatedTestController {
@CacheControl(policy = CachePolicy.PUBLIC, maxAge = 60)
public String handlePubliclyCachedPageRequest() {
return null;
}
@CacheControl(policy = { CachePolicy.MUST_REVALIDATE }, maxAge = 300)
public String handlePubliclyCachedPageAndRevalidatedRequest() {
return null;
}
@CacheControl(policy = { CachePolicy.PUBLIC, CachePolicy.PROXY_REVALIDATE }, maxAge = 60)
public String handlePubliclyCachedPageAndProxyRevalidatedRequest() {
return null;
}
@CacheControl(policy = CachePolicy.PRIVATE, maxAge = 360)
public String handlePrivatelyCachedPageRequest() {
return null;
}
+ public String handleWithDefaultPolicy() {
+ return null;
+ }
+
}
diff --git a/spring-mvc-cache-control/src/test/java/net/rossillo/spring/web/mvc/CacheControlHandlerInterceptorTest.java b/spring-mvc-cache-control/src/test/java/net/rossillo/spring/web/mvc/CacheControlHandlerInterceptorTest.java
index 2ca106e..0d86863 100644
--- a/spring-mvc-cache-control/src/test/java/net/rossillo/spring/web/mvc/CacheControlHandlerInterceptorTest.java
+++ b/spring-mvc-cache-control/src/test/java/net/rossillo/spring/web/mvc/CacheControlHandlerInterceptorTest.java
@@ -1,123 +1,133 @@
package net.rossillo.spring.web.mvc;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.web.method.HandlerMethod;
/**
* Provides cache control interceptor tests.
*
* @author Scott Rossillo
*
*/
public final class CacheControlHandlerInterceptorTest {
private CacheControlHandlerInterceptor interceptor;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private final CacheControlAnnotatedTestController controller = new CacheControlAnnotatedTestController();
@Before
public void setUp() {
interceptor = new CacheControlHandlerInterceptor();
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
}
@Test
public void testCacheControlPublic() throws Exception {
final HandlerMethod handler = new HandlerMethod(
controller,
controller.getClass().getMethod("handlePubliclyCachedPageRequest"));
interceptor.preHandle(request, response, handler);
System.err.println("CC: " + response.getHeader("Cache-Control"));
assertNotNull(response.getHeader("Cache-Control"));
assertTrue(response.getHeader("Cache-Control").contains("public"));
assertFalse(response.getHeader("Cache-Control").contains("private"));
}
@Test
public void testCacheControlPublicProxyMustRevalidate() throws Exception {
final HandlerMethod handler = new HandlerMethod(
controller,
controller.getClass().getMethod("handlePubliclyCachedPageAndProxyRevalidatedRequest"));
interceptor.preHandle(request, response, handler);
System.err.println("CC: " + response.getHeader("Cache-Control"));
assertNotNull(response.getHeader("Cache-Control"));
assertTrue(response.getHeader("Cache-Control").contains("public"));
assertTrue(response.getHeader("Cache-Control").contains("proxy-revalidate"));
assertFalse(response.getHeader("Cache-Control").contains("private"));
}
@Test
public void testCacheControlMustRevalidate() throws Exception {
final HandlerMethod handler = new HandlerMethod(
controller,
controller.getClass().getMethod("handlePubliclyCachedPageAndRevalidatedRequest"));
interceptor.preHandle(request, response, handler);
System.err.println("CC: " + response.getHeader("Cache-Control"));
assertNotNull(response.getHeader("Cache-Control"));
assertTrue(response.getHeader("Cache-Control").contains("must-revalidate"));
assertFalse(response.getHeader("Cache-Control").contains("private"));
}
@Test
public void testCacheControlPrivate() throws Exception {
final HandlerMethod handler = new HandlerMethod(
controller,
controller.getClass().getMethod("handlePrivatelyCachedPageRequest"));
interceptor.preHandle(request, response, handler);
System.err.println("CC: " + response.getHeader("Cache-Control"));
assertNotNull(response.getHeader("Cache-Control"));
assertTrue(response.getHeader("Cache-Control").contains("private"));
assertFalse(response.getHeader("Cache-Control").contains("public"));
}
@Test
public void testExpires() throws Exception {
final HandlerMethod handler = new HandlerMethod(
controller,
controller.getClass().getMethod("handlePrivatelyCachedPageRequest"));
interceptor.preHandle(request, response, handler);
assertNotNull(response.getHeader("Expires"));
}
@Test
public void testNoExpires() throws Exception {
final HandlerMethod handler = new HandlerMethod(
controller,
controller.getClass().getMethod("handlePrivatelyCachedPageRequest"));
interceptor.setUseExpiresHeader(false);
interceptor.preHandle(request, response, handler);
assertFalse(response.containsHeader("Expires"));
}
+
+ @Test
+ public void testHandleWithDefaultPolicy() throws Exception {
+
+ final HandlerMethod handler = new HandlerMethod(
+ controller,
+ controller.getClass().getMethod("handleWithDefaultPolicy"));
+
+ assertNotNull(interceptor.getCacheControl(null, null, handler));
+ }
}
| false | false | null | null |
diff --git a/src/net/kevxu/senselib/LocationService.java b/src/net/kevxu/senselib/LocationService.java
index 75e32b5..a0201d0 100644
--- a/src/net/kevxu/senselib/LocationService.java
+++ b/src/net/kevxu/senselib/LocationService.java
@@ -1,291 +1,291 @@
package net.kevxu.senselib;
import java.util.ArrayList;
import java.util.List;
import net.kevxu.senselib.StepDetector.StepListener;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
/**
* Class for providing location information. start() and stop() must be
* explicitly called to start and stop the internal thread.
*
* @author Kaiwen Xu
*/
public class LocationService extends SensorService implements LocationListener, StepListener {
private static final String TAG = "LocationService";
public static int LEVEL_GPS_NOT_ENABLED = 0;
public static int LEVEL_GPS_ENABLED = 1;
// Average step distance for human (in meters)
private static final float CONSTANT_AVERAGE_STEP_DISTANCE = 0.7874F;
- // Average step time for human (in meters)
+ // Average step time for human (in milliseconds)
private static final long CONSTANT_AVERGAE_STEP_TIME = 500L;
private static final int GPS_UPDATE_MULTIPLIER = 1;
private static final long GPS_UPDATE_MIN_TIME = CONSTANT_AVERGAE_STEP_TIME * GPS_UPDATE_MULTIPLIER;
private static final float GPS_UPDATE_MIN_DISTANCE = CONSTANT_AVERAGE_STEP_DISTANCE * GPS_UPDATE_MULTIPLIER;
private Context mContext;
private LocationManager mLocationManager;
private List<LocationServiceListener> mLocationServiceListeners;
private StepDetector mStepDetector;
private LocationServiceFusionThread mLocationServiceFusionThread;
private volatile int mServiceLevel;
public interface LocationServiceListener {
/**
* Called when service level changed. Service level includes
* LocationService.LEVEL_*.
*
* @param level
* Service level.
*/
public void onServiceLevelChanged(int level);
public void onLocationChanged(Location location);
}
protected LocationService(Context context, StepDetector stepDetector) throws SensorNotAvailableException {
this(context, stepDetector, null);
}
protected LocationService(Context context, StepDetector stepDetector, LocationServiceListener locationServiceListener) throws SensorNotAvailableException {
mContext = context;
mLocationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
mLocationServiceListeners = new ArrayList<LocationServiceListener>();
if (locationServiceListener != null) {
mLocationServiceListeners.add(locationServiceListener);
}
mStepDetector = stepDetector;
mStepDetector.addListener(this);
}
/**
* Call this when start or resume.
*/
@Override
protected void start() {
if (mLocationServiceFusionThread == null) {
mLocationServiceFusionThread = new LocationServiceFusionThread();
mLocationServiceFusionThread.start();
Log.i(TAG, "LocationServiceFusionThread started.");
}
if (mLocationManager == null) {
mLocationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
}
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
GPS_UPDATE_MIN_TIME, GPS_UPDATE_MIN_DISTANCE, this);
Log.i(TAG, "GPS update registered.");
Log.i(TAG, "LocationService started.");
}
/**
* Call this when pause.
*/
@Override
protected void stop() {
mLocationServiceFusionThread.terminate();
Log.i(TAG, "Waiting for LocationServiceFusionThread to stop.");
try {
mLocationServiceFusionThread.join();
} catch (InterruptedException e) {
Log.w(TAG, e.getMessage(), e);
}
Log.i(TAG, "LocationServiceFusionThread stoppped.");
mLocationServiceFusionThread = null;
mLocationManager.removeUpdates(this);
Log.i(TAG, "GPS update unregistered.");
Log.i(TAG, "LocationService stopped.");
}
private final class LocationServiceFusionThread extends AbstractSensorWorkerThread {
private static final float ACCEPTABLE_ACCURACY = 15.0F;
// Variables for accepting data from outside
private Location gpsLocation;
private float[] aiwcs;
private volatile long steps = 0;
// Internal data
private boolean initialFix = false;
private Location locationFix;
private long previousSteps = 0;
public LocationServiceFusionThread() {
this(DEFAULT_INTERVAL);
}
public LocationServiceFusionThread(long interval) {
super(interval);
aiwcs = new float[3];
}
public synchronized void pushGPSLocation(Location location) {
if (gpsLocation == null) {
gpsLocation = new Location(location);
} else {
gpsLocation.set(location);
}
// Debug
for (LocationServiceListener listener : mLocationServiceListeners) {
listener.onLocationChanged(gpsLocation);
}
}
private synchronized Location getGPSLocation() {
return gpsLocation;
}
public synchronized void pushStep(float[] aiwcs) {
steps++;
System.arraycopy(aiwcs, 0, this.aiwcs, 0, 3);
}
@Override
public void run() {
while (!isTerminated()) {
Location currentLocation = getGPSLocation();
if (currentLocation != null && currentLocation.hasAccuracy() && currentLocation.getAccuracy() <= ACCEPTABLE_ACCURACY) {
if (initialFix && locationFix != null && steps - previousSteps > 0) {
long stepsWalked = steps - previousSteps;
float distanceWalked = stepsWalked * CONSTANT_AVERAGE_STEP_DISTANCE;
if (distanceWalked >= locationFix.getAccuracy()) {
// Walk out of current location accuracy range
previousSteps = steps;
locationFix.set(currentLocation);
setLocation(locationFix);
}
}
if (!initialFix && locationFix == null) {
locationFix = new Location(currentLocation);
initialFix = true;
previousSteps = steps;
setLocation(locationFix);
} else if (!initialFix) {
locationFix.set(currentLocation);
initialFix = true;
previousSteps = steps;
setLocation(locationFix);
}
}
try {
Thread.sleep(getInterval());
} catch (InterruptedException e) {
Log.w(TAG, e.getMessage(), e);
}
}
}
}
public LocationService addListener(LocationServiceListener locationServiceListener) {
if (locationServiceListener != null) {
mLocationServiceListeners.add(locationServiceListener);
return this;
} else {
throw new NullPointerException("LocationServiceListener is null.");
}
}
protected LocationService removeListeners() {
mLocationServiceListeners.clear();
return this;
}
private synchronized void setServiceLevel(int serviceLevel) {
if (serviceLevel != mServiceLevel) {
mServiceLevel = serviceLevel;
for (LocationServiceListener listener : mLocationServiceListeners) {
listener.onServiceLevelChanged(mServiceLevel);
}
}
}
private synchronized void setLocation(Location location) {
if (location != null) {
for (LocationServiceListener listener : mLocationServiceListeners) {
listener.onLocationChanged(location);
}
}
}
@Override
public void onLocationChanged(Location location) {
synchronized (this) {
mLocationServiceFusionThread.pushGPSLocation(location);
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
synchronized (this) {
if (provider.equals(LocationManager.GPS_PROVIDER)) {
Log.i(TAG, "GPS enabled.");
setServiceLevel(LEVEL_GPS_ENABLED);
}
}
}
@Override
public void onProviderDisabled(String provider) {
synchronized (this) {
if (provider.equals(LocationManager.GPS_PROVIDER)) {
Log.i(TAG, "GPS disabled.");
setServiceLevel(LEVEL_GPS_NOT_ENABLED);
}
}
}
@Override
public void onStep(float[] values) {
synchronized (this) {
mLocationServiceFusionThread.pushStep(values);
}
}
@Override
public void onMovement(float[] values) {
// Not used
}
}
| true | false | null | null |
diff --git a/products/federation/openfm/source/com/sun/identity/wss/trust/wst10/RequestSecurityToken_Impl.java b/products/federation/openfm/source/com/sun/identity/wss/trust/wst10/RequestSecurityToken_Impl.java
index f1087caf3..4c1958741 100644
--- a/products/federation/openfm/source/com/sun/identity/wss/trust/wst10/RequestSecurityToken_Impl.java
+++ b/products/federation/openfm/source/com/sun/identity/wss/trust/wst10/RequestSecurityToken_Impl.java
@@ -1,160 +1,161 @@
/**
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2008 Sun Microsystems Inc. All Rights Reserved
*
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (the License). You may not use this file except in
* compliance with the License.
*
* You can obtain a copy of the License at
* https://opensso.dev.java.net/public/CDDLv1.0.html or
* opensso/legal/CDDLv1.0.txt
* See the License for the specific language governing
* permission and limitations under the License.
*
* When distributing Covered Code, include this CDDL
* Header Notice in each file and include the License file
* at opensso/legal/CDDLv1.0.txt.
* If applicable, add the following below the CDDL Header,
* with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
- * $Id: RequestSecurityToken_Impl.java,v 1.1 2008-09-19 16:00:57 mallas Exp $
+ * $Id: RequestSecurityToken_Impl.java,v 1.2 2008-10-01 23:39:07 mallas Exp $
*
*/
package com.sun.identity.wss.trust.wst10;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import com.sun.identity.wss.trust.RequestSecurityToken;
import com.sun.identity.wss.trust.WSTException;
import com.sun.identity.wss.sts.STSConstants;
import com.sun.identity.wss.sts.STSUtils;
import com.sun.identity.shared.xml.XMLUtils;
public class RequestSecurityToken_Impl extends RequestSecurityToken {
private Element rstE = null;
public RequestSecurityToken_Impl() {
// Constructor
}
public RequestSecurityToken_Impl(Element element) throws WSTException {
//TODO Schema checking
if(element == null) {
throw new WSTException("NullElement");
}
if(!REQUEST_SECURITY_TOKEN.equals(element.getLocalName())) {
throw new WSTException("InvalidElement");
}
if(!STSConstants.WST10_NAMESPACE.equals(element.getNamespaceURI())) {
throw new WSTException("InvalidNameSpace");
}
this.rstE = element;
NodeList nl = element.getChildNodes();
for (int i=0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if(node.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
Element child = (Element)node;
String localName = child.getLocalName();
if(TOKEN_TYPE.equals(localName)) {
tokenType = XMLUtils.getElementValue(child);
} else if(REQUEST_TYPE.equals(localName)) {
requestType = XMLUtils.getElementValue(child);
} else if(APPLIES_TO.equals(localName)) {
appliesTo = STSUtils.getAppliesTo(child);
} else if(ON_BEHALF_OF.equals(localName)) {
oboToken = (Element)child.getFirstChild();
} else if(KEY_TYPE.equals(localName)) {
keyType = XMLUtils.getElementValue(child);
}
}
}
public Element toDOMElement() throws WSTException {
if(rstE != null) {
return rstE;
}
return XMLUtils.toDOMDocument(
toXMLString(), STSUtils.debug).getDocumentElement();
}
public String toXMLString() throws WSTException {
StringBuffer sb = new StringBuffer(300);
sb.append("<").append(STSConstants.WST_PREFIX)
.append(REQUEST_SECURITY_TOKEN).append(" ")
.append(STSConstants.WST_XMLNS).append("=\"")
.append(STSConstants.WST10_NAMESPACE).append("\"")
.append(" ").append(STSConstants.WSP_XMLNS).append("=")
.append("\"").append(STSConstants.WSP_NS).append("\"")
.append(" ").append(STSConstants.WSA_XMLNS).append("=")
.append("\"").append(STSConstants.WSA_NS).append("\"")
.append(">");
if(tokenType != null) {
sb.append("<").append(STSConstants.WST_PREFIX).append(TOKEN_TYPE)
.append(">").append(tokenType).append("</")
+ .append(STSConstants.WST_PREFIX)
.append(TOKEN_TYPE).append(">");
}
if(requestType == null || requestType.length() == 0) {
throw new WSTException("RequestType is null");
}
sb.append("<").append(STSConstants.WST_PREFIX).append(REQUEST_TYPE)
.append(">").append(requestType).append("</")
.append(STSConstants.WST_PREFIX)
.append(REQUEST_TYPE).append(">");
if(appliesTo != null) {
sb.append("<").append(STSConstants.WSP_PREFIX)
.append(APPLIES_TO).append(">")
.append("<").append(STSConstants.WSA_PREFIX)
.append(EP_REFERENCE).append(">").append("<")
.append(STSConstants.WSA_PREFIX)
.append(ADDRESS).append(">").append(appliesTo)
.append("</").append(STSConstants.WSA_PREFIX)
.append(ADDRESS).append(">")
.append("</").append(STSConstants.WSA_PREFIX)
.append(EP_REFERENCE).append(">")
.append("</").append(STSConstants.WSP_PREFIX)
.append(APPLIES_TO).append(">");
}
if(oboToken != null) {
sb.append("<").append(STSConstants.WST_PREFIX)
.append(ON_BEHALF_OF).append(">")
.append(XMLUtils.print(oboToken)).append("</")
.append(STSConstants.WST_PREFIX)
.append(ON_BEHALF_OF).append(">");
}
if(keyType != null) {
sb.append("<").append(STSConstants.WST_PREFIX)
.append(KEY_TYPE).append(">")
.append(keyType).append("</")
.append(STSConstants.WST_PREFIX)
.append(KEY_TYPE).append(">");
}
sb.append("</").append(STSConstants.WST_PREFIX)
.append(REQUEST_SECURITY_TOKEN).append(">");
return sb.toString();
}
}
diff --git a/products/federation/openfm/source/com/sun/identity/wss/trust/wst13/RequestSecurityToken_Impl.java b/products/federation/openfm/source/com/sun/identity/wss/trust/wst13/RequestSecurityToken_Impl.java
index c95ae8af8..44a5cb47b 100644
--- a/products/federation/openfm/source/com/sun/identity/wss/trust/wst13/RequestSecurityToken_Impl.java
+++ b/products/federation/openfm/source/com/sun/identity/wss/trust/wst13/RequestSecurityToken_Impl.java
@@ -1,161 +1,162 @@
/**
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2008 Sun Microsystems Inc. All Rights Reserved
*
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (the License). You may not use this file except in
* compliance with the License.
*
* You can obtain a copy of the License at
* https://opensso.dev.java.net/public/CDDLv1.0.html or
* opensso/legal/CDDLv1.0.txt
* See the License for the specific language governing
* permission and limitations under the License.
*
* When distributing Covered Code, include this CDDL
* Header Notice in each file and include the License file
* at opensso/legal/CDDLv1.0.txt.
* If applicable, add the following below the CDDL Header,
* with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
- * $Id: RequestSecurityToken_Impl.java,v 1.1 2008-09-19 16:00:57 mallas Exp $
+ * $Id: RequestSecurityToken_Impl.java,v 1.2 2008-10-01 23:39:08 mallas Exp $
*
*/
package com.sun.identity.wss.trust.wst13;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import com.sun.identity.wss.trust.RequestSecurityToken;
import com.sun.identity.wss.trust.WSTException;
import com.sun.identity.wss.sts.STSConstants;
import com.sun.identity.wss.sts.STSUtils;
import com.sun.identity.shared.xml.XMLUtils;
public class RequestSecurityToken_Impl extends RequestSecurityToken {
private Element rstE = null;
public RequestSecurityToken_Impl() {
// Constructor
}
public RequestSecurityToken_Impl(Element element) throws WSTException {
//TODO Schema checking
if(element == null) {
throw new WSTException("NullElement");
}
if(!REQUEST_SECURITY_TOKEN.equals(element.getLocalName())) {
throw new WSTException("InvalidElement");
}
if(!STSConstants.WST13_NAMESPACE.equals(element.getNamespaceURI())) {
throw new WSTException("InvalidNameSpace");
}
this.rstE = element;
NodeList nl = element.getChildNodes();
for (int i=0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if(node.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
Element child = (Element)node;
String localName = child.getLocalName();
if(TOKEN_TYPE.equals(localName)) {
tokenType = XMLUtils.getElementValue(child);
} else if(REQUEST_TYPE.equals(localName)) {
requestType = XMLUtils.getElementValue(child);
} else if(APPLIES_TO.equals(localName)) {
appliesTo = STSUtils.getAppliesTo(child);
} else if(ON_BEHALF_OF.equals(localName)) {
oboToken = (Element)child.getFirstChild();
} else if(KEY_TYPE.equals(localName)) {
keyType = XMLUtils.getElementValue(child);
}
}
}
public Element toDOMElement() throws WSTException {
if(rstE != null) {
return rstE;
}
return XMLUtils.toDOMDocument(
toXMLString(), STSUtils.debug).getDocumentElement();
}
public String toXMLString() throws WSTException {
StringBuffer sb = new StringBuffer(300);
sb.append("<").append(STSConstants.WST_PREFIX)
.append(REQUEST_SECURITY_TOKEN).append(" ")
.append(STSConstants.WST_XMLNS).append("=\"")
.append(STSConstants.WST13_NAMESPACE).append("\"")
.append(" ").append(STSConstants.WSP_XMLNS).append("=")
.append("\"").append(STSConstants.WSP_NS).append("\"")
.append(" ").append(STSConstants.WSA_XMLNS).append("=")
.append("\"").append(STSConstants.WSA_NS).append("\"")
.append(">");
if(tokenType != null) {
sb.append("<").append(STSConstants.WST_PREFIX).append(TOKEN_TYPE)
.append(">").append(tokenType).append("</")
+ .append(STSConstants.WST_PREFIX)
.append(TOKEN_TYPE).append(">");
}
if(requestType == null || requestType.length() == 0) {
throw new WSTException("RequestType is null");
}
sb.append("<").append(STSConstants.WST_PREFIX).append(REQUEST_TYPE)
.append(">").append(requestType).append("</")
.append(STSConstants.WST_PREFIX)
.append(REQUEST_TYPE).append(">");
if(appliesTo != null) {
sb.append("<").append(STSConstants.WSP_PREFIX)
.append(APPLIES_TO).append(">")
.append("<").append(STSConstants.WSA_PREFIX)
.append(EP_REFERENCE).append(">").append("<")
.append(STSConstants.WSA_PREFIX)
.append(ADDRESS).append(">").append(appliesTo)
.append("</").append(STSConstants.WSA_PREFIX)
.append(ADDRESS).append(">")
.append("</").append(STSConstants.WSA_PREFIX)
.append(EP_REFERENCE).append(">")
.append("</").append(STSConstants.WSP_PREFIX)
.append(APPLIES_TO).append(">");
}
if(oboToken != null) {
sb.append("<").append(STSConstants.WST_PREFIX)
.append(ON_BEHALF_OF).append(">")
.append(XMLUtils.print(oboToken)).append("</")
.append(STSConstants.WST_PREFIX)
.append(ON_BEHALF_OF).append(">");
}
if(keyType != null) {
sb.append("<").append(STSConstants.WST_PREFIX)
.append(KEY_TYPE).append(">")
.append(keyType).append("</")
.append(STSConstants.WST_PREFIX)
.append(KEY_TYPE).append(">");
}
sb.append("</").append(STSConstants.WST_PREFIX)
.append(REQUEST_SECURITY_TOKEN).append(">");
return sb.toString();
}
}
| false | false | null | null |
diff --git a/izpack-frontend/trunk/src/izpack/frontend/controller/AuthorManager.java b/izpack-frontend/trunk/src/izpack/frontend/controller/AuthorManager.java
index a83be066..17930cf0 100644
--- a/izpack-frontend/trunk/src/izpack/frontend/controller/AuthorManager.java
+++ b/izpack-frontend/trunk/src/izpack/frontend/controller/AuthorManager.java
@@ -1,125 +1,128 @@
/*
* Created on Jun 29, 2004
*
* $Id: AuthorManager.java Feb 8, 2004 izpack-frontend Copyright (C) 2001-2003
* IzPack Development Group
*
* File : AuthorManager.java Description : TODO Add description Author's email :
* [email protected]
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or 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 izpack.frontend.controller;
import izpack.frontend.model.Author;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import utils.XML;
import exceptions.DocumentCreationException;
import exceptions.UnhandleableException;
/**
* @author Andy Gombos
*
* Manage the persistent list of authors who have been used in the installer
*/
public class AuthorManager
{
public static ArrayList loadAuthors()
{
Document document;
try
{
document = XML.createDocument("conf/authors.xml");
}
catch (DocumentCreationException e1)
{
return null;
}
XPath xpath = XPathFactory.newInstance().newXPath();
//Load the authors array
NodeList authorElems;
try
{
authorElems = (NodeList) xpath.evaluate("//author", document, XPathConstants.NODESET);
ArrayList<Author> authors = new ArrayList<Author>();
for (int i = 0; i < authorElems.getLength(); i++)
{
String aname = xpath.evaluate("//author[" + (i + 1) + "]/@name", document);
String email = xpath.evaluate("//author[" + (i + 1) + "]/@email", document);
Author author = new Author(aname, email);
authors.add(author);
}
Collections.sort(authors);
persistantAuthors = authors;
return authors;
}
catch (XPathExpressionException e)
{
throw new UnhandleableException(e);
}
}
public static void writeAuthors() throws IOException
- {
+ {
+ if (persistantAuthors == null)
+ return;
+
Document document = XML.createDocument();
//Create the root element (authors)
Element root = document.createElement("authors");
document.appendChild(root);
for (Iterator iter = persistantAuthors.iterator(); iter.hasNext();)
{
Author auth = (Author) iter.next();
Element author = document.createElement("author");
root.appendChild(author);
author.setAttribute("name", auth.getName());
author.setAttribute("email", auth.getEmail());
}
XML.writeXML("conf/authors.xml", document);
}
public static void updateAuthors(ArrayList authors)
{
persistantAuthors = authors;
}
private static ArrayList persistantAuthors;
}
diff --git a/izpack-frontend/trunk/src/reporting/CrashHandler.java b/izpack-frontend/trunk/src/reporting/CrashHandler.java
index 850ddbab..cff47908 100644
--- a/izpack-frontend/trunk/src/reporting/CrashHandler.java
+++ b/izpack-frontend/trunk/src/reporting/CrashHandler.java
@@ -1,57 +1,59 @@
package reporting;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.Thread.UncaughtExceptionHandler;
/*
* Created on Sep 20, 2005
*
* $Id: CrashHandler.java Feb 8, 2004 izpack-frontend
* Copyright (C) 2001-2003 IzPack Development Group
*
* File : CrashHandler.java
* Description : TODO Add description
* Author's email : [email protected]
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or 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.
*/
public class CrashHandler implements UncaughtExceptionHandler
{
public void uncaughtException(Thread t, Throwable e)
{
System.err.println("Unhandled exception " + e.getClass().getName() + " " + e.getMessage());
System.err.println("Submitting an error report.");
System.err.println("This contains no personal information");
System.err.println("Please write a quick message of what you were doing when the exception occurred.");
System.err.println("To skip, or sumbit a message, press ENTER.");
String message = "";
try
{
message = new BufferedReader(new InputStreamReader(System.in)).readLine();
}
catch (IOException e1)
{
- // TODO Auto-generated catch block
- e1.printStackTrace();
+ //Ignore, no sense in causing more errors
}
+ if (message == null)
+ message = "";
+
ErrorSubmitter.sendErrorReport(e, message);
System.exit(-1);
}
}
diff --git a/izpack-frontend/trunk/src/reporting/ErrorSubmitter.java b/izpack-frontend/trunk/src/reporting/ErrorSubmitter.java
index 58116fff..7f107101 100644
--- a/izpack-frontend/trunk/src/reporting/ErrorSubmitter.java
+++ b/izpack-frontend/trunk/src/reporting/ErrorSubmitter.java
@@ -1,120 +1,119 @@
package reporting;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
/*
* Created on Oct 5, 2005
*
* $Id: PostTest.java Feb 8, 2004 izpack-frontend
* Copyright (C) 2001-2003 IzPack Development Group
*
* File : PostTest.java
* Description : TODO Add description
* Author's email : [email protected]
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or 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.
*/
public class ErrorSubmitter
{
public static void sendErrorReport(Throwable e, String message)
{
try
{
HttpURLConnection con = (HttpURLConnection) new URL("http://izpack.berlios.de/process.php").openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
OutputStream os = con.getOutputStream();
StringBuffer properties = new StringBuffer();
Properties props = System.getProperties();
Set<Object> keys = props.keySet();
os.write("exceptionList=".getBytes());
Throwable t = e;
writeException(t, os);
//Write out any linked exceptions too
while ( (t = t.getCause()) != null)
writeException(t, os);
os.write("&threadDump=".getBytes());
Map<Thread, StackTraceElement[]> stackTraces = Thread.getAllStackTraces();
Set<Thread> threads = stackTraces.keySet();
for (Thread thread : threads)
{
os.write( ("Thread: " + thread.getName() + "\r\n" ).getBytes() );
StackTraceElement[] stackTrace = stackTraces.get(thread);
for (int i = 0; i < stackTrace.length; i++)
{
os.write( ("\t" + stackTrace[i] + "\r\n").getBytes());
}
}
for (Object object : keys)
{
properties.append(object + " = " + props.getProperty((String) object) + "\r\n");
}
os.write("&properties=".getBytes());
os.write(properties.toString().getBytes());
os.write("&message=".getBytes());
os.write(message.getBytes());
if (con.getResponseCode() == 200)
System.err.println("Submit succeeded");
con.disconnect();
}
catch (Exception e1)
{
//Do nothing, we're doing this because of an error :)
- //Not really critical anyway
- System.err.println("Error filing report: " + e1.getMessage());
+ //Not really critical anyway
}
}
private static void writeException(Throwable e, OutputStream os) throws IOException
{
StackTraceElement[] trace = e.getStackTrace();
os.write(( e.toString() + "\r\n" ).getBytes());
for (int i = 0; i < trace.length; i++)
{
os.write( ("\t" + trace[i] + "\r\n").getBytes());
}
}
}
| false | false | null | null |
diff --git a/src/java/com/facebook/LinkBench/LinkBenchDriver.java b/src/java/com/facebook/LinkBench/LinkBenchDriver.java
index 2aea182..627fd99 100644
--- a/src/java/com/facebook/LinkBench/LinkBenchDriver.java
+++ b/src/java/com/facebook/LinkBench/LinkBenchDriver.java
@@ -1,601 +1,601 @@
package com.facebook.LinkBench;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.ByteBuffer;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.log4j.Logger;
import com.facebook.LinkBench.LinkBenchLoad.LoadChunk;
import com.facebook.LinkBench.LinkBenchLoad.LoadProgress;
import com.facebook.LinkBench.LinkBenchRequest.RequestProgress;
import com.facebook.LinkBench.stats.LatencyStats;
import com.facebook.LinkBench.stats.SampledStats;
import com.facebook.LinkBench.util.ClassLoadUtil;
/*
LinkBenchDriver class.
First loads data using multi-threaded LinkBenchLoad class.
Then does read and write requests of various types (addlink, deletelink,
updatelink, getlink, countlinks, getlinklist) using multi-threaded
LinkBenchRequest class.
Config options are taken from config file passed as argument.
*/
public class LinkBenchDriver {
public static final int EXIT_BADARGS = 1;
public static final int EXIT_BADCONFIG = 2;
/* Command line arguments */
private static String configFile = null;
private static String workloadConfigFile = null;
private static Properties cmdLineProps = null;
private static String logFile = null;
/** File for final statistics */
private static PrintStream csvStatsFile = null;
/** File for output of incremental csv data */
private static PrintStream csvStreamFile = null;
private static boolean doLoad = false;
private static boolean doRequest = false;
private Properties props;
private final Logger logger = Logger.getLogger(ConfigUtil.LINKBENCH_LOGGER);
LinkBenchDriver(String configfile, Properties
overrideProps, String logFile)
throws java.io.FileNotFoundException, IOException, LinkBenchConfigError {
// which link store to use
props = new Properties();
props.load(new FileInputStream(configfile));
for (String key: overrideProps.stringPropertyNames()) {
props.setProperty(key, overrideProps.getProperty(key));
}
loadWorkloadProps();
ConfigUtil.setupLogging(props, logFile);
logger.info("Config file: " + configfile);
logger.info("Workload config file: " + workloadConfigFile);
}
/**
* Load properties from auxilliary workload properties file if provided.
* Properties from workload properties file do not override existing
* properties
* @throws IOException
* @throws FileNotFoundException
*/
private void loadWorkloadProps() throws IOException, FileNotFoundException {
if (props.containsKey(Config.WORKLOAD_CONFIG_FILE)) {
workloadConfigFile = props.getProperty(Config.WORKLOAD_CONFIG_FILE);
if (!new File(workloadConfigFile).isAbsolute()) {
String linkBenchHome = ConfigUtil.findLinkBenchHome();
if (linkBenchHome == null) {
throw new RuntimeException("Data file config property "
+ Config.WORKLOAD_CONFIG_FILE
+ " was specified using a relative path, but linkbench home"
+ " directory was not specified through environment var "
+ ConfigUtil.linkbenchHomeEnvVar);
} else {
workloadConfigFile = linkBenchHome + File.separator + workloadConfigFile;
}
}
Properties workloadProps = new Properties();
- props.load(new FileInputStream(workloadConfigFile));
+ workloadProps.load(new FileInputStream(workloadConfigFile));
// Add workload properties, but allow other values to override
for (String key: workloadProps.stringPropertyNames()) {
- if (!props.contains(key)) {
+ if (props.getProperty(key) == null) {
props.setProperty(key, workloadProps.getProperty(key));
}
}
}
}
private static class Stores {
final LinkStore linkStore;
final NodeStore nodeStore;
public Stores(LinkStore linkStore, NodeStore nodeStore) {
super();
this.linkStore = linkStore;
this.nodeStore = nodeStore;
}
}
// generate instances of LinkStore and NodeStore
private Stores initStores()
throws Exception {
LinkStore linkStore = createLinkStore();
NodeStore nodeStore = createNodeStore(linkStore);
return new Stores(linkStore, nodeStore);
}
private LinkStore createLinkStore() throws Exception, IOException {
// The property "linkstore" defines the class name that will be used to
// store data in a database. The folowing class names are pre-packaged
// for easy access:
// LinkStoreMysql : run benchmark on mySQL
// LinkStoreHBaseGeneralAtomicityTesting : atomicity testing on HBase.
String linkStoreClassName = ConfigUtil.getPropertyRequired(props,
Config.LINKSTORE_CLASS);
logger.debug("Using LinkStore implementation: " + linkStoreClassName);
LinkStore linkStore;
try {
linkStore = ClassLoadUtil.newInstance(linkStoreClassName,
LinkStore.class);
} catch (ClassNotFoundException nfe) {
throw new IOException("Cound not find class for " + linkStoreClassName);
}
return linkStore;
}
/**
* @param linkStore a LinkStore instance to be reused if it turns out
* that linkStore and nodeStore classes are same
* @return
* @throws Exception
* @throws IOException
*/
private NodeStore createNodeStore(LinkStore linkStore) throws Exception,
IOException {
String nodeStoreClassName = props.getProperty(Config.NODESTORE_CLASS);
if (nodeStoreClassName == null) {
logger.debug("No NodeStore implementation provided");
} else {
logger.debug("Using NodeStore implementation: " + nodeStoreClassName);
}
if (linkStore != null && linkStore.getClass().getName().equals(
nodeStoreClassName)) {
// Same class, reuse object
if (!NodeStore.class.isAssignableFrom(linkStore.getClass())) {
throw new Exception("Specified NodeStore class " + nodeStoreClassName
+ " is not a subclass of NodeStore");
}
return (NodeStore)linkStore;
} else {
NodeStore nodeStore;
try {
nodeStore = ClassLoadUtil.newInstance(nodeStoreClassName,
NodeStore.class);
return nodeStore;
} catch (java.lang.ClassNotFoundException nfe) {
throw new IOException("Cound not find class for " + nodeStoreClassName);
}
}
}
void load() throws IOException, InterruptedException, Throwable {
if (!doLoad) {
logger.info("Skipping load data per the cmdline arg");
return;
}
// load data
int nLinkLoaders = ConfigUtil.getInt(props, Config.NUM_LOADERS);
boolean bulkLoad = true;
BlockingQueue<LoadChunk> chunk_q = new LinkedBlockingQueue<LoadChunk>();
// max id1 to generate
long maxid1 = ConfigUtil.getLong(props, Config.MAX_ID);
// id1 at which to start
long startid1 = ConfigUtil.getLong(props, Config.MIN_ID);
// Create loaders
logger.info("Starting loaders " + nLinkLoaders);
logger.debug("Bulk Load setting: " + bulkLoad);
Random masterRandom = createMasterRNG(props, Config.LOAD_RANDOM_SEED);
boolean genNodes = ConfigUtil.getBool(props, Config.GENERATE_NODES);
int nTotalLoaders = genNodes ? nLinkLoaders + 1 : nLinkLoaders;
LatencyStats latencyStats = new LatencyStats(nTotalLoaders);
List<Runnable> loaders = new ArrayList<Runnable>(nTotalLoaders);
LoadProgress loadTracker = LoadProgress.create(logger, props);
for (int i = 0; i < nLinkLoaders; i++) {
LinkStore linkStore = createLinkStore();
bulkLoad = bulkLoad && linkStore.bulkLoadBatchSize() > 0;
LinkBenchLoad l = new LinkBenchLoad(linkStore, props, latencyStats,
csvStreamFile, i, maxid1 == startid1 + 1, chunk_q, loadTracker);
loaders.add(l);
}
if (genNodes) {
logger.info("Will generate graph nodes during loading");
int loaderId = nTotalLoaders - 1;
NodeStore nodeStore = createNodeStore(null);
Random rng = new Random(masterRandom.nextLong());
loaders.add(new NodeLoader(props, logger, nodeStore, rng,
latencyStats, csvStreamFile, loaderId));
}
enqueueLoadWork(chunk_q, startid1, maxid1, nLinkLoaders,
new Random(masterRandom.nextLong()));
// run loaders
loadTracker.startTimer();
long loadTime = concurrentExec(loaders);
long expectedNodes = maxid1 - startid1;
long actualLinks = 0;
long actualNodes = 0;
for (final Runnable l:loaders) {
if (l instanceof LinkBenchLoad) {
actualLinks += ((LinkBenchLoad)l).getLinksLoaded();
} else {
assert(l instanceof NodeLoader);
actualNodes += ((NodeLoader)l).getNodesLoaded();
}
}
latencyStats.displayLatencyStats();
if (csvStatsFile != null) {
latencyStats.printCSVStats(csvStatsFile, true);
}
double loadTime_s = (loadTime/1000.0);
logger.info(String.format("LOAD PHASE COMPLETED. " +
" Loaded %d nodes (Expected %d)." +
" Loaded %d links (%.2f links per node). " +
" Took %.1f seconds. Links/second = %d",
actualNodes, expectedNodes, actualLinks,
actualLinks / (double) actualNodes, loadTime_s,
(long) Math.round(actualLinks / loadTime_s)));
}
/**
* Create a new random number generated, optionally seeded to a known
* value from the config file. If seed value not provided, a seed
* is chosen. In either case the seed is logged for later reproducibility.
* @param props
* @param configKey config key for the seed value
* @return
*/
private Random createMasterRNG(Properties props, String configKey) {
long seed;
if (props.containsKey(configKey)) {
seed = ConfigUtil.getLong(props, configKey);
logger.info("Using configured random seed " + configKey + "=" + seed);
} else {
seed = System.nanoTime() ^ (long)configKey.hashCode();
logger.info("Using random seed " + seed + " since " + configKey
+ " not specified");
}
SecureRandom masterRandom;
try {
masterRandom = SecureRandom.getInstance("SHA1PRNG");
} catch (NoSuchAlgorithmException e) {
logger.warn("SHA1PRNG not available, defaulting to default SecureRandom" +
" implementation");
masterRandom = new SecureRandom();
}
masterRandom.setSeed(ByteBuffer.allocate(8).putLong(seed).array());
// Can be used to check that rng is behaving as expected
logger.debug("First number generated by master " + configKey +
": " + masterRandom.nextLong());
return masterRandom;
}
private void enqueueLoadWork(BlockingQueue<LoadChunk> chunk_q, long startid1,
long maxid1, int nloaders, Random rng) {
// Enqueue work chunks. Do it in reverse order as a heuristic to improve
// load balancing, since queue is FIFO and later chunks tend to be larger
int chunkSize = ConfigUtil.getInt(props, Config.LOADER_CHUNK_SIZE, 2048);
long chunk_num = 0;
ArrayList<LoadChunk> stack = new ArrayList<LoadChunk>();
for (long id1 = startid1; id1 < maxid1; id1 += chunkSize) {
stack.add(new LoadChunk(chunk_num, id1,
Math.min(id1 + chunkSize, maxid1), rng));
chunk_num++;
}
for (int i = stack.size() - 1; i >= 0; i--) {
chunk_q.add(stack.get(i));
}
for (int i = 0; i < nloaders; i++) {
// Add a shutdown signal for each loader
chunk_q.add(LoadChunk.SHUTDOWN);
}
}
void sendrequests() throws IOException, InterruptedException, Throwable {
if (!doRequest) {
logger.info("Skipping request phase per the cmdline arg");
return;
}
// config info for requests
int nrequesters = ConfigUtil.getInt(props, Config.NUM_REQUESTERS);
if (nrequesters == 0) {
logger.info("NO REQUEST PHASE CONFIGURED. ");
return;
}
LatencyStats latencyStats = new LatencyStats(nrequesters);
List<LinkBenchRequest> requesters = new LinkedList<LinkBenchRequest>();
RequestProgress progress = LinkBenchRequest.createProgress(logger, props);
Random masterRandom = createMasterRNG(props, Config.REQUEST_RANDOM_SEED);
// create requesters
for (int i = 0; i < nrequesters; i++) {
Stores stores = initStores();
LinkBenchRequest l = new LinkBenchRequest(stores.linkStore,
stores.nodeStore, props, latencyStats, csvStreamFile,
progress, new Random(masterRandom.nextLong()), i, nrequesters);
requesters.add(l);
}
progress.startTimer();
// run requesters
concurrentExec(requesters);
long finishTime = System.currentTimeMillis();
// Calculate duration accounting for warmup time
long benchmarkTime = finishTime - progress.getBenchmarkStartTime();
long requestsdone = 0;
int abortedRequesters = 0;
// wait for requesters
for (LinkBenchRequest requester: requesters) {
requestsdone += requester.getRequestsDone();
if (requester.didAbort()) {
abortedRequesters++;
}
}
latencyStats.displayLatencyStats();
if (csvStatsFile != null) {
latencyStats.printCSVStats(csvStatsFile, true);
}
logger.info("REQUEST PHASE COMPLETED. " + requestsdone +
" requests done in " + (benchmarkTime/1000) + " seconds." +
" Requests/second = " + (1000*requestsdone)/benchmarkTime);
if (abortedRequesters > 0) {
logger.error(String.format("Benchmark did not complete cleanly: %d/%d " +
"request threads aborted. See error log entries for details.",
abortedRequesters, nrequesters));
}
}
/**
* Start all runnables at the same time. Then block till all
* tasks are completed. Returns the elapsed time (in millisec)
* since the start of the first task to the completion of all tasks.
*/
static long concurrentExec(final List<? extends Runnable> tasks)
throws Throwable {
final CountDownLatch startSignal = new CountDownLatch(tasks.size());
final CountDownLatch doneSignal = new CountDownLatch(tasks.size());
final AtomicLong startTime = new AtomicLong(0);
for (final Runnable task : tasks) {
new Thread(new Runnable() {
@Override
public void run() {
/*
* Run a task. If an uncaught exception occurs, bail
* out of the benchmark immediately, since any results
* of the benchmark will no longer be valid anyway
*/
try {
startSignal.countDown();
startSignal.await();
long now = System.currentTimeMillis();
startTime.compareAndSet(0, now);
task.run();
} catch (Throwable e) {
Logger threadLog = Logger.getLogger(ConfigUtil.LINKBENCH_LOGGER);
threadLog.error("Unrecoverable exception in" +
" worker thread:", e);
System.exit(1);
}
doneSignal.countDown();
}
}).start();
}
doneSignal.await(); // wait for all threads to finish
long endTime = System.currentTimeMillis();
return endTime - startTime.get();
}
void drive() throws IOException, InterruptedException, Throwable {
load();
sendrequests();
}
public static void main(String[] args)
throws IOException, InterruptedException, Throwable {
processArgs(args);
LinkBenchDriver d = new LinkBenchDriver(configFile,
cmdLineProps, logFile);
try {
d.drive();
} catch (LinkBenchConfigError e) {
System.err.println("Configuration error: " + e.toString());
System.exit(EXIT_BADCONFIG);
}
}
private static void printUsage(Options options) {
//PrintWriter writer = new PrintWriter(System.err);
HelpFormatter fmt = new HelpFormatter();
fmt.printHelp("linkbench", options, true);
}
private static Options initializeOptions() {
Options options = new Options();
Option config = new Option("c", true, "Linkbench config file");
config.setArgName("file");
options.addOption(config);
Option log = new Option("L", true, "Log to this file");
log.setArgName("file");
options.addOption(log);
Option csvStats = new Option("csvstats", "csvstats", true,
"CSV stats output");
csvStats.setArgName("file");
options.addOption(csvStats);
Option csvStream = new Option("csvstream", "csvstream", true,
"CSV streaming stats output");
csvStream.setArgName("file");
options.addOption(csvStream);
options.addOption("l", false,
"Execute loading stage of benchmark");
options.addOption("r", false,
"Execute request stage of benchmark");
// Java-style properties to override config file
// -Dkey=value
Option property = new Option("D", "Override a config setting");
property.setArgs(2);
property.setArgName("property=value");
property.setValueSeparator('=');
options.addOption(property);
return options;
}
/**
* Process command line arguments and set static variables
* exits program if invalid arguments provided
* @param options
* @param args
* @throws ParseException
*/
private static void processArgs(String[] args)
throws ParseException {
Options options = initializeOptions();
CommandLine cmd = null;
try {
CommandLineParser parser = new GnuParser();
cmd = parser.parse( options, args);
} catch (ParseException ex) {
// Use Apache CLI-provided messages
System.err.println(ex.getMessage());
printUsage(options);
System.exit(EXIT_BADARGS);
}
/*
* Apache CLI validates arguments, so can now assume
* all required options are present, etc
*/
if (cmd.getArgs().length > 0) {
System.err.print("Invalid trailing arguments:");
for (String arg: cmd.getArgs()) {
System.err.print(' ');
System.err.print(arg);
}
System.err.println();
printUsage(options);
System.exit(EXIT_BADARGS);
}
// Set static option variables
doLoad = cmd.hasOption('l');
doRequest = cmd.hasOption('r');
logFile = cmd.getOptionValue('L'); // May be null
configFile = cmd.getOptionValue('c');
if (configFile == null) {
// Try to find in usual location
String linkBenchHome = ConfigUtil.findLinkBenchHome();
if (linkBenchHome != null) {
configFile = linkBenchHome + File.separator +
"config" + File.separator + "LinkConfigMysql.properties";
} else {
System.err.println("Config file not specified through command "
+ "line argument and " + ConfigUtil.linkbenchHomeEnvVar
+ " environment variable not set to valid directory");
printUsage(options);
System.exit(EXIT_BADARGS);
}
}
String csvStatsFileName = cmd.getOptionValue("csvstats"); // May be null
if (csvStatsFileName != null) {
try {
csvStatsFile = new PrintStream(new FileOutputStream(csvStatsFileName));
} catch (FileNotFoundException e) {
System.err.println("Could not open file " + csvStatsFileName +
" for writing");
printUsage(options);
System.exit(EXIT_BADARGS);
}
}
String csvStreamFileName = cmd.getOptionValue("csvstream"); // May be null
if (csvStreamFileName != null) {
try {
csvStreamFile = new PrintStream(
new FileOutputStream(csvStreamFileName));
// File is written to by multiple threads, first write header
SampledStats.writeCSVHeader(csvStreamFile);
} catch (FileNotFoundException e) {
System.err.println("Could not open file " + csvStreamFileName +
" for writing");
printUsage(options);
System.exit(EXIT_BADARGS);
}
}
cmdLineProps = cmd.getOptionProperties("D");
if (!(doLoad || doRequest)) {
System.err.println("Did not select benchmark mode");
printUsage(options);
System.exit(EXIT_BADARGS);
}
}
}
| false | false | null | null |
diff --git a/m3ua/impl/src/main/java/org/mobicents/protocols/ss7/m3ua/impl/fsm/FSM.java b/m3ua/impl/src/main/java/org/mobicents/protocols/ss7/m3ua/impl/fsm/FSM.java
index 5f570d8c5..f80b1aa53 100644
--- a/m3ua/impl/src/main/java/org/mobicents/protocols/ss7/m3ua/impl/fsm/FSM.java
+++ b/m3ua/impl/src/main/java/org/mobicents/protocols/ss7/m3ua/impl/fsm/FSM.java
@@ -1,172 +1,172 @@
/*
* TeleStax, Open Source Cloud Communications Copyright 2012.
* and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.mobicents.protocols.ss7.m3ua.impl.fsm;
import javolution.util.FastMap;
import org.apache.log4j.Logger;
import org.mobicents.protocols.ss7.m3ua.impl.scheduler.M3UATask;
/**
* @author amit bhayani
*/
public class FSM extends M3UATask {
static final protected Logger logger = Logger.getLogger(FSM.class);
public static final String ATTRIBUTE_MESSAGE = "message";
private String name;
// first and last states in fsm
protected FSMState start;
protected FSMState end;
// intermediate states
private FastMap<String, FSMState> states = new FastMap<String, FSMState>();
protected FSMState currentState;
private FastMap attributes = new FastMap();
private FSMState oldState;
public FSM(String name) {
this.name = name;
}
public FSMState getState() {
return currentState;
}
public void setStart(String name) {
// the start state already has value which differs from current state?
if (this.start != null && currentState != null) {
throw new IllegalStateException("Start state can't be changed now");
}
this.start = states.get(name);
this.currentState = start;
}
public void setEnd(String name) {
this.end = states.get(name);
}
public FSMState createState(String name) {
FSMState s = new FSMState(this, name);
states.put(name, s);
return s;
}
public void setAttribute(String name, Object value) {
attributes.put(name, value);
}
public Object getAttribute(String name) {
return attributes.get(name);
}
public void removeAttribute(String name) {
attributes.remove(name);
}
public Transition createTransition(String name, String from, String to) {
if (name.equals("timeout")) {
throw new IllegalArgumentException("timeout is illegal name for transition");
}
if (!states.containsKey(from)) {
throw new IllegalStateException("Unknown state: " + from);
}
if (!states.containsKey(to)) {
throw new IllegalStateException("Unknown state: " + to);
}
Transition t = new Transition(name, states.get(to));
states.get(from).add(t);
return t;
}
public Transition createTimeoutTransition(String from, String to, long timeout) {
if (!states.containsKey(from)) {
throw new IllegalStateException("Unknown state: " + from);
}
if (!states.containsKey(to)) {
throw new IllegalStateException("Unknown state: " + to);
}
Transition t = new Transition("timeout", states.get(to));
states.get(from).timeout = timeout;
states.get(from).add(t);
return t;
}
/**
* Processes transition.
*
* @param name
* the name of transition.
*/
public void signal(String name) throws UnknownTransitionException {
// check that start state defined
if (start == null) {
throw new IllegalStateException("The start sate is not defined");
}
// check that end state defined
if (end == null) {
throw new IllegalStateException("The end sate is not defined");
}
// ignore any signals if fsm reaches end state
// if (state == end) {
// return;
// }
oldState = currentState;
// switch to next state
currentState = currentState.signal(name);
if (logger.isDebugEnabled()) {
logger.debug(String.format("%s Transition to=%s", toString(), name));
}
}
public void tick(long now) {
// if (state != null && state != start && state != end) {
if (currentState != null) {
currentState.tick(now);
}
}
@Override
public String toString() {
- return String.format("FSM.name=%s old state=%s, current state=%s", this.name, this.oldState.getName(),
- currentState.getName());
+ return String.format("FSM.name=%s old state=%s, current state=%s", this.name, (this.oldState!=null)?this.oldState.getName():"",
+ (this.currentState!=null)?this.currentState.getName():"");
}
}
| true | false | null | null |
diff --git a/core/ui/src/main/java/org/richfaces/renderkit/html/AjaxPollRenderer.java b/core/ui/src/main/java/org/richfaces/renderkit/html/AjaxPollRenderer.java
index bf06e242..4ba6fb11 100644
--- a/core/ui/src/main/java/org/richfaces/renderkit/html/AjaxPollRenderer.java
+++ b/core/ui/src/main/java/org/richfaces/renderkit/html/AjaxPollRenderer.java
@@ -1,163 +1,162 @@
/**
* License Agreement.
*
* Rich Faces - Natural Ajax for Java Server Faces (JSF)
*
* Copyright (C) 2007 Exadel, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.richfaces.renderkit.html;
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.faces.application.ResourceDependencies;
-import javax.faces.application.ResourceDependency;
-import javax.faces.component.UIComponent;
-import javax.faces.context.FacesContext;
-import javax.faces.context.PartialViewContext;
-import javax.faces.context.ResponseWriter;
-import javax.faces.event.ActionEvent;
-
import org.ajax4jsf.javascript.JSFunction;
import org.ajax4jsf.javascript.JSFunctionDefinition;
import org.ajax4jsf.javascript.JSReference;
import org.richfaces.cdk.annotations.JsfRenderer;
import org.richfaces.component.AbstractPoll;
import org.richfaces.renderkit.HtmlConstants;
import org.richfaces.renderkit.RenderKitUtils;
import org.richfaces.renderkit.RendererBase;
import org.richfaces.renderkit.util.HandlersChain;
import org.richfaces.renderkit.util.RendererUtils;
+import javax.faces.application.ResourceDependencies;
+import javax.faces.application.ResourceDependency;
+import javax.faces.component.UIComponent;
+import javax.faces.context.FacesContext;
+import javax.faces.context.PartialViewContext;
+import javax.faces.context.ResponseWriter;
+import javax.faces.event.ActionEvent;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
/**
* @author shura
*/
@ResourceDependencies({@ResourceDependency(library = "org.richfaces", name = "ajax.reslib"),
@ResourceDependency(library = "org.richfaces", name = "base-component.reslib"),
@ResourceDependency(library = "org.richfaces", name = "poll.js")})
@JsfRenderer
public class AjaxPollRenderer extends RendererBase {
public static final String COMPONENT_FAMILY = "org.richfaces.Poll";
public static final String RENDERER_TYPE = "org.richfaces.PollRenderer";
private static final String AJAX_POLL_FUNCTION = "new RichFaces.ui.Poll";
private static final String ENABLED = "enabled";
private void addComponentToAjaxRender(FacesContext context, UIComponent component) {
PartialViewContext pvc = context.getPartialViewContext();
pvc.getRenderIds().add(component.getClientId(context));
}
@Override
protected void queueComponentEventForBehaviorEvent(FacesContext context, UIComponent component, String eventName) {
super.queueComponentEventForBehaviorEvent(context, component, eventName);
if (AbstractPoll.TIMER.equals(eventName)) {
new ActionEvent(component).queue();
addComponentToAjaxRender(context, component);
}
}
/*
* (non-Javadoc)
*
* @see org.ajax4jsf.renderkit.RendererBase#doEncodeEnd(javax.faces.context.ResponseWriter,
* javax.faces.context.FacesContext, javax.faces.component.UIComponent)
*/
protected void doEncodeEnd(ResponseWriter writer, FacesContext context,
UIComponent component) throws IOException {
RendererUtils utils = getUtils();
boolean shouldRenderForm = utils.getNestingForm(context, component) == null;
String rootElementName = shouldRenderForm ? HtmlConstants.DIV_ELEM : HtmlConstants.SPAN_ELEM;
AbstractPoll poll = (AbstractPoll) component;
writer.startElement(rootElementName, component);
writer.writeAttribute(HtmlConstants.STYLE_ATTRIBUTE, "display:none;", null);
utils.encodeId(context, component);
if (shouldRenderForm) {
String clientId = component.getClientId(context) + RendererUtils.DUMMY_FORM_ID;
utils.encodeBeginForm(context, component, writer, clientId);
utils.encodeEndForm(context, writer);
}
- writer.endElement(rootElementName);
// polling script.
writer.startElement(HtmlConstants.SCRIPT_ELEM, component);
writer.writeAttribute(HtmlConstants.TYPE_ATTR, "text/javascript", null);
StringBuffer script = new StringBuffer("");
JSFunction function = new JSFunction(AJAX_POLL_FUNCTION);
Map<String, Object> options = new HashMap<String, Object>();
RenderKitUtils.addToScriptHash(options, "interval", poll.getInterval(), "1000");
//RenderKitUtils.addToScriptHash(options, "pollId", component.getClientId(context));
HandlersChain handlersChain = new HandlersChain(context, poll);
handlersChain.addInlineHandlerFromAttribute(AbstractPoll.ON_TIMER);
handlersChain.addBehaviors(AbstractPoll.TIMER);
handlersChain.addAjaxSubmitFunction();
String handler = handlersChain.toScript();
if (handler != null) {
JSFunctionDefinition timerHandler = new JSFunctionDefinition(JSReference.EVENT);
timerHandler.addToBody(handler);
options.put(AbstractPoll.ON_TIMER, timerHandler);
}
if (poll.isEnabled()) {
options.put(ENABLED, true);
}
function.addParameter(component.getClientId(context));
function.addParameter(options);
//function.appendScript(script);
writer.writeText(function.toScript(), null);
writer.endElement(HtmlConstants.SCRIPT_ELEM);
+ writer.endElement(rootElementName);
}
/*
* (non-Javadoc)
*
* @see org.ajax4jsf.renderkit.RendererBase#getComponentClass()
*/
protected Class<? extends UIComponent> getComponentClass() {
// only push component is allowed.
return AbstractPoll.class;
}
@Override
protected void doDecode(FacesContext context, UIComponent component) {
super.doDecode(context, component);
AbstractPoll poll = (AbstractPoll) component;
if (poll.isEnabled()) {
Map<String, String> requestParameterMap = context.getExternalContext().getRequestParameterMap();
if (requestParameterMap.get(poll.getClientId(context)) != null) {
new ActionEvent(poll).queue();
addComponentToAjaxRender(context, component);
}
}
}
}
| false | false | null | null |
diff --git a/app/models/User.java b/app/models/User.java
index 3f7d307..8d240b4 100644
--- a/app/models/User.java
+++ b/app/models/User.java
@@ -1,45 +1,47 @@
package models;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import play.data.format.Formats;
import play.data.validation.Constraints;
import play.db.ebean.Model;
import javax.persistence.*;
import java.sql.Timestamp;
import java.util.Date;
/**
* User entity managed by Ebean
*/
@Entity
@Table(name = "users")
+@JsonIgnoreProperties({"id"})
public class User extends Model {
@Id
@Constraints.Required
@Formats.NonEmpty
public String email;
@Constraints.Required
public String name;
@Enumerated(EnumType.STRING)
public UserRole role;
@Constraints.Required
public Date firstLogin;
@Version
public Timestamp lastModified;
// -- Queries
public static Model.Finder<String, User> find = new Model.Finder(String.class, User.class);
/**
* Retrieve a User from email.
*/
public static User findByEmail(String email) {
return find.where().eq("email", email).findUnique();
}
}
| false | false | null | null |
diff --git a/src/main/java/de/mactunes/schmitzkatz/blog/posts/BlogPost.java b/src/main/java/de/mactunes/schmitzkatz/blog/posts/BlogPost.java
index c43c001..4ca45fc 100644
--- a/src/main/java/de/mactunes/schmitzkatz/blog/posts/BlogPost.java
+++ b/src/main/java/de/mactunes/schmitzkatz/blog/posts/BlogPost.java
@@ -1,167 +1,167 @@
package de.mactunes.schmitzkatz.blog.posts;
import java.util.Date;
import java.util.Calendar;
import java.io.File;
import java.text.SimpleDateFormat;
import net.sf.json.JSONObject;
import net.sf.json.JSONException;
import net.sf.json.JSONSerializer;
import com.petebevin.markdown.MarkdownProcessor;
public class BlogPost implements Comparable<BlogPost> {
public static final String POSTS_PATH = "blog" + File.separator + "Posts";
public static final String GENERATED_PATH = "blog" + File.separator + "Generated";
public static final String TEMPLATES_PATH = "blog" + File.separator + "Templates";
public static final String MEDIA_DIR = "media";
public static final String POSTS_DIR = "posts";
public static final String BLOG_POST_HTML_FILENAME = "index.html"; // TODO get from props
private static final String SLASH = "/";
private static final String SERIALIZED_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
private static final SimpleDateFormat FORMATTER = new SimpleDateFormat(SERIALIZED_DATE_FORMAT);
public static final String JSON_KEY_DATE = "date",
JSON_KEY_TITLE = "title",
JSON_KEY_SUMMARY = "summary",
JSON_KEY_TEXT = "text";
private static final int INDENT_SPACES = 4;
private String title, summary, markdownText, htmlText;
private Date date;
private String identifier;
public BlogPost(String title, String summary, Date date, String pathToDirectory) {
this.title = title;
this.summary = summary;
this.date = date;
this.identifier = identifier;
}
public BlogPost(String strJSON, String strMarkdown, String identifier) {
this.identifier = identifier;
this.markdownText = strMarkdown;
try {
JSONObject objJSON = (JSONObject) JSONSerializer.toJSON(strJSON);
if (objJSON.has(JSON_KEY_TITLE)) {
this.title = objJSON.getString(JSON_KEY_TITLE);
}
if (objJSON.has(JSON_KEY_DATE)) {
try {
this.date = FORMATTER.parse(objJSON.getString(JSON_KEY_DATE));
} catch (Exception ex) {
System.out.println("Error: failed parsing date for post: " + title);
}
}
if (objJSON.has(JSON_KEY_SUMMARY)) {
this.summary = objJSON.getString(JSON_KEY_SUMMARY);
}
} catch (JSONException je) {
System.out.println("Error: could not parse some element for blog post: " + title);
}
}
public String getJSONRepresentation() {
JSONObject jsonObj = new JSONObject();
jsonObj.put(JSON_KEY_TITLE, title);
jsonObj.put(JSON_KEY_DATE, FORMATTER.format(date).toString());
jsonObj.put(JSON_KEY_SUMMARY, summary);
jsonObj.put(JSON_KEY_TEXT, markdownText);
return jsonObj.toString(INDENT_SPACES);
}
public String getTitle() {
return title;
}
public String getSummary() {
return summary;
}
public String getTextAsMarkdown() {
return markdownText;
}
public String getTextAsHTML() {
if (null == markdownText) {
return null;
}
// don't invoke markdown processor every time.
// cache the results and return them when called multiple times
if (null != htmlText) {
return htmlText;
}
MarkdownProcessor processor = new MarkdownProcessor();
return processor.markdown(markdownText);
}
public Date getDate() {
return date;
}
public String getIdentifier() {
return identifier;
}
public String getPostDir() {
return POSTS_PATH + File.separator + identifier;
}
public String getPostMediaDir() {
return getPostDir() + File.separator + MEDIA_DIR;
}
public String getParentDirInGeneratedDir() {
return GENERATED_PATH + getRelativeGeneratedPostsPath();
}
private String getRelativeGeneratedPostsPath() {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return File.separator + POSTS_DIR +
File.separator + cal.get(Calendar.YEAR) +
- File.separator + cal.get(Calendar.MONTH) +
+ File.separator + (cal.get(Calendar.MONTH) + 1) +
File.separator + cal.get(Calendar.DAY_OF_MONTH) ;
}
public String getPostDirInGeneratedDir() {
return getParentDirInGeneratedDir() +
File.separator +
getIdentifier();
}
public String getLink() {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return POSTS_DIR + SLASH +
cal.get(Calendar.YEAR) + SLASH +
- cal.get(Calendar.MONTH) + SLASH +
+ (cal.get(Calendar.MONTH) + 1) + SLASH +
cal.get(Calendar.DAY_OF_MONTH) + SLASH +
getIdentifier() + SLASH +
BLOG_POST_HTML_FILENAME;
}
public String getPostMediaDirInGeneratedDir() {
return getParentDirInGeneratedDir() +
File.separator +
getIdentifier() +
File.separator +
MEDIA_DIR;
}
@Override
public int compareTo(BlogPost otherBlogPost) {
return date.compareTo(otherBlogPost.getDate());
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/main/java/org/lazan/t5/stitch/services/internal/SyntaxSourceImpl.java b/src/main/java/org/lazan/t5/stitch/services/internal/SyntaxSourceImpl.java
index 6d8bc54..e453357 100644
--- a/src/main/java/org/lazan/t5/stitch/services/internal/SyntaxSourceImpl.java
+++ b/src/main/java/org/lazan/t5/stitch/services/internal/SyntaxSourceImpl.java
@@ -1,30 +1,30 @@
package org.lazan.t5.stitch.services.internal;
import java.util.Map;
import org.apache.tapestry5.Asset;
import org.apache.tapestry5.ioc.annotations.UsesMappedConfiguration;
import org.apache.tapestry5.ioc.internal.util.CollectionFactory;
import org.lazan.t5.stitch.model.Syntax;
import org.lazan.t5.stitch.services.SyntaxSource;
@UsesMappedConfiguration(key=String.class, value=Syntax.class)
public class SyntaxSourceImpl implements SyntaxSource {
- private Map<String, Syntax> syntaxBySyffix;
+ private Map<String, Syntax> syntaxBySuffix;
- public SyntaxSourceImpl(Map<String, Syntax> syntaxBySyffix) {
+ public SyntaxSourceImpl(Map<String, Syntax> syntaxBySuffix) {
super();
- this.syntaxBySyffix = CollectionFactory.newCaseInsensitiveMap(syntaxBySyffix);
+ this.syntaxBySuffix = CollectionFactory.newCaseInsensitiveMap(syntaxBySuffix);
}
public Syntax getSyntax(Asset source) {
String name = source.getResource().getFile();
int dotIndex = name.lastIndexOf('.');
Syntax syntax = null;
if (dotIndex != -1) {
String suffix = name.substring(dotIndex + 1);
- syntax = syntaxBySyffix.get(suffix);
+ syntax = syntaxBySuffix.get(suffix);
}
return syntax == null ? Syntax.AUTO_DETECT : syntax;
}
}
| false | false | null | null |
diff --git a/web/src/main/java/org/fao/geonet/kernel/csw/services/GetDomain.java b/web/src/main/java/org/fao/geonet/kernel/csw/services/GetDomain.java
index d6224ffaf0..1c56b0fcc2 100644
--- a/web/src/main/java/org/fao/geonet/kernel/csw/services/GetDomain.java
+++ b/web/src/main/java/org/fao/geonet/kernel/csw/services/GetDomain.java
@@ -1,455 +1,455 @@
//=============================================================================
//=== Copyright (C) 2001-2007 Food and Agriculture Organization of the
//=== United Nations (FAO-UN), United Nations World Food Programme (WFP)
//=== and United Nations Environment Programme (UNEP)
//===
//=== This program is free software; you can redistribute it and/or modify
//=== it under the terms of the GNU General Public License as published by
//=== the Free Software Foundation; either version 2 of the License, or (at
//=== your option) any later version.
//===
//=== This program is distributed in the hope that it will be useful, but
//=== WITHOUT ANY WARRANTY; without even the implied warranty of
//=== MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//=== General Public License for more details.
//===
//=== You should have received a copy of the GNU General Public License
//=== along with this program; if not, write to the Free Software
//=== Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
//===
//=== Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2,
//=== Rome - Italy. email: [email protected]
//==============================================================================
package org.fao.geonet.kernel.csw.services;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import jeeves.server.context.ServiceContext;
import jeeves.utils.Log;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.DocumentStoredFieldVisitor;
import org.apache.lucene.index.FieldInfos;
import org.apache.lucene.index.SlowCompositeReaderWrapper;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.CachingWrapperFilter;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.TopDocs;
import org.fao.geonet.GeonetContext;
import org.fao.geonet.constants.Geonet;
import org.fao.geonet.csw.common.Csw;
import org.fao.geonet.csw.common.exceptions.CatalogException;
import org.fao.geonet.csw.common.exceptions.NoApplicableCodeEx;
import org.fao.geonet.csw.common.exceptions.OperationNotSupportedEx;
import org.fao.geonet.kernel.csw.CatalogConfiguration;
import org.fao.geonet.kernel.csw.CatalogDispatcher;
import org.fao.geonet.kernel.csw.CatalogService;
import org.fao.geonet.kernel.csw.services.getrecords.CatalogSearcher;
import org.fao.geonet.kernel.search.IndexAndTaxonomy;
import org.fao.geonet.kernel.search.LuceneConfig;
import org.fao.geonet.kernel.search.LuceneSearcher;
import org.fao.geonet.kernel.search.LuceneUtils;
import org.fao.geonet.kernel.search.SearchManager;
import org.fao.geonet.kernel.search.SummaryComparator;
import org.fao.geonet.kernel.search.SummaryComparator.SortOption;
import org.fao.geonet.kernel.search.SummaryComparator.Type;
import org.fao.geonet.kernel.search.index.GeonetworkMultiReader;
import org.fao.geonet.kernel.search.spatial.Pair;
import org.jdom.Element;
import bak.pcj.map.ObjectKeyIntMapIterator;
import bak.pcj.map.ObjectKeyIntOpenHashMap;
//=============================================================================
public class GetDomain extends AbstractOperation implements CatalogService
{
//---------------------------------------------------------------------------
//---
//--- Constructor
//---
//---------------------------------------------------------------------------
private LuceneConfig _luceneConfig;
public GetDomain(LuceneConfig luceneConfig) {
this._luceneConfig = luceneConfig;
}
//---------------------------------------------------------------------------
//---
//--- API methods
//---
//---------------------------------------------------------------------------
public String getName() { return "GetDomain"; }
//---------------------------------------------------------------------------
public Element execute(Element request, ServiceContext context) throws CatalogException
{
checkService(request);
checkVersion(request);
Element response = new Element(getName() +"Response", Csw.NAMESPACE_CSW);
String[] propertyNames = getParameters(request, "PropertyName");
String[] parameterNames = getParameters(request, "ParameterName");
String cswServiceSpecificConstraint = request.getChildText(Geonet.Elem.FILTER);
// PropertyName handled first.
if (propertyNames != null) {
List<Element> domainValues;
try {
domainValues = handlePropertyName(propertyNames, context, false, CatalogConfiguration.getMaxNumberOfRecordsForPropertyNames(), cswServiceSpecificConstraint, _luceneConfig);
} catch (Exception e) {
Log.error(Geonet.CSW, "Error getting domain value for specified PropertyName : " + e);
throw new NoApplicableCodeEx(
"Raised exception while getting domain value for specified PropertyName : " + e);
}
response.addContent(domainValues);
return response;
}
if (parameterNames != null) {
List<Element> domainValues = handleParameterName(parameterNames);
response.addContent(domainValues);
}
return response;
}
//---------------------------------------------------------------------------
public Element adaptGetRequest(Map<String, String> params)
{
String service = params.get("service");
String version = params.get("version");
String parameterName = params.get("parametername");
String propertyName = params.get("propertyname");
Element request = new Element(getName(), Csw.NAMESPACE_CSW);
setAttrib(request, "service", service);
setAttrib(request, "version", version);
//--- these 2 are in mutual exclusion.
Element propName = new Element("PropertyName", Csw.NAMESPACE_CSW).setText(propertyName);
Element paramName = new Element("ParameterName", Csw.NAMESPACE_CSW).setText(parameterName);
// Property is handled first.
if (propertyName != null && !propertyName.equals(""))
request.addContent(propName);
else if (parameterName != null && !parameterName.equals(""))
request.addContent(paramName);
return request;
}
//---------------------------------------------------------------------------
public Element retrieveValues(String parameterName) throws CatalogException {
return null;
}
//---------------------------------------------------------------------------
public static List<Element> handlePropertyName(String[] propertyNames,
ServiceContext context, boolean freq, int maxRecords, String cswServiceSpecificConstraint, LuceneConfig luceneConfig) throws Exception {
List<Element> domainValuesList = null;
if(Log.isDebugEnabled(Geonet.CSW))
Log.debug(Geonet.CSW,"Handling property names '"+Arrays.toString(propertyNames)+"' with max records of "+maxRecords);
for (int i=0; i < propertyNames.length; i++) {
if (i==0) domainValuesList = new ArrayList<Element>();
// Initialize list of values element.
Element listOfValues = null;
// Generate DomainValues element
Element domainValues = new Element("DomainValues", Csw.NAMESPACE_CSW);
// FIXME what should be the type ???
domainValues.setAttribute("type", "csw:Record");
String property = propertyNames[i].trim();
// Set propertyName in any case.
Element pn = new Element("PropertyName", Csw.NAMESPACE_CSW);
domainValues.addContent(pn.setText(property));
GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
SearchManager sm = gc.getSearchmanager();
IndexAndTaxonomy indexAndTaxonomy= sm.getNewIndexReader(null);
try {
GeonetworkMultiReader reader = indexAndTaxonomy.indexReader;
BooleanQuery groupsQuery = (BooleanQuery) CatalogSearcher.getGroupsQuery(context);
BooleanQuery query = null;
// Apply CSW service specific constraint
if (StringUtils.isNotEmpty(cswServiceSpecificConstraint)) {
Query constraintQuery = CatalogSearcher.getCswServiceSpecificConstraintQuery(cswServiceSpecificConstraint, luceneConfig);
query = new BooleanQuery();
BooleanClause.Occur occur = LuceneUtils
.convertRequiredAndProhibitedToOccur(true, false);
query.add(groupsQuery, occur);
query.add(constraintQuery, occur);
} else {
query = groupsQuery;
}
List<Pair<String, Boolean>> sortFields = Collections.singletonList(Pair.read(Geonet.SearchResult.SortBy.RELEVANCE, true));
Sort sort = LuceneSearcher.makeSort(sortFields, context.getLanguage(), false);
CachingWrapperFilter filter = null;
Pair<TopDocs,Element> searchResults = LuceneSearcher.doSearchAndMakeSummary(
maxRecords, 0, maxRecords, context.getLanguage(),
null, reader,
query, filter, sort, null, false, false,
false, false // Scoring is useless for GetDomain operation
);
TopDocs hits = searchResults.one();
try {
// Get mapped lucene field in CSW configuration
String indexField = CatalogConfiguration.getFieldMapping().get(
property.toLowerCase());
if (indexField != null)
property = indexField;
// check if params asked is in the index using getFieldNames ?
@SuppressWarnings("resource")
FieldInfos fi = new SlowCompositeReaderWrapper(reader).getFieldInfos();
if (fi.fieldInfo(property) == null)
continue;
boolean isRange = false;
if (CatalogConfiguration.getGetRecordsRangeFields().contains(
property))
isRange = true;
if (isRange)
listOfValues = new Element("RangeOfValues", Csw.NAMESPACE_CSW);
else
listOfValues = new Element("ListOfValues", Csw.NAMESPACE_CSW);
Set<String> fields = new HashSet<String>();
fields.add(property);
fields.add("_isTemplate");
// parse each document in the index
String[] fieldValues;
SortedSet<String> sortedValues = new TreeSet<String>();
ObjectKeyIntOpenHashMap duplicateValues = new ObjectKeyIntOpenHashMap();
for (int j = 0; j < hits.scoreDocs.length; j++) {
DocumentStoredFieldVisitor selector = new DocumentStoredFieldVisitor(fields);
reader.document(hits.scoreDocs[j].doc, selector);
Document doc = selector.getDocument();
// Skip templates and subTemplates
String[] isTemplate = doc.getValues("_isTemplate");
if (isTemplate[0] != null && !isTemplate[0].equals("n"))
continue;
// Get doc values for specified property
fieldValues = doc.getValues(property);
if (fieldValues == null)
continue;
addtoSortedSet(sortedValues, fieldValues, duplicateValues);
}
SummaryComparator valuesComparator = new SummaryComparator(SortOption.FREQUENCY, Type.STRING, context.getLanguage(), null);
TreeSet<SummaryComparator.SummaryElement> sortedValuesFrequency = new TreeSet<SummaryComparator.SummaryElement>(valuesComparator);
ObjectKeyIntMapIterator entries = duplicateValues.entries();
while(entries.hasNext()) {
- sortedValuesFrequency.add(new SummaryComparator.SummaryElement(entries));
entries.next();
+ sortedValuesFrequency.add(new SummaryComparator.SummaryElement(entries));
}
if (freq)
return createValuesByFrequency(sortedValuesFrequency);
else
listOfValues.addContent(createValuesElement(sortedValues, isRange));
} finally {
// any children means that the catalog was unable to determine
// anything about the specified parameter
if (listOfValues!= null && listOfValues.getChildren().size() != 0)
domainValues.addContent(listOfValues);
// Add current DomainValues to the list
domainValuesList.add(domainValues);
}
} finally {
sm.releaseIndexReader(indexAndTaxonomy);
}
}
return domainValuesList;
}
//---------------------------------------------------------------------------
//---
//--- Private methods
//---
//---------------------------------------------------------------------------
private List<Element> handleParameterName(String[] parameterNames) throws CatalogException {
Element values;
List<Element> domainValuesList = null;
for (int i=0; i < parameterNames.length; i++) {
if (i==0) domainValuesList = new ArrayList<Element>();
// Generate DomainValues element
Element domainValues = new Element("DomainValues", Csw.NAMESPACE_CSW);
// FIXME what should be the type ???
domainValues.setAttribute("type", "csw:Record");
String paramName = parameterNames[i];
// Set parameterName in any case.
Element pn = new Element("ParameterName", Csw.NAMESPACE_CSW);
domainValues.addContent(pn.setText(paramName));
String operationName = paramName.substring(0, paramName.indexOf('.'));
String parameterName = paramName.substring(paramName.indexOf('.')+1);
CatalogService cs = checkOperation(operationName);
values = cs.retrieveValues(parameterName);
// values null mean that the catalog was unable to determine
// anything about the specified parameter
if (values != null)
domainValues.addContent(values);
// Add current DomainValues to the list
domainValuesList.add(domainValues);
}
return domainValuesList;
}
//---------------------------------------------------------------------------
private CatalogService checkOperation(String operationName)
throws CatalogException {
CatalogService cs = CatalogDispatcher.hmServices.get(operationName);
if (cs == null)
throw new OperationNotSupportedEx(operationName);
return cs;
}
//---------------------------------------------------------------------------
private String[] getParameters(Element request, String parameter) {
if (request == null)
return null;
Element paramElt = request.getChild(parameter,Csw.NAMESPACE_CSW);
if (paramElt == null)
return null;
String parameterName = paramElt.getText();
return parameterName.split(",");
}
//---------------------------------------------------------------------------
/**
* @param sortedValues
* @param fieldValues
* @param duplicateValues
*/
private static void addtoSortedSet(SortedSet<String> sortedValues,
String[] fieldValues, ObjectKeyIntOpenHashMap duplicateValues) {
for (String value : fieldValues) {
sortedValues.add(value);
if (duplicateValues.containsKey(value)) {
int nb = duplicateValues.get(value);
duplicateValues.remove(value);
duplicateValues.put(value, nb+1);
} else
duplicateValues.put(value, 1);
}
}
//---------------------------------------------------------------------------
/**
* Create value element for each item of the string array
* @param sortedValues
* @param isRange
* @return
*/
private static List<Element> createValuesElement(SortedSet<String> sortedValues, boolean isRange) {
List<Element> valuesList = new ArrayList<Element>();
if (!isRange) {
for (String value : sortedValues) {
valuesList.add(new Element("Value", Csw.NAMESPACE_CSW).setText(value));
}
} else {
valuesList.add(new Element("MinValue",Csw.NAMESPACE_CSW).setText(sortedValues.first()));
valuesList.add(new Element("MaxValue",Csw.NAMESPACE_CSW).setText(sortedValues.last()));
}
return valuesList;
}
//---------------------------------------------------------------------------
/**
* @param sortedValuesFrequency
* @return
*/
private static List<Element> createValuesByFrequency(TreeSet<SummaryComparator.SummaryElement> sortedValuesFrequency) {
List<Element> values = new ArrayList<Element>();
Element value;
for (SummaryComparator.SummaryElement element : sortedValuesFrequency) {
value = new Element("Value", Csw.NAMESPACE_CSW);
value.setAttribute("count", Integer.toString(element.count));
value.setText(element.name);
values.add(value);
}
return values;
}
}
//=============================================================================
| false | false | null | null |
diff --git a/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/java/JavaTemplateData.java b/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/java/JavaTemplateData.java
index ea683b812..221193421 100644
--- a/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/java/JavaTemplateData.java
+++ b/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/java/JavaTemplateData.java
@@ -1,110 +1,106 @@
/*
* Copyright (c) 2010, IETR/INSA of Rennes
* 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 IETR/INSA of Rennes nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
* WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
package net.sf.orcc.backends.java;
import java.util.HashMap;
import java.util.Map;
import net.sf.orcc.df.Actor;
import net.sf.orcc.ir.Arg;
import net.sf.orcc.ir.ArgByRef;
import net.sf.orcc.ir.ArgByVal;
-import net.sf.orcc.ir.Expression;
import net.sf.orcc.ir.InstCall;
import net.sf.orcc.ir.Param;
import net.sf.orcc.ir.Type;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.ecore.EObject;
/**
* This class computes a map for inserting cast information in some call
* instructions arguments.
*
* @author Antoine Lorence
*
*/
public class JavaTemplateData {
/**
* List to save cast informations
*/
private Map<Arg, Type> castedListReferences;
public JavaTemplateData(Actor actor) {
castedListReferences = new HashMap<Arg, Type>();
computeCastedListReferences(actor);
}
public Map<Arg, Type> getCastedListReferences() {
return castedListReferences;
}
private void computeCastedListReferences(Actor actor) {
TreeIterator<EObject> it = actor.eAllContents();
while (it.hasNext()) {
EObject object = it.next();
// Working on CAL procedure calling except "print" instructions
if (object instanceof InstCall
&& !((InstCall) object).getProcedure().getName()
.equals("print")) {
InstCall call = (InstCall) object;
EList<Arg> callArgs = call.getParameters();
EList<Param> procParams = call.getProcedure().getParameters();
if (callArgs.size() != procParams.size())
System.out.println("Size error : " + callArgs.size()
+ " given for " + procParams.size() + " needed.");
else {
int i;
for (i = 0; i < callArgs.size(); ++i) {
Type procParamType = procParams.get(i).getVariable()
.getType();
Type callParamType = callArgs.get(i).isByRef() ? ((ArgByRef) callArgs
.get(i)).getUse().getVariable().getType()
: ((ArgByVal) callArgs.get(i)).getValue()
.getType();
- Expression e = ((ArgByVal) callArgs.get(i)).getValue();
-
-
if (!callParamType.equals(procParamType)) {
castedListReferences.put(callArgs.get(i),
procParamType);
break;
}
}
}
}
}
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/Carbonado/src/main/java/com/amazon/carbonado/repo/replicated/ReplicationTrigger.java b/Carbonado/src/main/java/com/amazon/carbonado/repo/replicated/ReplicationTrigger.java
index 7f743ac..7edec6b 100644
--- a/Carbonado/src/main/java/com/amazon/carbonado/repo/replicated/ReplicationTrigger.java
+++ b/Carbonado/src/main/java/com/amazon/carbonado/repo/replicated/ReplicationTrigger.java
@@ -1,413 +1,415 @@
/*
* Copyright 2006 Amazon Technologies, Inc. or its affiliates.
* Amazon, Amazon.com and Carbonado are trademarks or registered trademarks
* of Amazon Technologies, Inc. or its affiliates. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazon.carbonado.repo.replicated;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.amazon.carbonado.FetchException;
import com.amazon.carbonado.FetchNoneException;
import com.amazon.carbonado.OptimisticLockException;
import com.amazon.carbonado.PersistException;
import com.amazon.carbonado.PersistNoneException;
import com.amazon.carbonado.Repository;
import com.amazon.carbonado.Storable;
import com.amazon.carbonado.Storage;
import com.amazon.carbonado.Transaction;
import com.amazon.carbonado.Trigger;
import com.amazon.carbonado.UniqueConstraintException;
import com.amazon.carbonado.spi.RepairExecutor;
import com.amazon.carbonado.spi.TriggerManager;
/**
* All inserts/updates/deletes are first committed to the master storage, then
* duplicated and committed to the replica.
*
* @author Don Schneider
* @author Brian S O'Neill
*/
class ReplicationTrigger<S extends Storable> extends Trigger<S> {
private final Repository mRepository;
private final Storage<S> mReplicaStorage;
private final Storage<S> mMasterStorage;
private final TriggerManager<S> mTriggerManager;
ReplicationTrigger(Repository repository,
Storage<S> replicaStorage,
Storage<S> masterStorage)
{
mRepository = repository;
mReplicaStorage = replicaStorage;
mMasterStorage = masterStorage;
// Use TriggerManager to locally disable trigger execution during
// resync and repairs.
mTriggerManager = new TriggerManager<S>();
mTriggerManager.addTrigger(this);
replicaStorage.addTrigger(mTriggerManager);
}
@Override
public Object beforeInsert(S replica) throws PersistException {
return beforeInsert(replica, false);
}
@Override
public Object beforeTryInsert(S replica) throws PersistException {
return beforeInsert(replica, true);
}
private Object beforeInsert(S replica, boolean forTry) throws PersistException {
final S master = mMasterStorage.prepare();
replica.copyAllProperties(master);
try {
if (forTry) {
if (!master.tryInsert()) {
throw abortTry();
}
} else {
master.insert();
}
} catch (UniqueConstraintException e) {
// This may be caused by an inconsistency between replica and
// master. Here's one scenerio: user called tryLoad and saw the
// entry does not exist. So instead of calling update, he/she calls
// insert. If the master entry exists, then there is an
// inconsistency. The code below checks for this specific kind of
// error and repairs it by inserting a record in the replica.
// Here's another scenerio: Unique constraint was caused by an
// inconsistency with the values of the alternate keys. User
// expected alternate keys to have unique values, as indicated by
// replica.
repair(replica);
// Throw exception since we don't know what the user's intentions
// really are.
throw e;
}
// Master may have applied sequences to unitialized primary keys, so
// copy primary keys to replica. Mark properties as dirty to allow
// primary key to be changed.
replica.markPropertiesDirty();
// Copy all properties in order to trigger constraints that
// master should have resolved.
master.copyAllProperties(replica);
return null;
}
@Override
public Object beforeUpdate(S replica) throws PersistException {
return beforeUpdate(replica, false);
}
@Override
public Object beforeTryUpdate(S replica) throws PersistException {
return beforeUpdate(replica, true);
}
private Object beforeUpdate(S replica, boolean forTry) throws PersistException {
final S master = mMasterStorage.prepare();
replica.copyPrimaryKeyProperties(master);
if (!replica.hasDirtyProperties()) {
// Nothing to update, but must load from master anyhow, since
// update must always perform a fresh load as a side-effect. We
// cannot simply call update on the master, since it may need a
// version property to be set. Setting the version has the
// side-effect of making the storable look dirty, so the master
// will perform an update. This in turn causes the version to
// increase for no reason.
try {
if (forTry) {
if (!master.tryLoad()) {
// Master record does not exist. To ensure consistency,
// delete record from replica.
tryDeleteReplica(replica);
throw abortTry();
}
} else {
try {
master.load();
} catch (FetchNoneException e) {
// Master record does not exist. To ensure consistency,
// delete record from replica.
tryDeleteReplica(replica);
throw e;
}
}
} catch (FetchException e) {
throw e.toPersistException
("Could not load master object for update: " + master.toStringKeyOnly());
}
} else {
replica.copyVersionProperty(master);
replica.copyDirtyProperties(master);
try {
if (forTry) {
if (!master.tryUpdate()) {
// Master record does not exist. To ensure consistency,
// delete record from replica.
tryDeleteReplica(replica);
throw abortTry();
}
} else {
try {
master.update();
} catch (PersistNoneException e) {
// Master record does not exist. To ensure consistency,
// delete record from replica.
tryDeleteReplica(replica);
throw e;
}
}
} catch (OptimisticLockException e) {
// This may be caused by an inconsistency between replica and
// master.
repair(replica);
// Throw original exception since we don't know what the user's
// intentions really are.
throw e;
}
}
// Copy master properties back, since its repository may have
// altered property values as a side effect.
master.copyUnequalProperties(replica);
return null;
}
@Override
public Object beforeDelete(S replica) throws PersistException {
S master = mMasterStorage.prepare();
replica.copyPrimaryKeyProperties(master);
// If this fails to delete anything, don't care. Any delete failure
// will be detected when the replica is deleted. If there was an
// inconsistency, it is resolved after the replica is deleted.
master.tryDelete();
return null;
}
/**
* Re-sync the replica to the master. The primary keys of both entries are
* assumed to match.
*
* @param replicaEntry current replica entry, or null if none
* @param masterEntry current master entry, or null if none
*/
void resyncEntries(S replicaEntry, S masterEntry) throws FetchException, PersistException {
if (replicaEntry == null && masterEntry == null) {
return;
}
Log log = LogFactory.getLog(ReplicatedRepository.class);
setReplicationDisabled(true);
try {
Transaction txn = mRepository.enterTransaction();
try {
if (replicaEntry != null) {
if (masterEntry == null) {
log.info("Deleting bogus replica entry: " + replicaEntry);
}
try {
replicaEntry.tryDelete();
} catch (PersistException e) {
log.error("Unable to delete replica entry: " + replicaEntry, e);
if (masterEntry != null) {
// Try to update instead.
S newReplicaEntry = mReplicaStorage.prepare();
transferToReplicaEntry(replicaEntry, masterEntry, newReplicaEntry);
log.info("Replacing corrupt replica entry with: " + newReplicaEntry);
try {
newReplicaEntry.update();
} catch (PersistException e2) {
log.error("Unable to update replica entry: " + replicaEntry, e2);
return;
}
}
}
}
if (masterEntry != null) {
S newReplicaEntry = mReplicaStorage.prepare();
if (replicaEntry == null) {
masterEntry.copyAllProperties(newReplicaEntry);
log.info("Adding missing replica entry: " + newReplicaEntry);
} else {
if (replicaEntry.equalProperties(masterEntry)) {
return;
}
transferToReplicaEntry(replicaEntry, masterEntry, newReplicaEntry);
log.info("Replacing stale replica entry with: " + newReplicaEntry);
}
if (!newReplicaEntry.tryInsert()) {
// Try to correct bizarre corruption.
newReplicaEntry.tryDelete();
newReplicaEntry.tryInsert();
}
}
txn.commit();
} finally {
txn.exit();
}
} finally {
setReplicationDisabled(false);
}
}
private void transferToReplicaEntry(S replicaEntry, S masterEntry, S newReplicaEntry) {
// First copy from old replica to preserve values of any independent
// properties. Be sure not to copy nulls from old replica to new
// replica, in case new non-nullable properties have been added. This
// is why copyUnequalProperties is called instead of copyAllProperties.
replicaEntry.copyUnequalProperties(newReplicaEntry);
// Calling copyAllProperties will skip unsupported independent
// properties in master, thus preserving old independent property values.
masterEntry.copyAllProperties(newReplicaEntry);
}
/**
* Runs a repair in a background thread. This is done for two reasons: It
* allows repair to not be hindered by locks acquired by transactions and
* repairs don't get rolled back when culprit exception is thrown. Culprit
* may be UniqueConstraintException or OptimisticLockException.
*/
private void repair(S replica) throws PersistException {
replica = (S) replica.copy();
S master = mMasterStorage.prepare();
- replica.copyPrimaryKeyProperties(master);
+ // Must copy more than just primary key properties to master since
+ // replica object might only have alternate keys.
+ replica.copyAllProperties(master);
try {
if (replica.tryLoad()) {
if (master.tryLoad()) {
if (replica.equalProperties(master)) {
// Both are equal -- no repair needed.
return;
}
}
} else {
try {
if (!master.tryLoad()) {
// Both are missing -- no repair needed.
return;
}
} catch (IllegalStateException e) {
// Can be caused by not fully defining the primary key on
// the replica, but an alternate key is. The insert will
// fail anyhow, so don't try to repair.
return;
}
}
} catch (FetchException e) {
throw e.toPersistException();
}
final S finalReplica = replica;
final S finalMaster = master;
RepairExecutor.execute(new Runnable() {
public void run() {
try {
Transaction txn = mRepository.enterTransaction();
try {
txn.setForUpdate(true);
if (finalReplica.tryLoad()) {
if (finalMaster.tryLoad()) {
resyncEntries(finalReplica, finalMaster);
} else {
resyncEntries(finalReplica, null);
}
} else if (finalMaster.tryLoad()) {
resyncEntries(null, finalMaster);
}
txn.commit();
} finally {
txn.exit();
}
} catch (FetchException fe) {
Log log = LogFactory.getLog(ReplicatedRepository.class);
log.warn("Unable to check if repair is required for " +
finalReplica.toStringKeyOnly(), fe);
} catch (PersistException pe) {
Log log = LogFactory.getLog(ReplicatedRepository.class);
log.error("Unable to repair entry " +
finalReplica.toStringKeyOnly(), pe);
}
}
});
}
boolean addTrigger(Trigger<? super S> trigger) {
return mTriggerManager.addTrigger(trigger);
}
boolean removeTrigger(Trigger<? super S> trigger) {
return mTriggerManager.removeTrigger(trigger);
}
/**
* Deletes the replica entry with replication disabled.
*/
boolean tryDeleteReplica(Storable replica) throws PersistException {
// Disable replication to prevent trigger from being invoked by
// deleting replica.
setReplicationDisabled(true);
try {
return replica.tryDelete();
} finally {
setReplicationDisabled(false);
}
}
/**
* Deletes the replica entry with replication disabled.
*/
void deleteReplica(Storable replica) throws PersistException {
// Disable replication to prevent trigger from being invoked by
// deleting replica.
setReplicationDisabled(true);
try {
replica.delete();
} finally {
setReplicationDisabled(false);
}
}
void setReplicationDisabled(boolean disabled) {
// This method disables not only this trigger, but all triggers added
// to manager.
if (disabled) {
mTriggerManager.localDisable();
} else {
mTriggerManager.localEnable();
}
}
}
| true | false | null | null |
diff --git a/sdkmanager/libs/sdkuilib/src/com/android/sdkuilib/internal/repository/UpdaterData.java b/sdkmanager/libs/sdkuilib/src/com/android/sdkuilib/internal/repository/UpdaterData.java
index 6cae085ac..486095ca7 100755
--- a/sdkmanager/libs/sdkuilib/src/com/android/sdkuilib/internal/repository/UpdaterData.java
+++ b/sdkmanager/libs/sdkuilib/src/com/android/sdkuilib/internal/repository/UpdaterData.java
@@ -1,536 +1,536 @@
/*
* Copyright (C) 2009 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.sdkuilib.internal.repository;
import com.android.prefs.AndroidLocation.AndroidLocationException;
import com.android.sdklib.ISdkLog;
import com.android.sdklib.SdkManager;
import com.android.sdklib.internal.avd.AvdManager;
import com.android.sdklib.internal.repository.AddonPackage;
import com.android.sdklib.internal.repository.Archive;
import com.android.sdklib.internal.repository.ITask;
import com.android.sdklib.internal.repository.ITaskFactory;
import com.android.sdklib.internal.repository.ITaskMonitor;
import com.android.sdklib.internal.repository.LocalSdkParser;
import com.android.sdklib.internal.repository.Package;
import com.android.sdklib.internal.repository.RepoSource;
import com.android.sdklib.internal.repository.RepoSources;
import com.android.sdklib.internal.repository.ToolPackage;
import com.android.sdklib.internal.repository.Package.UpdateInfo;
import com.android.sdkuilib.internal.repository.icons.ImageFactory;
import com.android.sdkuilib.repository.UpdaterWindow.ISdkListener;
import org.eclipse.swt.widgets.Shell;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* Data shared between {@link UpdaterWindowImpl} and its pages.
*/
class UpdaterData {
private String mOsSdkRoot;
private final ISdkLog mSdkLog;
private ITaskFactory mTaskFactory;
private boolean mUserCanChangeSdkRoot;
private SdkManager mSdkManager;
private AvdManager mAvdManager;
private final LocalSdkParser mLocalSdkParser = new LocalSdkParser();
private final RepoSources mSources = new RepoSources();
private final LocalSdkAdapter mLocalSdkAdapter = new LocalSdkAdapter(this);
private final RepoSourcesAdapter mSourcesAdapter = new RepoSourcesAdapter(this);
private ImageFactory mImageFactory;
private final SettingsController mSettingsController = new SettingsController();
private final ArrayList<ISdkListener> mListeners = new ArrayList<ISdkListener>();
private Shell mWindowShell;
public UpdaterData(String osSdkRoot, ISdkLog sdkLog) {
mOsSdkRoot = osSdkRoot;
mSdkLog = sdkLog;
initSdk();
}
// ----- getters, setters ----
public void setOsSdkRoot(String osSdkRoot) {
if (mOsSdkRoot == null || mOsSdkRoot.equals(osSdkRoot) == false) {
mOsSdkRoot = osSdkRoot;
initSdk();
}
}
public String getOsSdkRoot() {
return mOsSdkRoot;
}
public void setTaskFactory(ITaskFactory taskFactory) {
mTaskFactory = taskFactory;
}
public ITaskFactory getTaskFactory() {
return mTaskFactory;
}
public void setUserCanChangeSdkRoot(boolean userCanChangeSdkRoot) {
mUserCanChangeSdkRoot = userCanChangeSdkRoot;
}
public boolean canUserChangeSdkRoot() {
return mUserCanChangeSdkRoot;
}
public RepoSources getSources() {
return mSources;
}
public RepoSourcesAdapter getSourcesAdapter() {
return mSourcesAdapter;
}
public LocalSdkParser getLocalSdkParser() {
return mLocalSdkParser;
}
public LocalSdkAdapter getLocalSdkAdapter() {
return mLocalSdkAdapter;
}
public ISdkLog getSdkLog() {
return mSdkLog;
}
public void setImageFactory(ImageFactory imageFactory) {
mImageFactory = imageFactory;
}
public ImageFactory getImageFactory() {
return mImageFactory;
}
public SdkManager getSdkManager() {
return mSdkManager;
}
public AvdManager getAvdManager() {
return mAvdManager;
}
public SettingsController getSettingsController() {
return mSettingsController;
}
public void addListeners(ISdkListener listener) {
if (mListeners.contains(listener) == false) {
mListeners.add(listener);
}
}
public void removeListener(ISdkListener listener) {
mListeners.remove(listener);
}
public void setWindowShell(Shell windowShell) {
mWindowShell = windowShell;
}
public Shell getWindowShell() {
return mWindowShell;
}
// -----
/**
* Initializes the {@link SdkManager} and the {@link AvdManager}.
*/
private void initSdk() {
mSdkManager = SdkManager.createManager(mOsSdkRoot, mSdkLog);
try {
mAvdManager = null; // remove the old one if needed.
mAvdManager = new AvdManager(mSdkManager, mSdkLog);
} catch (AndroidLocationException e) {
mSdkLog.error(e, "Unable to read AVDs");
}
// notify adapters/parsers
// TODO
// notify listeners.
notifyListeners();
}
/**
* Reloads the SDK content (targets).
* <p/> This also reloads the AVDs in case their status changed.
* <p/>This does not notify the listeners ({@link ISdkListener}).
*/
public void reloadSdk() {
// reload SDK
mSdkManager.reloadSdk(mSdkLog);
// reload AVDs
if (mAvdManager != null) {
try {
mAvdManager.reloadAvds(mSdkLog);
} catch (AndroidLocationException e) {
// FIXME
}
}
// notify adapters?
mLocalSdkParser.clearPackages();
// TODO
// notify listeners
notifyListeners();
}
/**
* Reloads the AVDs.
* <p/>This does not notify the listeners.
*/
public void reloadAvds() {
// reload AVDs
if (mAvdManager != null) {
try {
mAvdManager.reloadAvds(mSdkLog);
} catch (AndroidLocationException e) {
mSdkLog.error(e, null);
}
}
}
/**
* Returns the list of installed packages, parsing them if this has not yet been done.
*/
public Package[] getInstalledPackage() {
LocalSdkParser parser = getLocalSdkParser();
Package[] packages = parser.getPackages();
if (packages == null) {
// load on demand the first time
packages = parser.parseSdk(getOsSdkRoot(), getSdkManager(), getSdkLog());
}
return packages;
}
/**
* Notify the listeners ({@link ISdkListener}) that the SDK was reloaded.
* <p/>This can be called from any thread.
*/
public void notifyListeners() {
if (mWindowShell != null && mListeners.size() > 0) {
mWindowShell.getDisplay().syncExec(new Runnable() {
public void run() {
for (ISdkListener listener : mListeners) {
try {
listener.onSdkChange();
} catch (Throwable t) {
mSdkLog.error(t, null);
}
}
}
});
}
}
/**
* Install the list of given {@link Archive}s. This is invoked by the user selecting some
* packages in the remote page and then clicking "install selected".
*
* @param archives The archives to install. Incompatible ones will be skipped.
*/
public void installArchives(final Collection<Archive> archives) {
if (mTaskFactory == null) {
throw new IllegalArgumentException("Task Factory is null");
}
final boolean forceHttp = getSettingsController().getForceHttp();
mTaskFactory.start("Installing Archives", new ITask() {
public void run(ITaskMonitor monitor) {
final int progressPerArchive = 2 * Archive.NUM_MONITOR_INC;
monitor.setProgressMax(archives.size() * progressPerArchive);
monitor.setDescription("Preparing to install archives");
boolean installedAddon = false;
boolean installedTools = false;
int numInstalled = 0;
for (Archive archive : archives) {
int nextProgress = monitor.getProgress() + progressPerArchive;
try {
if (monitor.isCancelRequested()) {
break;
}
if (archive.getParentPackage() instanceof AddonPackage) {
installedAddon = true;
} else if (archive.getParentPackage() instanceof ToolPackage) {
installedTools = true;
}
if (archive.install(mOsSdkRoot, forceHttp, mSdkManager, monitor)) {
numInstalled++;
}
} catch (Throwable t) {
// Display anything unexpected in the monitor.
String msg = t.getMessage();
if (msg != null) {
- monitor.setResult("Unexpected Error installing '%1$s: %2$s",
+ monitor.setResult("Unexpected Error installing '%1$s': %2$s",
archive.getParentPackage().getShortDescription(), msg);
} else {
// no error info? get the stack call to display it
// At least that'll give us a better bug report.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
t.printStackTrace(new PrintStream(baos));
// and display it
- monitor.setResult("Unexpected Error installing '%1$s\n%2$s",
+ monitor.setResult("Unexpected Error installing '%1$s'\n%2$s",
archive.getParentPackage().getShortDescription(),
baos.toString());
}
} finally {
// Always move the progress bar to the desired position.
// This allows internal methods to not have to care in case
// they abort early
monitor.incProgress(nextProgress - monitor.getProgress());
}
}
if (installedAddon) {
// Update the USB vendor ids for adb
try {
mSdkManager.updateAdb();
} catch (Exception e) {
mSdkLog.error(e, "Update ADB failed");
}
}
if (installedAddon || installedTools) {
// We need to restart ADB. Actually since we don't know if it's even
// running, maybe we should just kill it and not start it.
// Note: it turns out even under Windows we don't need to kill adb
// before updating the tools folder, as adb.exe is (surprisingly) not
// locked.
// TODO either bring in ddmlib and use its existing methods to stop adb
// or use a shell exec to tools/adb.
}
if (numInstalled == 0) {
monitor.setDescription("Done. Nothing was installed.");
} else {
monitor.setDescription("Done. %1$d %2$s installed.",
numInstalled,
numInstalled == 1 ? "package" : "packages");
//notify listeners something was installed, so that they can refresh
reloadSdk();
}
}
});
}
/**
* Tries to update all the *existing* local packages.
* This first refreshes all sources, then compares the available remote packages when
* the current local ones and suggest updates to be done to the user. Finally all
* selected updates are installed.
*
* @param selectedArchives The list of remote archive to consider for the update.
* This can be null, in which case a list of remote archive is fetched from all
* available sources.
*/
public void updateOrInstallAll(Collection<Archive> selectedArchives) {
if (selectedArchives == null) {
refreshSources(true);
}
final Map<Archive, Archive> updates = findUpdates(selectedArchives);
if (selectedArchives != null) {
// Not only we want to perform updates but we also want to install the
// selected archives. If they do not match an update, list them anyway
// except they map themselves to null (no "old" archive)
for (Archive a : selectedArchives) {
if (!updates.containsValue(a)) {
updates.put(a, null);
}
}
}
UpdateChooserDialog dialog = new UpdateChooserDialog(this, updates);
dialog.open();
Collection<Archive> result = dialog.getResult();
if (result != null && result.size() > 0) {
installArchives(result);
}
}
/**
* Refresh all sources. This is invoked either internally (reusing an existing monitor)
* or as a UI callback on the remote page "Refresh" button (in which case the monitor is
* null and a new task should be created.)
*
* @param forceFetching When true, load sources that haven't been loaded yet.
* When false, only refresh sources that have been loaded yet.
*/
public void refreshSources(final boolean forceFetching) {
assert mTaskFactory != null;
final boolean forceHttp = getSettingsController().getForceHttp();
mTaskFactory.start("Refresh Sources",new ITask() {
public void run(ITaskMonitor monitor) {
RepoSource[] sources = mSources.getSources();
monitor.setProgressMax(sources.length);
for (RepoSource source : sources) {
if (forceFetching ||
source.getPackages() != null ||
source.getFetchError() != null) {
source.load(monitor.createSubMonitor(1), forceHttp);
}
monitor.incProgress(1);
}
}
});
}
/**
* Check the local archives vs the remote available packages to find potential updates.
* Return a map [remote archive => local archive] of suitable update candidates.
* Returns null if there's an unexpected error. Otherwise returns a map that can be
* empty but not null.
*
* @param selectedArchives The list of remote archive to consider for the update.
* This can be null, in which case a list of remote archive is fetched from all
* available sources.
*/
private Map<Archive, Archive> findUpdates(Collection<Archive> selectedArchives) {
// Map [remote archive => local archive] of suitable update candidates
Map<Archive, Archive> result = new HashMap<Archive, Archive>();
// First go thru all sources and make a local list of all available archives
// sorted by package class.
HashMap<Class<? extends Package>, ArrayList<Archive>> availPkgs =
new HashMap<Class<? extends Package>, ArrayList<Archive>>();
if (selectedArchives != null) {
// Only consider the archives given
for (Archive a : selectedArchives) {
// Only add compatible archives
if (a.isCompatible()) {
Class<? extends Package> clazz = a.getParentPackage().getClass();
ArrayList<Archive> list = availPkgs.get(clazz);
if (list == null) {
availPkgs.put(clazz, list = new ArrayList<Archive>());
}
list.add(a);
}
}
} else {
// Get all the available archives from all loaded sources
RepoSource[] remoteSources = getSources().getSources();
for (RepoSource remoteSrc : remoteSources) {
Package[] remotePkgs = remoteSrc.getPackages();
if (remotePkgs != null) {
for (Package remotePkg : remotePkgs) {
Class<? extends Package> clazz = remotePkg.getClass();
ArrayList<Archive> list = availPkgs.get(clazz);
if (list == null) {
availPkgs.put(clazz, list = new ArrayList<Archive>());
}
for (Archive a : remotePkg.getArchives()) {
// Only add compatible archives
if (a.isCompatible()) {
list.add(a);
}
}
}
}
}
}
Package[] localPkgs = getLocalSdkParser().getPackages();
if (localPkgs == null) {
// This is unexpected. The local sdk parser should have been called first.
return null;
}
for (Package localPkg : localPkgs) {
// get the available archive list for this package type
ArrayList<Archive> list = availPkgs.get(localPkg.getClass());
// if this list is empty, we'll never find anything that matches
if (list == null || list.size() == 0) {
continue;
}
// local packages should have one archive at most
Archive[] localArchives = localPkg.getArchives();
if (localArchives != null && localArchives.length > 0) {
Archive localArchive = localArchives[0];
// only consider archive compatible with the current platform
if (localArchive != null && localArchive.isCompatible()) {
// We checked all this archive stuff because that's what eventually gets
// installed, but the "update" mechanism really works on packages. So now
// the real question: is there a remote package that can update this
// local package?
for (Archive availArchive : list) {
UpdateInfo info = localPkg.canBeUpdatedBy(availArchive.getParentPackage());
if (info == UpdateInfo.UPDATE) {
// Found one!
result.put(availArchive, localArchive);
break;
}
}
}
}
}
return result;
}
}
diff --git a/sdkmanager/libs/sdkuilib/src/com/android/sdkuilib/internal/widgets/AvdSelector.java b/sdkmanager/libs/sdkuilib/src/com/android/sdkuilib/internal/widgets/AvdSelector.java
index a85c1b81e..96d1b65f5 100644
--- a/sdkmanager/libs/sdkuilib/src/com/android/sdkuilib/internal/widgets/AvdSelector.java
+++ b/sdkmanager/libs/sdkuilib/src/com/android/sdkuilib/internal/widgets/AvdSelector.java
@@ -1,1056 +1,1056 @@
/*
* Copyright (C) 2009 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.sdkuilib.internal.widgets;
import com.android.prefs.AndroidLocation.AndroidLocationException;
import com.android.sdklib.IAndroidTarget;
import com.android.sdklib.ISdkLog;
import com.android.sdklib.NullSdkLog;
import com.android.sdklib.SdkConstants;
import com.android.sdklib.internal.avd.AvdManager;
import com.android.sdklib.internal.avd.AvdManager.AvdInfo;
import com.android.sdklib.internal.avd.AvdManager.AvdInfo.AvdStatus;
import com.android.sdklib.internal.repository.ITask;
import com.android.sdklib.internal.repository.ITaskMonitor;
import com.android.sdkuilib.internal.repository.icons.ImageFactory;
import com.android.sdkuilib.internal.tasks.ProgressTask;
import com.android.sdkuilib.repository.UpdaterWindow;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
/**
* The AVD selector is a table that is added to the given parent composite.
* <p/>
* After using one of the constructors, call {@link #setSelection(AvdInfo)},
* {@link #setSelectionListener(SelectionListener)} and finally use
* {@link #getSelected()} to retrieve the selection.
*/
public final class AvdSelector {
private static int NUM_COL = 2;
private final DisplayMode mDisplayMode;
private AvdManager mAvdManager;
private final String mOsSdkPath;
private Table mTable;
private Button mDeleteButton;
private Button mDetailsButton;
private Button mNewButton;
private Button mRefreshButton;
private Button mManagerButton;
private Button mUpdateButton;
private Button mStartButton;
private SelectionListener mSelectionListener;
private IAvdFilter mTargetFilter;
/** Defaults to true. Changed by the {@link #setEnabled(boolean)} method to represent the
* "global" enabled state on this composite. */
private boolean mIsEnabled = true;
private ImageFactory mImageFactory;
private Image mOkImage;
private Image mBrokenImage;
/**
* The display mode of the AVD Selector.
*/
public static enum DisplayMode {
/**
* Manager mode. Invalid AVDs are displayed. Buttons to create/delete AVDs
*/
MANAGER,
/**
* Non manager mode. Only valid AVDs are displayed. Cannot create/delete AVDs, but
* there is a button to open the AVD Manager.
* In the "check" selection mode, checkboxes are displayed on each line
* and {@link AvdSelector#getSelected()} returns the line that is checked
* even if it is not the currently selected line. Only one line can
* be checked at once.
*/
SIMPLE_CHECK,
/**
* Non manager mode. Only valid AVDs are displayed. Cannot create/delete AVDs, but
* there is a button to open the AVD Manager.
* In the "select" selection mode, there are no checkboxes and
* {@link AvdSelector#getSelected()} returns the line currently selected.
* Only one line can be selected at once.
*/
SIMPLE_SELECTION,
}
/**
* A filter to control the whether or not an AVD should be displayed by the AVD Selector.
*/
public interface IAvdFilter {
/**
* Called before {@link #accept(AvdInfo)} is called for any AVD.
*/
void prepare();
/**
* Called to decided whether an AVD should be displayed.
* @param avd the AVD to test.
* @return true if the AVD should be displayed.
*/
boolean accept(AvdInfo avd);
/**
* Called after {@link #accept(AvdInfo)} has been called on all the AVDs.
*/
void cleanup();
}
/**
* Internal implementation of {@link IAvdFilter} to filter out the AVDs that are not
* running an image compatible with a specific target.
*/
private final static class TargetBasedFilter implements IAvdFilter {
private final IAndroidTarget mTarget;
TargetBasedFilter(IAndroidTarget target) {
mTarget = target;
}
public void prepare() {
// nothing to prepare
}
public boolean accept(AvdInfo avd) {
if (avd != null) {
return mTarget.isCompatibleBaseFor(avd.getTarget());
}
return false;
}
public void cleanup() {
// nothing to clean up
}
}
/**
* Creates a new SDK Target Selector, and fills it with a list of {@link AvdInfo}, filtered
* by a {@link IAndroidTarget}.
* <p/>Only the {@link AvdInfo} able to run application developed for the given
* {@link IAndroidTarget} will be displayed.
*
* @param parent The parent composite where the selector will be added.
* @param osSdkPath The SDK root path. When not null, enables the start button to start
* an emulator on a given AVD.
* @param manager the AVD manager.
* @param filter When non-null, will allow filtering the AVDs to display.
* @param displayMode The display mode ({@link DisplayMode}).
*
* TODO: pass an ISdkLog and use it when reloading, starting the emulator, etc.
*/
public AvdSelector(Composite parent,
String osSdkPath,
AvdManager manager,
IAvdFilter filter,
DisplayMode displayMode) {
mOsSdkPath = osSdkPath;
mAvdManager = manager;
mTargetFilter = filter;
mDisplayMode = displayMode;
// get some bitmaps.
mImageFactory = new ImageFactory(parent.getDisplay());
mOkImage = mImageFactory.getImageByName("accept_icon16.png");
mBrokenImage = mImageFactory.getImageByName("reject_icon16.png");
// Layout has 2 columns
Composite group = new Composite(parent, SWT.NONE);
GridLayout gl;
group.setLayout(gl = new GridLayout(NUM_COL, false /*makeColumnsEqualWidth*/));
gl.marginHeight = gl.marginWidth = 0;
group.setLayoutData(new GridData(GridData.FILL_BOTH));
group.setFont(parent.getFont());
group.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent arg0) {
mImageFactory.dispose();
}
});
int style = SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER;
if (displayMode == DisplayMode.SIMPLE_CHECK) {
style |= SWT.CHECK;
}
mTable = new Table(group, style);
mTable.setHeaderVisible(true);
mTable.setLinesVisible(false);
setTableHeightHint(0);
Composite buttons = new Composite(group, SWT.NONE);
buttons.setLayout(gl = new GridLayout(1, false /*makeColumnsEqualWidth*/));
gl.marginHeight = gl.marginWidth = 0;
buttons.setLayoutData(new GridData(GridData.FILL_VERTICAL));
buttons.setFont(group.getFont());
if (displayMode == DisplayMode.MANAGER) {
mNewButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
mNewButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mNewButton.setText("New...");
mNewButton.setToolTipText("Creates a new AVD.");
mNewButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
onNew();
}
});
mDeleteButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
mDeleteButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mDeleteButton.setText("Delete...");
mDeleteButton.setToolTipText("Deletes the selected AVD.");
mDeleteButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
onDelete();
}
});
mUpdateButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
mUpdateButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mUpdateButton.setText("Update...");
mUpdateButton.setToolTipText("Updates the path of the selected AVD.");
mUpdateButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
onUpdate();
}
});
Label l = new Label(buttons, SWT.SEPARATOR | SWT.HORIZONTAL);
l.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
}
mDetailsButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
mDetailsButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mDetailsButton.setText("Details...");
mDetailsButton.setToolTipText("Diplays details of the selected AVD.");
mDetailsButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
onDetails();
}
});
mStartButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
mStartButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mStartButton.setText("Start...");
mStartButton.setToolTipText("Starts the selected AVD.");
mStartButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
onStart();
}
});
Composite padding = new Composite(buttons, SWT.NONE);
padding.setLayoutData(new GridData(GridData.FILL_VERTICAL));
mRefreshButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
mRefreshButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mRefreshButton.setText("Resfresh");
- mRefreshButton.setToolTipText("Reloads the list of AVD.\nUse this if you create AVD from the command line.");
+ mRefreshButton.setText("Refresh");
+ mRefreshButton.setToolTipText("Reloads the list of AVD.\nUse this if you create AVDs from the command line.");
mRefreshButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
refresh(true);
}
});
if (displayMode != DisplayMode.MANAGER) {
mManagerButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
mManagerButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
mManagerButton.setText("Manager...");
mManagerButton.setToolTipText("Launches the AVD manager.");
mManagerButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
onManager();
}
});
} else {
Composite legend = new Composite(group, SWT.NONE);
legend.setLayout(gl = new GridLayout(2, false /*makeColumnsEqualWidth*/));
gl.marginHeight = gl.marginWidth = 0;
legend.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false,
NUM_COL, 1));
legend.setFont(group.getFont());
new Label(legend, SWT.NONE).setImage(mOkImage);
new Label(legend, SWT.NONE).setText("A valid Android Virtual Device.");
new Label(legend, SWT.NONE).setImage(mBrokenImage);
new Label(legend, SWT.NONE).setText(
"An Android Virtual Device that failed to load. Click 'Details' to see the error.");
}
// create the table columns
final TableColumn column0 = new TableColumn(mTable, SWT.NONE);
column0.setText("AVD Name");
final TableColumn column1 = new TableColumn(mTable, SWT.NONE);
column1.setText("Target Name");
final TableColumn column2 = new TableColumn(mTable, SWT.NONE);
column2.setText("Platform");
final TableColumn column3 = new TableColumn(mTable, SWT.NONE);
column3.setText("API Level");
adjustColumnsWidth(mTable, column0, column1, column2, column3);
setupSelectionListener(mTable);
fillTable(mTable);
}
/**
* Creates a new SDK Target Selector, and fills it with a list of {@link AvdInfo}.
*
* @param parent The parent composite where the selector will be added.
* @param manager the AVD manager.
* @param displayMode The display mode ({@link DisplayMode}).
*/
public AvdSelector(Composite parent,
String osSdkPath,
AvdManager manager,
DisplayMode displayMode) {
this(parent, osSdkPath, manager, (IAvdFilter)null /* filter */, displayMode);
}
/**
* Creates a new SDK Target Selector, and fills it with a list of {@link AvdInfo}, filtered
* by an {@link IAndroidTarget}.
* <p/>Only the {@link AvdInfo} able to run applications developed for the given
* {@link IAndroidTarget} will be displayed.
*
* @param parent The parent composite where the selector will be added.
* @param manager the AVD manager.
* @param filter Only shows the AVDs matching this target (must not be null).
* @param displayMode The display mode ({@link DisplayMode}).
*/
public AvdSelector(Composite parent,
String osSdkPath,
AvdManager manager,
IAndroidTarget filter,
DisplayMode displayMode) {
this(parent, osSdkPath, manager, new TargetBasedFilter(filter), displayMode);
}
/**
* Sets the table grid layout data.
*
* @param heightHint If > 0, the height hint is set to the requested value.
*/
public void setTableHeightHint(int heightHint) {
GridData data = new GridData();
if (heightHint > 0) {
data.heightHint = heightHint;
}
data.grabExcessVerticalSpace = true;
data.grabExcessHorizontalSpace = true;
data.horizontalAlignment = GridData.FILL;
data.verticalAlignment = GridData.FILL;
mTable.setLayoutData(data);
}
/**
* Refresh the display of Android Virtual Devices.
* Tries to keep the selection.
* <p/>
* This must be called from the UI thread.
*
* @param reload if true, the AVD manager will reload the AVD from the disk.
* @return false if the reloading failed. This is always true if <var>reload</var> is
* <code>false</code>.
*/
public boolean refresh(boolean reload) {
if (reload) {
try {
mAvdManager.reloadAvds(NullSdkLog.getLogger());
} catch (AndroidLocationException e) {
return false;
}
}
AvdInfo selected = getSelected();
fillTable(mTable);
setSelection(selected);
return true;
}
/**
* Sets a new AVD manager
* This does not refresh the display. Call {@link #refresh(boolean)} to do so.
* @param manager the AVD manager.
*/
public void setManager(AvdManager manager) {
mAvdManager = manager;
}
/**
* Sets a new AVD filter.
* This does not refresh the display. Call {@link #refresh(boolean)} to do so.
* @param filter An IAvdFilter. If non-null, this will filter out the AVD to not display.
*/
public void setFilter(IAvdFilter filter) {
mTargetFilter = filter;
}
/**
* Sets a new Android Target-based AVD filter.
* This does not refresh the display. Call {@link #refresh(boolean)} to do so.
* @param target An IAndroidTarget. If non-null, only AVD whose target are compatible with the
* filter target will displayed an available for selection.
*/
public void setFilter(IAndroidTarget target) {
if (target != null) {
mTargetFilter = new TargetBasedFilter(target);
} else {
mTargetFilter = null;
}
}
/**
* Sets a selection listener. Set it to null to remove it.
* The listener will be called <em>after</em> this table processed its selection
* events so that the caller can see the updated state.
* <p/>
* The event's item contains a {@link TableItem}.
* The {@link TableItem#getData()} contains an {@link IAndroidTarget}.
* <p/>
* It is recommended that the caller uses the {@link #getSelected()} method instead.
* <p/>
* The default behavior for double click (when not in {@link DisplayMode#SIMPLE_CHECK}) is to
* display the details of the selected AVD.<br>
* To disable it (when you provide your own double click action), set
* {@link SelectionEvent#doit} to false in
* {@link SelectionListener#widgetDefaultSelected(SelectionEvent)}
*
* @param selectionListener The new listener or null to remove it.
*/
public void setSelectionListener(SelectionListener selectionListener) {
mSelectionListener = selectionListener;
}
/**
* Sets the current target selection.
* <p/>
* If the selection is actually changed, this will invoke the selection listener
* (if any) with a null event.
*
* @param target the target to be selected. Use null to deselect everything.
* @return true if the target could be selected, false otherwise.
*/
public boolean setSelection(AvdInfo target) {
boolean found = false;
boolean modified = false;
int selIndex = mTable.getSelectionIndex();
int index = 0;
for (TableItem i : mTable.getItems()) {
if (mDisplayMode == DisplayMode.SIMPLE_CHECK) {
if ((AvdInfo) i.getData() == target) {
found = true;
if (!i.getChecked()) {
modified = true;
i.setChecked(true);
}
} else if (i.getChecked()) {
modified = true;
i.setChecked(false);
}
} else {
if ((AvdInfo) i.getData() == target) {
found = true;
if (index != selIndex) {
mTable.setSelection(index);
modified = true;
}
break;
}
index++;
}
}
if (modified && mSelectionListener != null) {
mSelectionListener.widgetSelected(null);
}
enableActionButtons();
return found;
}
/**
* Returns the currently selected item. In {@link DisplayMode#SIMPLE_CHECK} mode this will
* return the {@link AvdInfo} that is checked instead of the list selection.
*
* @return The currently selected item or null.
*/
public AvdInfo getSelected() {
if (mDisplayMode == DisplayMode.SIMPLE_CHECK) {
for (TableItem i : mTable.getItems()) {
if (i.getChecked()) {
return (AvdInfo) i.getData();
}
}
} else {
int selIndex = mTable.getSelectionIndex();
if (selIndex >= 0) {
return (AvdInfo) mTable.getItem(selIndex).getData();
}
}
return null;
}
/**
* Enables the receiver if the argument is true, and disables it otherwise.
* A disabled control is typically not selectable from the user interface
* and draws with an inactive or "grayed" look.
*
* @param enabled the new enabled state.
*/
public void setEnabled(boolean enabled) {
mIsEnabled = enabled;
mTable.setEnabled(mIsEnabled);
mRefreshButton.setEnabled(mIsEnabled);
if (mNewButton != null) {
mNewButton.setEnabled(mIsEnabled);
}
if (mManagerButton != null) {
mManagerButton.setEnabled(mIsEnabled);
}
enableActionButtons();
}
public boolean isEnabled() {
return mIsEnabled;
}
/**
* Adds a listener to adjust the columns width when the parent is resized.
* <p/>
* If we need something more fancy, we might want to use this:
* http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet77.java?view=co
*/
private void adjustColumnsWidth(final Table table,
final TableColumn column0,
final TableColumn column1,
final TableColumn column2,
final TableColumn column3) {
// Add a listener to resize the column to the full width of the table
table.addControlListener(new ControlAdapter() {
@Override
public void controlResized(ControlEvent e) {
Rectangle r = table.getClientArea();
column0.setWidth(r.width * 25 / 100); // 25%
column1.setWidth(r.width * 45 / 100); // 45%
column2.setWidth(r.width * 15 / 100); // 15%
column3.setWidth(r.width * 15 / 100); // 15%
}
});
}
/**
* Creates a selection listener that will check or uncheck the whole line when
* double-clicked (aka "the default selection").
*/
private void setupSelectionListener(final Table table) {
// Add a selection listener that will check/uncheck items when they are double-clicked
table.addSelectionListener(new SelectionListener() {
/**
* Handles single-click selection on the table.
* {@inheritDoc}
*/
public void widgetSelected(SelectionEvent e) {
if (e.item instanceof TableItem) {
TableItem i = (TableItem) e.item;
enforceSingleSelection(i);
}
if (mSelectionListener != null) {
mSelectionListener.widgetSelected(e);
}
enableActionButtons();
}
/**
* Handles double-click selection on the table.
* Note that the single-click handler will probably already have been called.
*
* On double-click, <em>always</em> check the table item.
*
* {@inheritDoc}
*/
public void widgetDefaultSelected(SelectionEvent e) {
if (e.item instanceof TableItem) {
TableItem i = (TableItem) e.item;
if (mDisplayMode == DisplayMode.SIMPLE_CHECK) {
i.setChecked(true);
}
enforceSingleSelection(i);
}
// whether or not we display details. default: true when not in SIMPLE_CHECK mode.
boolean showDetails = mDisplayMode != DisplayMode.SIMPLE_CHECK;
if (mSelectionListener != null) {
mSelectionListener.widgetDefaultSelected(e);
showDetails &= e.doit; // enforce false in SIMPLE_CHECK
}
if (showDetails) {
onDetails();
}
enableActionButtons();
}
/**
* To ensure single selection, uncheck all other items when this one is selected.
* This makes the chekboxes act as radio buttons.
*/
private void enforceSingleSelection(TableItem item) {
if (mDisplayMode == DisplayMode.SIMPLE_CHECK) {
if (item.getChecked()) {
Table parentTable = item.getParent();
for (TableItem i2 : parentTable.getItems()) {
if (i2 != item && i2.getChecked()) {
i2.setChecked(false);
}
}
}
} else {
// pass
}
}
});
}
/**
* Fills the table with all AVD.
* The table columns are:
* <ul>
* <li>column 0: sdk name
* <li>column 1: sdk vendor
* <li>column 2: sdk api name
* <li>column 3: sdk version
* </ul>
*/
private void fillTable(final Table table) {
table.removeAll();
// get the AVDs
AvdInfo avds[] = null;
if (mAvdManager != null) {
if (mDisplayMode == DisplayMode.MANAGER) {
avds = mAvdManager.getAllAvds();
} else {
avds = mAvdManager.getValidAvds();
}
}
if (avds != null && avds.length > 0) {
table.setEnabled(true);
if (mTargetFilter != null) {
mTargetFilter.prepare();
}
for (AvdInfo avd : avds) {
if (mTargetFilter == null || mTargetFilter.accept(avd)) {
TableItem item = new TableItem(table, SWT.NONE);
item.setData(avd);
item.setText(0, avd.getName());
if (mDisplayMode == DisplayMode.MANAGER) {
item.setImage(0, avd.getStatus() == AvdStatus.OK ? mOkImage : mBrokenImage);
}
IAndroidTarget target = avd.getTarget();
if (target != null) {
item.setText(1, target.getFullName());
item.setText(2, target.getVersionName());
item.setText(3, target.getVersion().getApiString());
} else {
item.setText(1, "?");
item.setText(2, "?");
item.setText(3, "?");
}
}
}
if (mTargetFilter != null) {
mTargetFilter.cleanup();
}
}
if (table.getItemCount() == 0) {
table.setEnabled(false);
TableItem item = new TableItem(table, SWT.NONE);
item.setData(null);
item.setText(0, "--");
item.setText(1, "No AVD available");
item.setText(2, "--");
item.setText(3, "--");
}
}
/**
* Returns the currently selected AVD in the table.
* <p/>
* Unlike {@link #getSelected()} this will always return the item being selected
* in the list, ignoring the check boxes state in {@link DisplayMode#SIMPLE_CHECK} mode.
*/
private AvdInfo getTableSelection() {
int selIndex = mTable.getSelectionIndex();
if (selIndex >= 0) {
return (AvdInfo) mTable.getItem(selIndex).getData();
}
return null;
}
/**
* Updates the enable state of the Details, Start, Delete and Update buttons.
*/
private void enableActionButtons() {
if (mIsEnabled == false) {
mDetailsButton.setEnabled(false);
mStartButton.setEnabled(false);
if (mDeleteButton != null) {
mDeleteButton.setEnabled(false);
}
if (mUpdateButton != null) {
mUpdateButton.setEnabled(false);
}
} else {
AvdInfo selection = getTableSelection();
boolean hasSelection = selection != null;
mDetailsButton.setEnabled(hasSelection);
mStartButton.setEnabled(mOsSdkPath != null &&
hasSelection &&
selection.getStatus() == AvdStatus.OK);
if (mDeleteButton != null) {
mDeleteButton.setEnabled(hasSelection);
}
if (mUpdateButton != null) {
mUpdateButton.setEnabled(hasSelection &&
selection.getStatus() == AvdStatus.ERROR_IMAGE_DIR);
}
}
}
private void onNew() {
AvdCreationDialog dlg = new AvdCreationDialog(mTable.getShell(), mAvdManager,
mImageFactory);
if (dlg.open() == Window.OK) {
refresh(false /*reload*/);
}
}
private void onDetails() {
final AvdInfo avdInfo = getTableSelection();
AvdDetailsDialog dlg = new AvdDetailsDialog(mTable.getShell(), avdInfo);
dlg.open();
}
private void onDelete() {
final AvdInfo avdInfo = getTableSelection();
// get the current Display
final Display display = mTable.getDisplay();
// Confirm you want to delete this AVD
final boolean[] result = new boolean[1];
display.syncExec(new Runnable() {
public void run() {
Shell shell = display.getActiveShell();
result[0] = MessageDialog.openQuestion(shell,
"Delete Android Virtual Device",
String.format(
"Please confirm that you want to delete the Android Virtual Device named '%s'. This operation cannot be reverted.",
avdInfo.getName()));
}
});
if (result[0] == false) {
return;
}
// log for this action.
SdkLog log = new SdkLog(
String.format("Result of deleting AVD '%s':", avdInfo.getName()),
display);
// delete the AVD
boolean success = mAvdManager.deleteAvd(avdInfo, log);
// display the result
log.displayResult(success);
if (success) {
refresh(false /*reload*/);
}
}
private void onUpdate() {
final AvdInfo avdInfo = getTableSelection();
// get the current Display
final Display display = mTable.getDisplay();
// log for this action.
SdkLog log = new SdkLog(
String.format("Result of updating AVD '%s':", avdInfo.getName()),
display);
// delete the AVD
try {
mAvdManager.updateAvd(avdInfo, log);
// display the result
log.displayResult(true /* success */);
refresh(false /*reload*/);
} catch (IOException e) {
log.error(e, null);
log.displayResult(false /* success */);
}
}
private void onManager() {
UpdaterWindow window = new UpdaterWindow(
mTable.getShell(),
null /*sdk log*/,
mAvdManager.getSdkManager().getLocation(),
false /*userCanChangeSdkRoot*/);
window.open();
refresh(true /*reload*/); // UpdaterWindow uses its own AVD manager so this one must reload.
}
private void onStart() {
AvdInfo avdInfo = getTableSelection();
if (avdInfo == null || mOsSdkPath == null) {
return;
}
String path = mOsSdkPath +
File.separator +
SdkConstants.OS_SDK_TOOLS_FOLDER +
SdkConstants.FN_EMULATOR;
final String avdName = avdInfo.getName();
// build the command line based on the available parameters.
ArrayList<String> list = new ArrayList<String>();
list.add(path);
list.add("-avd"); //$NON-NLS-1$
list.add(avdName);
// convert the list into an array for the call to exec.
final String[] command = list.toArray(new String[list.size()]);
// launch the emulator
new ProgressTask(mTable.getShell(),
"Starting Android Emulator",
new ITask() {
public void run(ITaskMonitor monitor) {
try {
monitor.setDescription("Starting emulator for AVD '%1$s'", avdName);
int n = 10;
monitor.setProgressMax(n);
Process process = Runtime.getRuntime().exec(command);
grabEmulatorOutput(process, monitor);
// This small wait prevents the dialog from closing too fast:
// When it works, the emulator returns immediately, even if no UI
// is shown yet. And when it fails (because the AVD is locked/running)
// if we don't have a wait we don't capture the error for some reason.
for (int i = 0; i < n; i++) {
try {
Thread.sleep(100);
monitor.incProgress(1);
} catch (InterruptedException e) {
// ignore
}
}
} catch (IOException e) {
monitor.setResult("Failed to start emulator: %1$s", e.getMessage());
}
}
});
}
/**
* Get the stderr/stdout outputs of a process and return when the process is done.
* Both <b>must</b> be read or the process will block on windows.
* @param process The process to get the output from.
* @param monitor An {@link ISdkLog} to capture errors.
*/
private void grabEmulatorOutput(final Process process, final ITaskMonitor monitor) {
// read the lines as they come. if null is returned, it's because the process finished
new Thread("emu-stderr") { //$NON-NLS-1$
@Override
public void run() {
// create a buffer to read the stderr output
InputStreamReader is = new InputStreamReader(process.getErrorStream());
BufferedReader errReader = new BufferedReader(is);
try {
while (true) {
String line = errReader.readLine();
if (line != null) {
monitor.setResult("%1$s", line); //$NON-NLS-1$
} else {
break;
}
}
} catch (IOException e) {
// do nothing.
}
}
}.start();
new Thread("emu-stdout") { //$NON-NLS-1$
@Override
public void run() {
InputStreamReader is = new InputStreamReader(process.getInputStream());
BufferedReader outReader = new BufferedReader(is);
try {
while (true) {
String line = outReader.readLine();
if (line != null) {
monitor.setResult("%1$s", line); //$NON-NLS-1$
} else {
break;
}
}
} catch (IOException e) {
// do nothing.
}
}
}.start();
}
/**
* Collects all log from the AVD action and displays it in a dialog.
*/
static class SdkLog implements ISdkLog {
final ArrayList<String> logMessages = new ArrayList<String>();
private final String mMessage;
private final Display mDisplay;
public SdkLog(String message, Display display) {
mMessage = message;
mDisplay = display;
}
public void error(Throwable throwable, String errorFormat, Object... arg) {
if (errorFormat != null) {
logMessages.add(String.format("Error: " + errorFormat, arg));
}
if (throwable != null) {
logMessages.add(throwable.getMessage());
}
}
public void warning(String warningFormat, Object... arg) {
logMessages.add(String.format("Warning: " + warningFormat, arg));
}
public void printf(String msgFormat, Object... arg) {
logMessages.add(String.format(msgFormat, arg));
}
/**
* Displays the log if anything was captured.
*/
public void displayResult(final boolean success) {
if (logMessages.size() > 0) {
final StringBuilder sb = new StringBuilder(mMessage + "\n\n");
for (String msg : logMessages) {
sb.append(msg);
}
// display the message
// dialog box only run in ui thread..
mDisplay.asyncExec(new Runnable() {
public void run() {
Shell shell = mDisplay.getActiveShell();
if (success) {
MessageDialog.openInformation(shell, "Android Virtual Devices Manager",
sb.toString());
} else {
MessageDialog.openError(shell, "Android Virtual Devices Manager",
sb.toString());
}
}
});
}
}
}
}
| false | false | null | null |
diff --git a/src/com/simple/calculator/Calculate.java b/src/com/simple/calculator/Calculate.java
index fc59f58..d854ea4 100644
--- a/src/com/simple/calculator/Calculate.java
+++ b/src/com/simple/calculator/Calculate.java
@@ -1,185 +1,188 @@
package com.simple.calculator;
import java.util.ArrayList;
public class Calculate {
static String result;
public Calculate(ArrayList<String> list){
ArrayList<String> array = list;
for (int i = 0; i < array.size(); i++){ // Searches for (
if (array.get(i).equals("(")){
int count = 1;
int j = i + 1;
while (count != 0){ // Searches for the right )
if (array.get(j).equals("(")){
count++;
}
else if (array.get(j).equals(")")){
count--;
}
if (count == 0){
break;
}
j++;
}
ArrayList<String> subArray = new ArrayList<String>(); // makes a new subarraylist
for (int k = i + 1; k < j; k++){ // Adds the objects between the brackets into the subarraylist
subArray.add(array.get(k));
}
new Calculate(subArray); // Calls Calculate(subarray)(recursion)
String q = getResult();
array.set(i, q);
for(int l = j; l > i; l--){
array.remove(l);
}
}
}
for (int i = 0; i < array.size(); i++){ // Searches for ² and √
if (array.get(i).equals("²") || array.get(i).equals("√")){
if (array.get(i).equals("²")){ // Calculates x² by calling square(x)
String x = square(array.get(i- 1));
array.set(i, x);
result = array.get(i);
array.remove(i - 1);
i--;
}
else{ // Calculates √x by calling squareRoot(x)
String x = squareRoot(array.get(i + 1));
array.set(i, x);
result = array.get(i);
array.remove(i + 1);
}
}
}
for (int i = 0; i < array.size(); i++){ // Searches for * and ÷
if (array.get(i).equals("*") || array.get(i).equals("÷")){
if (array.get(i).equals("*")){ // Calculates x * y by calling multiplication(x, y)
String x = multiplication(array.get(i- 1), array.get(i + 1));
array.set(i, x);
result = array.get(i);
array.remove(i + 1);
array.remove(i - 1);
i--;
}
else{ // Calculates x / y by calling division(x, y)
String x = division(array.get(i- 1), array.get(i + 1));
array.set(i, x);
result = array.get(i);
array.remove(i + 1);
array.remove(i - 1);
i--;
}
}
}
for (int i = 0; i < array.size(); i++){ // Searches for + and -
if (array.get(i).equals("+") || array.get(i).equals("-")){
if (array.get(i).equals("+")){ // Calculates x + y by calling addition(x, y)
String x = addition(array.get(i- 1), array.get(i + 1));
array.set(i, x);
result = array.get(i);
array.remove(i + 1);
array.remove(i - 1);
i--;
}
else{ // Calculates x - y by calling subtraction(x, y)
String x = subtraction(array.get(i- 1), array.get(i + 1));
array.set(i, x);
result = array.get(i);
array.remove(i + 1);
array.remove(i - 1);
i--;
}
}
}
+ if (array.size() == 1){
+ result = array.get(0);
+ }
}
public static String addition(String x, String y){ // Calculates x + y
double xx = Double.parseDouble(x);
double yy = Double.parseDouble(y);
double zz = xx + yy;
return Double.toString(zz);
}
public static String subtraction(String x, String y){ // Calculates x - y
double xx = Double.parseDouble(x);
double yy = Double.parseDouble(y);
double zz = xx - yy;
return Double.toString(zz);
}
public static String multiplication(String x, String y){ // Calculates x * y
double xx = Double.parseDouble(x);
double yy = Double.parseDouble(y);
double zz = xx * yy;
return Double.toString(zz);
}
public static String division(String x, String y){ // Calculates x / y
double xx = Double.parseDouble(x);
double yy = Double.parseDouble(y);
double zz = xx / yy;
return Double.toString(zz);
}
public static String square(String x){ // Calculates x²
double xx = Double.parseDouble(x);
double zz = xx * xx;
return Double.toString(zz);
}
public static String squareRoot(String x){ // Calculates √x
double xx = Double.parseDouble(x);
double zz = Math.sqrt(xx);
return Double.toString(zz);
}
public static String getResult(){ // Returns the result
return result;
}
public static void main(String [] args){
ArrayList<String> list = new ArrayList<String>();
list.add("7");
list.add("*");
list.add("√");
list.add("9");
list.add("*");
list.add("2");
list.add("²");
list.add("*");
list.add("(");
list.add("3");
list.add("-");
list.add("(");
list.add("6");
list.add("+");
list.add("2");
list.add(")");
list.add(")");
list.add("²");
list.add("*");
list.add("(");
list.add("3");
list.add("+");
list.add("5");
list.add(")");
list.add("*");
list.add("√");
list.add("(");
list.add("5");
list.add("*");
list.add("4");
list.add(")");
new Calculate(list);
System.out.println(getResult());
}
}
diff --git a/src/com/simple/calculator/MainActivity.java b/src/com/simple/calculator/MainActivity.java
index 39d31cf..096ee0d 100644
--- a/src/com/simple/calculator/MainActivity.java
+++ b/src/com/simple/calculator/MainActivity.java
@@ -1,319 +1,328 @@
package com.simple.calculator;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
/**
* Project Simple Calculator : Main Activity
* This class is main activity class for Simple Calculator project
* In this class is portrait mode for calculator interface found in activity_main.xml
* This is only interface class and all calculations are done in different class
* Class tries to be smart about what inputs are valid and what are not and that way prevent user errors
*/
public ArrayList<String> calculate = new ArrayList<String>(); //This ArrayList holds calculation
public String buffer = null; //This String is buffer for adding numbers to the calculate Sting ArrayList
public String ans = "0"; //This Sting holds last answer that is calculated and it has default value of 0
/*
* Here is interface TextView
*/
TextView screen;
/*
* Hear is few static variables for some important chars
*/
public static String POTENS = "²";
public static String SQROOT = "√";
public static String OBRACKET = "(";
public static String CBRACKET = ")";
public static String DIVISION = "÷";
public static String MULTIPLY = "x";
public static String PLUS = "+";
public static String MINUS = "-";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen = (TextView) findViewById(R.id.view);
}
public void updScreen(){
/**
* updScreen() is method for updating TextView called screen for giving user feedback
* screen shows calculation that is entered
*/
if (this.calculate.size() == 0){
// Set number 0 for screen if no calculation has been given
this.screen.setText("0");
return;
}
// Idea is show user everything that has been set for ArrayList calculate by getting all Strings and adding them into one and setting that string text for TextView screen
String tmp = "";
for (String s : this.calculate) tmp = tmp + s;
this.screen.setText(tmp);
}
public void don(View v){
/**
* don() is method used as button listener for number buttons
*/
if (this.buffer == null){
if (calculate.size() == 0){
// if calculate size is 0 and ans is pushed then ans value is set to buffer and calculate
if ("ans".equals((String) v.getTag())){
buffer = ans;
calculate.add(buffer);
}
// if calculate size is 0 and number button is pushed then that number is set to buffer and calculate
else{
buffer = (String) v.getTag();
calculate.add(this.buffer);
}
}
// if calculate size is one or more and last symbol is potens it is replaced by number
else if (calculate.get(this.calculate.size()-1).equals(POTENS) && calculate.size() != 0){
calculate.remove(calculate.size()-1);
buffer = calculate.get(calculate.size()-1);
buffer = buffer + ( (String) v.getTag());
calculate.set(calculate.size()-1, buffer);
}
// if calculate size is one or more and last symbol is closing bracket nothing will be done
else if (calculate.get(this.calculate.size()-1).equals(CBRACKET)) return;
// if calculate size is one or more and last symbol isn't potens or closing bracket then number of tag is added to calculator
else {
if ("ans".equals((String) v.getTag())){
buffer = ans;
calculate.add(buffer);
}
else {
this.buffer = (String) v.getTag();
this.calculate.add(this.buffer);
}
}
}
else {
// if point or ans is given then nothing will be done
if ( ((String) v.getTag()).equals(".") && buffer.contains(".")) return;
if ( ((String) v.getTag()).equals("ans")) return;
// In other case number is add to buffer and calulate is updated
this.buffer = this.buffer + ( (String) v.getTag() );
this.calculate.set(this.calculate.size()-1, this.buffer);
}
this.updScreen();
}
public void doact(View v){
/**
* doact() is used button listener for actions/symbol (like +, - or x) buttons like
*/
// symbol is get from component tag witch is found from View
if (calculate.size() == 0){
// if calculate size is 0 then ans is added to calculate and after that symbol is add to calculate
calculate.add(ans);
this.calculate.add((String) v.getTag());
}
else if (this.buffer != null){
// if buffer isn't empty symbol is added to calculate and buffer is emptied
this.calculate.add((String) v.getTag());
buffer = null;
this.updScreen();
return;
}
else {
String tmp = this.calculate.get(this.calculate.size()-1);
// if buffer is empty and if last symbol in calculate is potens or closing bracket then symbol is added to calculate
if (tmp.equals(POTENS) || tmp.equals(CBRACKET)){
calculate.add((String) v.getTag());
}
// if buffer is empty and last symbol is square root nothing will be done
else if (tmp.equals(SQROOT)) return;
// if buffer is empty and last symbol isn't potens, square root or closing bracket then symbol is added to calculate in way that it replaces last symbol
else {
this.calculate.set(calculate.size()-1, (String) v.getTag());
}
}
this.updScreen();
}
public void clear(View v){
/**
* clear() is button listener method for clear button and it clear buffer and calculate ArrayList
*/
this.calculate = new ArrayList<String>();
this.buffer = null;
this.updScreen();
}
public void erase(View v){
/**
* erase() is button listener method for erasing one char or number from TextView screen
*/
// if calculate size is 0 then nothing will be done
if (calculate.size() == 0) return;
if (buffer != null){
// If buffer isn't empty and buffer is longer than 1 char
// Then last char from buffer is removed and change is updated to calculate
if (buffer.length() != 1){
buffer = buffer.substring(0, buffer.length()-1);
calculate.set(calculate.size()-1, buffer);
}
// In other case (buffer isn't empty and buffer has only 1 char) buffer is emptied and last string (number) is removed from calculate
else {
calculate.remove(calculate.size()-1);
buffer = null;
}
}
else {
String tmp = this.calculate.get(this.calculate.size()-1);
// if buffer is empty and last symbol is square root then square root is removed
if (tmp.equals(SQROOT)){
calculate.remove(calculate.size()-1);
}
// if buffer is empty and last symbol is opening bracket then opening bracket is removed
else if (tmp.equals(OBRACKET)){
calculate.remove(calculate.size()-1);
}
// In other case last symbol is removed and if next to last string is number string then it will be set to buffer
else {
calculate.remove(calculate.size()-1);
tmp = this.calculate.get(this.calculate.size()-1);
if (tmp.equals(POTENS)) ;
else if (tmp.equals(CBRACKET)) ;
else buffer = tmp;
}
}
this.updScreen();
}
public void calc(View v){
/**
* calc() is button listener for "=" symbol and does the calculating. calc() calls Calculate.java with does calculating in this application
*/
//if calculate size is 1 then nothing will be done
- if (this.calculate.size() == 1) return;
+ if (this.calculate.size() == 0) return;
String tmp = this.calculate.get(this.calculate.size()-1);
//if last symbol in calculate is of the following [ +, -, x, ÷, √, ( ] then last symbol will be removed from calculate because it would cause error
if (tmp.equals(SQROOT) || tmp.equals(MULTIPLY) || tmp.equals(MINUS) || tmp.equals(PLUS) || tmp.equals(DIVISION) || tmp.equals(OBRACKET)){
// if only symbol in calculate is "(" then calculate will be initialized and nothing else will be done
if (this.calculate.size() == 1 && tmp.equals(OBRACKET)){
this.calculate = new ArrayList<String>();
+ this.updScreen();
return;
}
else if (tmp.equals(OBRACKET)){
// if last symbol is "(" and calculate is longer than 1 then last two symbol are removed from calculate
this.calculate.remove(this.calculate.size()-1);
this.calculate.remove(this.calculate.size()-1);
}
else{
// in other cases last symbol will be removed
this.calculate.remove(this.calculate.size()-1);
}
}
int open = 0;
for (int i = 0; i < this.calculate.size(); i++){
// This for loop has two purposes:
// 1. count how many open brackets are in calculate
// 2. change "x" symbols to "*" symbols
if (this.calculate.get(i).equals(OBRACKET)) open++;
else if (this.calculate.get(i).equals(CBRACKET)) open--;
else if (this.calculate.get(i).equals(MULTIPLY)) this.calculate.set(i, "*");
}
while (open > 0){
// This while loop will close all open brackets
this.calculate.add(CBRACKET);
open--;
}
+ this.updScreen();
try {
// Try Catch is used to ensure that if some illegal calculate is give for Calculate.java then application don't crash and gives user error message
// First in this try calculate we call Calculate.java and give calculate for it
new Calculate(this.calculate);
// Then answer from calculation is saved to ans
this.ans = Calculate.getResult();
// Then ans will be simplified if possible by using double and integer variables
double test = Double.parseDouble(this.ans);
if (test%1==0){
int tt = (int) test;
this.ans = Integer.toString(tt);
}
// Last ans will be set for screen
String lastText = (String) this.screen.getText();
this.screen.setText(lastText + "=\n"+this.ans);
}
catch(java.lang.Exception e) {
// if there is error or exception in try bloc and error message will be given for user
this.screen.setText("ERROR");
+ //System.out.print(e.toString());
this.ans = "0";
}
// Buffer is emptied and if calculate is initialize
this.calculate = new ArrayList<String>();
this.buffer = null;
}
public void brac(View v){
/**
* brac() is button listener method for brackets button and tries to be smart for adding brackets
*/
//if calculate size is 0 then "(" will be added
if (calculate.size() == 0){
calculate.add(OBRACKET);
}
else {
int open = 0; //if calculate size is not 0 then we count "(" and ")" in calculate
int close = 0;
for (String st: calculate){ //bracket count is done with for loop
if (st.equals(OBRACKET)) open ++;
else if (st.equals(CBRACKET)) close++;
}
String tmp = calculate.get(calculate.size()-1);
if (buffer == null && tmp.compareTo(POTENS) != 0){ //if buffer is empty and last symbol is not potens symbol then:
if (close < open && tmp.equals(CBRACKET)) calculate.add(CBRACKET); // -if there are open brackets and last symbol is closing bracket then closing bracket will be added
else if (close == open && tmp.equals(CBRACKET)) return; // -if there are no open brackets and last symbol is closing bracket then nothing will be done
else calculate.add(OBRACKET); // -in all other cases we will add opening bracket
}
+ else if (tmp.equals(POTENS) && close < open) calculate.add(CBRACKET);
else if (buffer != null && close < open){ //if buffer isn't empty and there are open brackets then buffer will be emptied and closing bracket
buffer = null;
calculate.add(CBRACKET);
}
}
this.updScreen();
}
public void tosecond(View v){
/**
* tosecond() is button listener method for potency button
*/
if (this.buffer == null ){ //if buffer is empty and if last symbol is closing bracket then potens will be added
if (calculate.size() == 0) return;
if (calculate.get(calculate.size()-1).equals(CBRACKET)){
calculate.add(POTENS);
}
else return;
}
else { //if buffer isn't empty then buffer is emptied and potens symbol will be added
buffer = null;
calculate.add(POTENS);
}
this.updScreen();
}
public void squeroot(View v){
/**
* squeroot() is button listener for square root button
*/
if (this.buffer != null) return; //if buffer isn't null then nothing will be done
- if (calculate.size() != 0)
- if (calculate.get(calculate.size()-1).equals(POTENS))
- return;
- calculate.add(SQROOT); //if last symbol is not potens then square root will be added
+ if (calculate.size() != 0){
+ if (calculate.get(calculate.size()-1).equals(POTENS)) return;
+ else if (calculate.get(calculate.size()-1).equals(SQROOT)){
+ calculate.add(OBRACKET);
+ calculate.add(SQROOT);
+ }
+ else calculate.add(SQROOT);
+ }
+ else calculate.add(SQROOT); //if last symbol is not potens then square root will be added
this.updScreen();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
| false | false | null | null |
diff --git a/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/core/ExecutionEnvironmentTests.java b/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/core/ExecutionEnvironmentTests.java
index 998e2e98e..0fd708f4a 100644
--- a/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/core/ExecutionEnvironmentTests.java
+++ b/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/core/ExecutionEnvironmentTests.java
@@ -1,235 +1,237 @@
/*******************************************************************************
* Copyright (c) 2000, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.debug.tests.core;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.variables.IStringVariableManager;
import org.eclipse.core.variables.VariablesPlugin;
import org.eclipse.jdt.core.IAccessRule;
import org.eclipse.jdt.core.IClasspathContainer;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.debug.tests.AbstractDebugTest;
import org.eclipse.jdt.launching.IVMInstall;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jdt.launching.LibraryLocation;
import org.eclipse.jdt.launching.environments.IExecutionEnvironment;
import org.eclipse.jdt.launching.environments.IExecutionEnvironmentsManager;
/**
* Tests for execution environments
*/
public class ExecutionEnvironmentTests extends AbstractDebugTest {
public ExecutionEnvironmentTests(String name) {
super(name);
}
public void testGetEnvironments() throws Exception {
IExecutionEnvironment[] executionEnvironments = JavaRuntime.getExecutionEnvironmentsManager().getExecutionEnvironments();
assertTrue("Should be at least one environment", executionEnvironments.length > 0);
for (int i = 0; i < executionEnvironments.length; i++) {
IExecutionEnvironment environment = executionEnvironments[i];
if (environment.getId().equals("J2SE-1.4")) {
return;
}
}
assertTrue("Did not find environment J2SE-1.4", false);
}
public void testAnalyze() throws Exception {
IVMInstall vm = JavaRuntime.getDefaultVMInstall();
IExecutionEnvironmentsManager manager = JavaRuntime.getExecutionEnvironmentsManager();
IExecutionEnvironment environment = manager.getEnvironment("J2SE-1.4");
assertNotNull("Missing environment J2SE-1.4", environment);
IVMInstall[] installs = environment.getCompatibleVMs();
assertTrue("Should be at least one vm install for the environment", installs.length > 0);
for (int i = 0; i < installs.length; i++) {
IVMInstall install = installs[i];
if (install.equals(vm)) {
return;
}
}
assertTrue("vm should be J2SE-1.4 compliant", false);
}
public void testAccessRuleParticipants() throws Exception {
IExecutionEnvironmentsManager manager = JavaRuntime.getExecutionEnvironmentsManager();
IExecutionEnvironment environment = manager.getEnvironment("org.eclipse.jdt.debug.tests.environment.j2se14x");
assertNotNull("Missing environment j2se14x", environment);
IVMInstall vm = JavaRuntime.getDefaultVMInstall();
LibraryLocation[] libraries = JavaRuntime.getLibraryLocations(vm);
IAccessRule[][] accessRules = environment.getAccessRules(vm, libraries, getJavaProject());
assertNotNull("Missing access rules", accessRules);
assertEquals("Wrong number of rules", libraries.length, accessRules.length);
for (int i = 0; i < accessRules.length; i++) {
IAccessRule[] rules = accessRules[i];
assertEquals("wrong number of rules for lib", 4, rules.length);
assertEquals("Wrong rule", "secondary", rules[0].getPattern().toString());
assertEquals("Wrong rule", "discouraged", rules[1].getPattern().toString());
assertEquals("Wrong rule", "accessible", rules[2].getPattern().toString());
assertEquals("Wrong rule", "non_accessible", rules[3].getPattern().toString());
}
}
public void testNoAccessRuleParticipants() throws Exception {
IExecutionEnvironmentsManager manager = JavaRuntime.getExecutionEnvironmentsManager();
IExecutionEnvironment environment = manager.getEnvironment("org.eclipse.jdt.debug.tests.environment.j2se13x");
assertNotNull("Missing environment j2se13x", environment);
IVMInstall vm = JavaRuntime.getDefaultVMInstall();
LibraryLocation[] libraries = JavaRuntime.getLibraryLocations(vm);
IAccessRule[][] accessRules = environment.getAccessRules(vm, libraries, getJavaProject());
assertNotNull("Missing access rules", accessRules);
assertEquals("Wrong number of rules", libraries.length, accessRules.length);
for (int i = 0; i < accessRules.length; i++) {
IAccessRule[] rules = accessRules[i];
assertEquals("wrong number of rules for lib", 0, rules.length);
}
}
public void testAccessRuleParticipantsWithShortCircut() throws Exception {
IExecutionEnvironmentsManager manager = JavaRuntime.getExecutionEnvironmentsManager();
IExecutionEnvironment environment = manager.getEnvironment("org.eclipse.jdt.debug.tests.environment.j2se15x");
assertNotNull("Missing environment j2se15x", environment);
IVMInstall vm = JavaRuntime.getDefaultVMInstall();
LibraryLocation[] libraries = JavaRuntime.getLibraryLocations(vm);
IAccessRule[][] accessRules = environment.getAccessRules(vm, libraries, getJavaProject());
assertNotNull("Missing access rules", accessRules);
assertEquals("Wrong number of rules", libraries.length, accessRules.length);
for (int i = 0; i < accessRules.length; i++) {
IAccessRule[] rules = accessRules[i];
assertEquals("wrong number of rules for lib", 1, rules.length);
assertEquals("Wrong rule", "**/*", rules[0].getPattern().toString());
}
}
/**
* Tests that a project bound to an EE has access rules.
*/
public void testAccessRulesPresentOnEEProject() throws Exception {
boolean foundLib = false;
IJavaProject project = getJavaProject("BoundEE");
assertTrue("BoundEE project does not exist", project.exists());
IClasspathEntry[] rawClasspath = project.getRawClasspath();
for (int i = 0; i < rawClasspath.length; i++) {
IClasspathEntry entry = rawClasspath[i];
if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
String environmentId = JavaRuntime.getExecutionEnvironmentId(entry.getPath());
if (environmentId != null) {
IClasspathContainer container = JavaCore.getClasspathContainer(entry.getPath(), project);
assertNotNull("missing classpath container", container);
IClasspathEntry[] entries = container.getClasspathEntries();
for (int j = 0; j < entries.length; j++) {
foundLib = true;
IClasspathEntry containerEntry = entries[j];
assertTrue("Missing access rules", containerEntry.getAccessRules().length > 0);
}
}
}
}
assertTrue("did not find JRE libs on classpath", foundLib);
}
/**
* Tests that a project bound to a specific JRE has no access rules.
*/
public void testAccessRulesNotPresentOnJREProject() throws Exception {
boolean foundLib = false;
IJavaProject project = getJavaProject("BoundJRE");
assertTrue("BoundJRE project does not exist", project.exists());
IClasspathEntry[] rawClasspath = project.getRawClasspath();
for (int i = 0; i < rawClasspath.length; i++) {
IClasspathEntry entry = rawClasspath[i];
if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
IVMInstall install = JavaRuntime.getVMInstall(entry.getPath());
if (install != null) {
IClasspathContainer container = JavaCore.getClasspathContainer(entry.getPath(), project);
assertNotNull("missing classpath container", container);
IClasspathEntry[] entries = container.getClasspathEntries();
for (int j = 0; j < entries.length; j++) {
foundLib = true;
IClasspathEntry containerEntry = entries[j];
assertEquals("access rules should not be present", 0, containerEntry.getAccessRules().length);
}
}
}
}
assertTrue("did not find JRE library on classpath", foundLib);
}
/**
* Tests that default access rules appear for system packages when a profile file is specified.
*
* @throws Exception
*/
public void testDefaultSystemPackageAccessRules() throws Exception {
IExecutionEnvironmentsManager manager = JavaRuntime.getExecutionEnvironmentsManager();
IExecutionEnvironment environment = manager.getEnvironment("org.eclipse.jdt.debug.tests.systemPackages");
assertNotNull("Missing environment systemPackages", environment);
IVMInstall vm = JavaRuntime.getDefaultVMInstall();
LibraryLocation[] libraries = JavaRuntime.getLibraryLocations(vm);
IAccessRule[][] accessRules = environment.getAccessRules(vm, libraries, getJavaProject());
assertNotNull("Missing access rules", accessRules);
assertEquals("Wrong number of rules", libraries.length, accessRules.length);
for (int i = 0; i < accessRules.length; i++) {
IAccessRule[] rules = accessRules[i];
assertEquals("wrong number of rules for lib", 4, rules.length);
assertEquals("Wrong rule", "java/**", rules[0].getPattern().toString());
assertEquals("Wrong rule", "one/two/*", rules[1].getPattern().toString());
assertEquals("Wrong rule", "three/four/*", rules[2].getPattern().toString());
assertEquals("Wrong rule", "**/*", rules[3].getPattern().toString());
}
}
/**
* Tests that a location can be resolved for ${ee_home:J2SE-1.4}
*
* @throws Exception
*/
public void testEEHomeVariable() throws Exception {
IStringVariableManager manager = VariablesPlugin.getDefault().getStringVariableManager();
String result = manager.performStringSubstitution("${ee_home:J2SE-1.4}");
assertNotNull(result);
- assertEquals(JavaRuntime.getDefaultVMInstall().getInstallLocation().getAbsolutePath(), result);
+ IExecutionEnvironment ee = JavaRuntime.getExecutionEnvironmentsManager().getEnvironment("J2SE-1.4");
+ IVMInstall install = JavaRuntime.getVMInstall(JavaRuntime.newJREContainerPath(ee));
+ assertEquals(install.getInstallLocation().getAbsolutePath(), result);
}
/**
* Tests that a location cannot be resolved for ${ee_home}
*
* @throws Exception
*/
public void testEEHomeVariableMissingArgument() throws Exception {
IStringVariableManager manager = VariablesPlugin.getDefault().getStringVariableManager();
try {
manager.performStringSubstitution("${ee_home}");
} catch (CoreException e) {
return; // expected
}
assertNotNull("Test should have thrown an exception", null);
}
/**
* Tests that a location cannot be resolved for ${ee_home:bogus}
*
* @throws Exception
*/
public void testEEHomeVariableInvalidArgument() throws Exception {
IStringVariableManager manager = VariablesPlugin.getDefault().getStringVariableManager();
try {
manager.performStringSubstitution("${ee_home:bogus}");
} catch (CoreException e) {
return; // expected
}
assertNotNull("Test should have thrown an exception", null);
}
}
| true | false | null | null |
diff --git a/samplet/src/maro/core/EmotionKnowledge.java b/samplet/src/maro/core/EmotionKnowledge.java
index d2df60a..69c0da8 100644
--- a/samplet/src/maro/core/EmotionKnowledge.java
+++ b/samplet/src/maro/core/EmotionKnowledge.java
@@ -1,270 +1,275 @@
package maro.core;
import maro.wrapper.Dumper;
import maro.wrapper.OwlApi;
import jason.asSyntax.ASSyntax;
import jason.bb.BeliefBase;
import java.util.Iterator;
import java.util.HashMap;
import java.util.Set;
public class EmotionKnowledge {
protected FeelingsThreshold ft;
protected OwlApi oaw = null;
protected String filename;
protected String agName;
protected Emotion emotion;
protected Integer lastStepFeeling;
public EmotionKnowledge(String name, String fileName) throws Exception {
filename = fileName;
agName = name;
oaw = new OwlApi();
oaw.loadOntologyFromFile(filename);
Set<String> allEmotions;
allEmotions = oaw.getAllEmotions();
if (allEmotions == null || allEmotions.isEmpty()) {
throw new Exception("Fail on load ontology data");
}
emotion = new Emotion();
emotion.setEmotions(allEmotions);
ft = new FeelingsThreshold();
}
protected boolean changeBelief(Dumper dumper, boolean isAdd) {
String functor;
String[] terms;
Dumper[] annots;
int arity;
if (dumper == null) {
return false;
}
terms = dumper.getTerms();
arity = dumper.getArity();
functor = dumper.getFunctorComplete();
if (!oaw.isRelevant(arity, functor)) {
return false;
}
annots = dumper.getAnnots();
if (isAdd) {
return oaw.add(arity, functor, terms, annots);
}
//else
return oaw.remove(arity, functor, terms, annots);
}
public boolean add(Dumper dumper) {
return changeBelief(dumper, true);
}
public boolean remove(Dumper dumper) {
return changeBelief(dumper, false);
}
public Iterator<Dumper> getCandidatesByFunctorAndArityIter(String functor, int arity) {
if (functor.equals("sameAs") || functor.equals("~sameAs")) {
arity = 0;
}
if (!oaw.isRelevant(arity, functor)) {
return null;
}
return oaw.getCandidatesByFunctorAndArityIter(arity, functor);
}
public Iterator<Dumper> iterator() {
return oaw.iterator();
}
boolean ignoreFlag = false;
public void summarize(int step) {
if (ft.isLoaded(emotion, agName, oaw) == true) {
if (ft.isActive() == false) {
if (ignoreFlag == false) {
System.out.println("Threshold of emotions are "
+ "inconsistent ou fault, ignoring emotions...");
ignoreFlag = true;
}
return; // why lost time?
} else {
if (ignoreFlag == false) {
// Erase items from setup after the loaded
oaw.remove(2, "hasThresholdType", null, null);
oaw.remove(2, "hasThreshold", null, null);
oaw.remove(2, "isSetupOf", null, null);
oaw.remove(2, "hasSetup", null, null); // inverse of isSetupOf
oaw.remove(1, "setup", null, null);
ignoreFlag = true;
}
}
}
for (String s : emotion.getEmotions()) {
HashMap<Integer, Integer> e = emotion.getAllValences(s, agName);
Integer ret = oaw.summaryOf(agName, s, step, e);
if (ret == null) {
continue;
}
emotion.setValence(s, agName, step, ret);
}
}
public Set<String> getEmotionType() {
Set<String> et = new java.util.HashSet<String>();
for (String s : emotion.getEmotions())
et.add(s);
return et;
}
public Integer getEmotionPotence(String emotionType, String agentName) {
Integer valence = emotion.getValence(emotionType, agentName,
(lastStepFeeling == null) ? 0 : lastStepFeeling);
return valence;
}
public Integer getEmotionValence(String emotionType, String agentName) {
Integer valence = getEmotionPotence(emotionType, agentName);
Integer minimum = ft.getThreshold(emotionType);
if (valence == null) return null;
return valence - minimum;
}
public Set<String> feelings(int step) {
Set<String> feelingStrLit = new java.util.HashSet<String>();
if (ft.isActive() == false) {
return feelingStrLit;
}
lastStepFeeling = step;
for (String s : getEmotionType()) {
Integer potence = getEmotionValence(s, agName);
int feeling = (potence != null) ? potence : 0;
if (feeling > 0) {
feelingStrLit.add("feeling(" + s + ", " + feeling + ")");
}
}
return feelingStrLit;
}
public void dumpData() {
if (System.getenv("emotionKnowledgeDebug") == null) {
return;
}
try {
- oaw.dumpOntology("/tmp/baka.owl");
+ String filenameDump;
+
+ if (agName.isEmpty()) filenameDump = "/tmp/baka.owl";
+ else filenameDump = "/tmp/"+agName+".owl";
+
+ oaw.dumpOntology(filenameDump);
} catch (Exception e) {
System.err.println("Error dumping ontology");
e.printStackTrace();
System.exit(29);
}
}
public void loadPreferences(BeliefBase base) throws Exception
{
Set<Dumper> negatives =
oaw.getCandidatesByFunctorAndArity(1, "negative");
Set<Dumper> positives =
oaw.getCandidatesByFunctorAndArity(1, "positive");
if (negatives == null && positives == null) {
erasePreferenceItens();
return ;
}
Set<Dumper> hasAnnotations =
oaw.getCandidatesByFunctorAndArity(2, "hasAnnotation");
Set<Dumper> hasAnnotationValues =
oaw.getCandidatesByFunctorAndArity(2, "hasAnnotationValue");
if (hasAnnotationValues == null && hasAnnotations == null) {
erasePreferenceItens();
return ;
}
for (Dumper d : negatives) {
String text = d.getTerms()[0];
String value = null;
String annot = null;
for (Dumper a : hasAnnotations) {
if (a.getTerms()[0].equals(text)) {
annot = a.getTermAsString(1);
break;
}
}
for (Dumper v : hasAnnotationValues) {
if (v.getTerms()[0].equals(text)) {
value = v.getTermAsString(1);
break;
}
}
if (value != null && annot != null) {
base.add(
ASSyntax.parseLiteral(
new String("priority(repulse,"+annot+","+value+")[source(self)]")
)
);
}
}
for (Dumper d : positives) {
String text = d.getTerms()[0];
String value = null;
String annot = null;
for (Dumper a : hasAnnotations) {
if (a.getTerms()[0].equals(text)) {
annot = a.getTermAsString(1);
break;
}
}
for (Dumper v : hasAnnotationValues) {
if (v.getTerms()[0].equals(text)) {
value = v.getTermAsString(1);
break;
}
}
if (value != null && annot != null) {
base.add(
ASSyntax.parseLiteral(
new String("priority(attract,"+annot+","+value+")[source(self)]")
)
);
}
}
erasePreferenceItens();
}
private void erasePreferenceItens() {
// Erase itens from preference after the preparation
oaw.remove(2, "hasAnnotationValue", null, null);
oaw.remove(2, "hasAnnotation", null, null);
oaw.remove(2, "hasName", null, null);
oaw.remove(1, "static", null, null);
oaw.remove(1, "dynamic", null, null);
oaw.remove(1, "annotation", null, null);
oaw.remove(1, "positive", null, null);
oaw.remove(1, "negative", null, null);
oaw.remove(1, "preference", null, null);
}
}
| true | false | null | null |
diff --git a/src/com/github/ideajavadocs/template/impl/DocTemplateManagerImpl.java b/src/com/github/ideajavadocs/template/impl/DocTemplateManagerImpl.java
index 2e36b8a..9bca826 100755
--- a/src/com/github/ideajavadocs/template/impl/DocTemplateManagerImpl.java
+++ b/src/com/github/ideajavadocs/template/impl/DocTemplateManagerImpl.java
@@ -1,183 +1,183 @@
package com.github.ideajavadocs.template.impl;
import com.github.ideajavadocs.template.DocTemplateManager;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiClassType;
import com.intellij.psi.PsiCodeBlock;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.PsiParameter;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import javax.swing.*;
/**
* The type Doc template manager impl.
*
* @author Sergey Timofiychuk
*/
public class DocTemplateManagerImpl implements DocTemplateManager, ProjectComponent {
// TODO add more templates for different cases
/* */
private static final String CLASS_TEMPLATE = "/**\n"
+ " * The ${type} ${name}.\n"
+ " */";
private static final Map<String, String> CLASS_TEMPLATES = new LinkedHashMap<String, String>();
static {
CLASS_TEMPLATES.put(".+", CLASS_TEMPLATE);
}
/* */
private static final String FIELD_TEMPLATE = "/**\n"
+ " * The ${name}.\n"
+ " */";
private static final String CONSTANT_TEMPLATE = "/**\n"
+ " * The constant ${name}.\n"
+ " */";
private static final Map<String, String> FIELD_TEMPLATES = new LinkedHashMap<String, String>();
static {
- FIELD_TEMPLATES.put(".+", CONSTANT_TEMPLATE);
- FIELD_TEMPLATES.put(".+static\\s.+", FIELD_TEMPLATE);
+ FIELD_TEMPLATES.put(".*static\\s.+", CONSTANT_TEMPLATE);
+ FIELD_TEMPLATES.put(".+", FIELD_TEMPLATE);
}
/* */
private static final String METHOD_GETTER_TEMPLATE = "/**\n"
+ " * ${description}.\n"
+ " * @return the ${return_by_name}\n"
+ " */";
private static final String METHOD_VOID_TEMPLATE = "/**\n"
+ " * ${description}.\n"
+ " */";
private static final String METHOD_TEMPLATE = "/**\n"
+ " * ${description}.\n"
+ " * @return the ${return_description}"
+ " */";
private static final Map<String, String> METHOD_TEMPLATES = new LinkedHashMap<String, String>();
static {
METHOD_TEMPLATES.put(".*get.+", METHOD_GETTER_TEMPLATE);
METHOD_TEMPLATES.put(".*void\\s.+", METHOD_VOID_TEMPLATE);
METHOD_TEMPLATES.put(".+", METHOD_TEMPLATE);
}
/* */
private static final String CONSTRUCTOR_TEMPLATE = "/**\n"
+ " * Instantiates a new ${description}.\n"
+ " */";
private static final Map<String, String> CONSTRUCTOR_TEMPLATES = new LinkedHashMap<String, String>();
static {
CONSTRUCTOR_TEMPLATES.put(".+", CONSTRUCTOR_TEMPLATE);
}
/* */
private static final String PARAM_TAG_TEMPLATE = "/**\n"
+ " * @param ${name} the ${description}\n"
+ " */";
private static final Map<String, String> PARAM_TAG_TEMPLATES = new LinkedHashMap<String, String>();
static {
PARAM_TAG_TEMPLATES.put(".+", PARAM_TAG_TEMPLATE);
}
/* */
private static final String THROWS_TAG_TEMPLATE = "/**\n"
+ " * @throws ${name} the ${description}\n"
+ " */";
private static final Map<String, String> THROWS_TAG_TEMPLATES = new LinkedHashMap<String, String>();
static {
THROWS_TAG_TEMPLATES.put(".+", THROWS_TAG_TEMPLATE);
}
@Override
public void projectOpened() {
}
@Override
public void projectClosed() {
}
@Override
public void initComponent() {
// TODO read template from file or app settings
}
@Override
public void disposeComponent() {
}
@NotNull
@Override
public String getComponentName() {
return COMPONENT_NAME;
}
@NotNull
@Override
public String getClassTemplate(@NotNull PsiClass classElement) {
return getMatchingTemplate(classElement.getText(), CLASS_TEMPLATES);
}
@NotNull
@Override
public String getMethodTemplate(@NotNull PsiMethod methodElement) {
Map<String, String> templates;
if (methodElement.isConstructor()) {
templates = CONSTRUCTOR_TEMPLATES;
} else {
templates = METHOD_TEMPLATES;
}
String signature = methodElement.getText();
PsiCodeBlock methodBody = methodElement.getBody();
if (methodBody != null) {
signature = signature.replace(methodBody.getText(), "");
}
return getMatchingTemplate(signature, templates);
}
@NotNull
@Override
public String getFieldTemplate(@NotNull PsiField fieldElement) {
- return getMatchingTemplate(fieldElement.getName(), FIELD_TEMPLATES);
+ return getMatchingTemplate(fieldElement.getText(), FIELD_TEMPLATES);
}
@NotNull
@Override
public String getParamTagTemplate(@NotNull PsiParameter psiParameter) {
return getMatchingTemplate(psiParameter.getText(), PARAM_TAG_TEMPLATES);
}
@NotNull
@Override
public String getExceptionTagTemplate(@NotNull PsiClassType classElement) {
return getMatchingTemplate(classElement.getCanonicalText(), THROWS_TAG_TEMPLATES);
}
@NotNull
private String getMatchingTemplate(@NotNull String elementText, @NotNull Map<String, String> templates) {
String result = StringUtils.EMPTY;
for (Entry<String, String> entry : templates.entrySet()) {
if (Pattern.compile(entry.getKey(), Pattern.DOTALL | Pattern.MULTILINE).matcher(elementText).matches()) {
result = entry.getValue();
break;
}
}
return result;
}
}
| false | false | null | null |
diff --git a/icy/canvas/IcyCanvas.java b/icy/canvas/IcyCanvas.java
index 22270cd..d3e25f8 100644
--- a/icy/canvas/IcyCanvas.java
+++ b/icy/canvas/IcyCanvas.java
@@ -1,4674 +1,4674 @@
/*
* Copyright 2010-2013 Institut Pasteur.
*
* This file is part of Icy.
*
* Icy 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.
*
* Icy 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 Icy. If not, see <http://www.gnu.org/licenses/>.
*/
package icy.canvas;
import icy.action.CanvasActions;
import icy.action.GeneralActions;
import icy.action.RoiActions;
import icy.action.WindowActions;
import icy.canvas.CanvasLayerEvent.LayersEventType;
import icy.canvas.IcyCanvasEvent.IcyCanvasEventType;
import icy.canvas.Layer.LayerListener;
import icy.common.EventHierarchicalChecker;
import icy.common.UpdateEventHandler;
import icy.common.listener.ChangeListener;
import icy.common.listener.ProgressListener;
import icy.gui.util.GuiUtil;
import icy.gui.viewer.MouseImageInfosPanel;
import icy.gui.viewer.TNavigationPanel;
import icy.gui.viewer.Viewer;
import icy.gui.viewer.ViewerEvent;
import icy.gui.viewer.ViewerListener;
import icy.gui.viewer.ZNavigationPanel;
import icy.image.IcyBufferedImage;
import icy.image.colormodel.IcyColorModel;
import icy.image.lut.LUT;
import icy.image.lut.LUTEvent;
import icy.image.lut.LUTEvent.LUTEventType;
import icy.image.lut.LUTListener;
import icy.main.Icy;
import icy.painter.Overlay;
import icy.painter.OverlayWrapper;
import icy.painter.Painter;
import icy.plugin.PluginDescriptor;
import icy.plugin.PluginLoader;
import icy.plugin.interface_.PluginCanvas;
import icy.roi.ROI;
import icy.sequence.DimensionId;
import icy.sequence.Sequence;
import icy.sequence.SequenceEvent;
import icy.sequence.SequenceEvent.SequenceEventType;
import icy.sequence.SequenceListener;
import icy.system.IcyExceptionHandler;
import icy.system.thread.ThreadUtil;
import icy.type.point.Point5D;
import icy.util.ClassUtil;
import icy.util.EventUtil;
import icy.util.OMEUtil;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.image.BufferedImage;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.event.ChangeEvent;
import plugins.kernel.canvas.Canvas2DPlugin;
import plugins.kernel.canvas.VtkCanvasPlugin;
/**
* @author Fabrice de Chaumont & Stephane Dallongeville<br>
* <br>
* An IcyCanvas is a basic Canvas used into the viewer. It contains a visual representation
* of the sequence and provides some facilities as basic transformation and view
* synchronization.<br>
* Also IcyCanvas receives key events from Viewer when they are not consumed.<br>
* <br>
* By default transformations are applied in following order :<br>
* Rotation, Translation then Scaling.<br>
* The rotation transformation is relative to canvas center.<br>
* <br>
* Free feel to implement and override this design or not. <br>
* <br>
* (Canvas2D and Canvas3D derives from IcyCanvas)<br>
*/
public abstract class IcyCanvas extends JPanel implements KeyListener, ViewerListener, SequenceListener, LUTListener,
ChangeListener, LayerListener
{
protected class IcyCanvasImageOverlay extends Overlay
{
public IcyCanvasImageOverlay()
{
super((getSequence() == null) ? "Image" : getSequence().getName(), OverlayPriority.IMAGE_NORMAL);
// we fix the image overlay
canBeRemoved = false;
readOnly = false;
}
@Override
public void paint(Graphics2D g, Sequence sequence, IcyCanvas canvas)
{
// default lazy implementation (very slow)
if (g != null)
g.drawImage(getCurrentImage(), null, 0, 0);
}
}
/**
* Returns all {@link PluginCanvas} plugins (kernel plugin are returned first).
*/
public static List<PluginDescriptor> getCanvasPlugins()
{
// get all canvas plugins
final List<PluginDescriptor> result = PluginLoader.getPlugins(PluginCanvas.class);
// VTK is not loaded ?
if (!Icy.isVtkLibraryLoaded())
{
// remove VtkCanvas
final int ind = PluginDescriptor.getIndex(result, VtkCanvasPlugin.class.getName());
if (ind != -1)
result.remove(ind);
}
// sort plugins list
Collections.sort(result, new Comparator<PluginDescriptor>()
{
@Override
public int compare(PluginDescriptor o1, PluginDescriptor o2)
{
return Integer.valueOf(getOrder(o1)).compareTo(Integer.valueOf(getOrder(o2)));
}
int getOrder(PluginDescriptor p)
{
if (p.getClassName().equals(Canvas2DPlugin.class.getName()))
return 0;
if (p.getClassName().equals(VtkCanvasPlugin.class.getName()))
return 1;
return 10;
}
});
return result;
}
/**
* Returns all {@link PluginCanvas} plugins class name (kernel plugin are returned first).
*/
public static List<String> getCanvasPluginNames()
{
// get all canvas plugins
final List<PluginDescriptor> plugins = getCanvasPlugins();
final List<String> result = new ArrayList<String>();
for (PluginDescriptor plugin : plugins)
result.add(plugin.getClassName());
return result;
}
/**
* Returns the plugin class name corresponding to the specified Canvas class name.<br>
* Returns <code>null</code> if we can't find a corresponding plugin.
*/
public static String getPluginClassName(String canvasClassName)
{
for (PluginDescriptor plugin : IcyCanvas.getCanvasPlugins())
{
final String className = getCanvasClassName(plugin);
// we found the corresponding plugin
if (canvasClassName.equals(className))
// get plugin class name
return plugin.getClassName();
}
return null;
}
/**
* Returns the canvas class name corresponding to the specified {@link PluginCanvas} plugin.<br>
* Returns <code>null</code> if we can't retrieve the corresponding canvas class name.
*/
public static String getCanvasClassName(PluginDescriptor plugin)
{
try
{
if (plugin != null)
{
final PluginCanvas pluginCanvas = (PluginCanvas) plugin.getPluginClass().newInstance();
// return canvas class name
return pluginCanvas.getCanvasClassName();
}
}
catch (Exception e)
{
IcyExceptionHandler.showErrorMessage(e, true);
}
return null;
}
/**
* Returns the canvas class name corresponding to the specified {@link PluginCanvas} class name.<br>
* Returns <code>null</code> if we can't find retrieve the corresponding canvas class name.
*/
public static String getCanvasClassName(String pluginClassName)
{
return getCanvasClassName(PluginLoader.getPlugin(pluginClassName));
}
// /**
// * Return the class name of all {@link PluginCanvas}.
// */
// public static List<String> getCanvasPlugins()
// {
// // get all canvas plugins
// final List<PluginDescriptor> plugins = PluginLoader.getPlugins(PluginCanvas.class);
// final List<String> result = new ArrayList<String>();
//
// // we want the default 2D and 3D canvas to be first
// result.add(Canvas2DPlugin.class.getName());
// if (Icy.isVtkLibraryLoaded())
// result.add(VtkCanvasPlugin.class.getName());
//
// for (PluginDescriptor plugin : plugins)
// {
// final String className = plugin.getClassName();
//
// // ignore default canvas as they have been already added
// if (Canvas2DPlugin.class.getName().equals(className))
// continue;
// if (VtkCanvasPlugin.class.getName().equals(className))
// continue;
//
// CollectionUtil.addUniq(result, plugin.getClassName());
// }
//
// return result;
// }
/**
* Create a {@link IcyCanvas} object from its class name or {@link PluginCanvas} class name.<br>
* Return <code>null</code> if the specified canvas classname does not exist or if an error
* occured.
*
* @param viewer
* {@link Viewer} to which to canvas is attached.
*/
public static IcyCanvas create(String className, Viewer viewer)
{
IcyCanvas result = null;
try
{
// search for the specified className
final Class<?> clazz = ClassUtil.findClass(className);
// class found
if (clazz != null)
{
try
{
// we first check if we have a IcyCanvas Plugin class here
final Class<? extends PluginCanvas> canvasClazz = clazz.asSubclass(PluginCanvas.class);
// create canvas
result = canvasClazz.newInstance().createCanvas(viewer);
}
catch (ClassCastException e0)
{
// check if this is a IcyCanvas class
final Class<? extends IcyCanvas> canvasClazz = clazz.asSubclass(IcyCanvas.class);
// get constructor (Viewer)
final Constructor<? extends IcyCanvas> constructor = canvasClazz
.getConstructor(new Class[] {Viewer.class});
// build canvas
result = constructor.newInstance(new Object[] {viewer});
}
}
}
catch (Exception e)
{
IcyExceptionHandler.showErrorMessage(e, true);
result = null;
}
return result;
}
public static void addVisibleLayerToList(final Layer layer, ArrayList<Layer> list)
{
if ((layer != null) && (layer.isVisible()))
list.add(layer);
}
private static final long serialVersionUID = -8461229450296203011L;
public static final String PROPERTY_LAYERS_VISIBLE = "layersVisible";
/**
* Navigations bar
*/
final protected ZNavigationPanel zNav;
final protected TNavigationPanel tNav;
/**
* The panel where mouse informations are displayed
*/
protected final MouseImageInfosPanel mouseInfPanel;
/**
* The panel contains all settings and informations data such as<br>
* scale factor, rendering mode...
* Will be retrieved by the inspector to get information on the current canvas.
*/
protected JPanel panel;
/**
* attached viewer
*/
protected final Viewer viewer;
/**
* layers visible flag
*/
protected boolean layersVisible;
/**
* synchronization group :<br>
* 0 = unsynchronized
* 1 = full synchronization group 1
* 2 = full synchronization group 2
* 3 = view synchronization group (T and Z navigation are not synchronized)
* 4 = slice synchronization group (only T and Z navigation are synchronized)
*/
protected int syncId;
/**
* Overlay/Layer used to display sequence image
*/
protected final Overlay imageOverlay;
protected final Layer imageLayer;
/**
* Layers attached to canvas<br>
* There are representing sequence overlays with some visualization properties
*/
protected final Map<Overlay, Layer> layers;
/**
* Priority ordered layers.
*/
protected List<Layer> orderedLayers;
/**
* internal updater
*/
protected final UpdateEventHandler updater;
/**
* Current X position (should be -1 when canvas handle multi X dimension view).
*/
protected int posX;
/**
* Current Y position (should be -1 when canvas handle multi Y dimension view).
*/
protected int posY;
/**
* Current Z position (should be -1 when canvas handle multi Z dimension view).
*/
protected int posZ;
/**
* Current T position (should be -1 when canvas handle multi T dimension view).
*/
protected int posT;
/**
* Current C position (should be -1 when canvas handle multi C dimension view).
*/
protected int posC;
/**
* Current mouse position (canvas coordinate space)
*/
protected Point mousePos;
/**
* internals
*/
protected LUT lut;
protected boolean synchMaster;
protected boolean orderedLayersOutdated;
private Runnable guiUpdater;
/**
* Constructor
*
* @param viewer
*/
public IcyCanvas(Viewer viewer)
{
super();
// default
this.viewer = viewer;
layersVisible = true;
layers = new HashMap<Overlay, Layer>();
orderedLayers = new ArrayList<Layer>();
syncId = 0;
synchMaster = false;
orderedLayersOutdated = false;
updater = new UpdateEventHandler(this, false);
// default position
mousePos = new Point(0, 0);
posX = -1;
posY = -1;
posZ = -1;
posT = -1;
posC = -1;
// GUI stuff
panel = new JPanel();
// Z navigation
zNav = new ZNavigationPanel();
zNav.addChangeListener(new javax.swing.event.ChangeListener()
{
@Override
public void stateChanged(ChangeEvent e)
{
// set the new Z position
setPositionZ(zNav.getValue());
}
});
// T navigation
tNav = new TNavigationPanel();
tNav.addChangeListener(new javax.swing.event.ChangeListener()
{
@Override
public void stateChanged(ChangeEvent e)
{
// set the new T position
setPositionT(tNav.getValue());
}
});
// mouse info panel
mouseInfPanel = new MouseImageInfosPanel();
// default canvas layout
setLayout(new BorderLayout());
add(zNav, BorderLayout.WEST);
add(GuiUtil.createPageBoxPanel(tNav, mouseInfPanel), BorderLayout.SOUTH);
// asynchronous updater for GUI
guiUpdater = new Runnable()
{
@Override
public void run()
{
ThreadUtil.invokeNow(new Runnable()
{
@Override
public void run()
{
// update sliders bounds if needed
updateZNav();
updateTNav();
// adjust X position if needed
final int maxX = getMaxPositionX();
final int curX = getPositionX();
if ((curX != -1) && (curX > maxX))
setPositionX(maxX);
// adjust Y position if needed
final int maxY = getMaxPositionY();
final int curY = getPositionY();
if ((curY != -1) && (curY > maxY))
setPositionY(maxY);
// adjust C position if needed
final int maxC = getMaxPositionC();
final int curC = getPositionC();
if ((curC != -1) && (curC > maxC))
setPositionC(maxC);
// adjust Z position if needed
final int maxZ = getMaxPositionZ();
final int curZ = getPositionZ();
if ((curZ != -1) && (curZ > maxZ))
setPositionZ(maxZ);
// adjust T position if needed
final int maxT = getMaxPositionT();
final int curT = getPositionT();
if ((curT != -1) && (curT > maxT))
setPositionT(maxT);
// refresh mouse panel informations (data values can have changed)
mouseInfPanel.updateInfos(IcyCanvas.this);
}
});
}
};
// create image overlay
imageOverlay = createImageOverlay();
// create layers from overlays
beginUpdate();
try
{
// first add image layer
imageLayer = addLayer(getImageOverlay());
final Sequence sequence = getSequence();
if (sequence != null)
{
// then add sequence overlays to layer list
for (Overlay overlay : sequence.getOverlays())
addLayer(overlay);
}
else
System.err.println("Sequence null when canvas created");
}
finally
{
endUpdate();
}
// add listeners
viewer.addListener(this);
final Sequence seq = getSequence();
if (seq != null)
seq.addListener(this);
// set lut (no event wanted here)
lut = null;
setLut(viewer.getLut(), false);
}
/**
* Called by the viewer when canvas is closed.
*/
public void shutDown()
{
// remove navigation panel listener
zNav.removeAllChangeListener();
tNav.removeAllChangeListener();
// remove listeners
if (lut != null)
lut.removeListener(this);
final Sequence seq = getSequence();
if (seq != null)
seq.removeListener(this);
viewer.removeListener(this);
// remove all layers
beginUpdate();
try
{
for (Layer layer : getLayers())
removeLayer(layer);
}
finally
{
endUpdate();
}
// release layers
- orderedLayers = null;
+ orderedLayers.clear();
// remove all IcyCanvas listeners
final IcyCanvasListener[] canvasListenters = listenerList.getListeners(IcyCanvasListener.class);
for (IcyCanvasListener listener : canvasListenters)
removeCanvasListener(listener);
// remove all Layers listeners
final CanvasLayerListener[] layersListenters = listenerList.getListeners(CanvasLayerListener.class);
for (CanvasLayerListener listener : layersListenters)
removeLayerListener(listener);
}
/**
* Force canvas refresh
*/
public abstract void refresh();
protected Overlay createImageOverlay()
{
// default image overlay
return new IcyCanvasImageOverlay();
}
/**
* Returns the {@link Overlay} used to display the current sequence image
*/
public Overlay getImageOverlay()
{
return imageOverlay;
}
/**
* Returns the {@link Layer} object used to display the current sequence image
*/
public Layer getImageLayer()
{
return imageLayer;
}
/**
* @deprecated Use {@link #isLayersVisible()} instead.
*/
@Deprecated
public boolean getDrawLayers()
{
return isLayersVisible();
}
/**
* @deprecated Use {@link #setLayersVisible(boolean)} instead.
*/
@Deprecated
public void setDrawLayers(boolean value)
{
setLayersVisible(value);
}
/**
* Return true if layers are visible on the canvas.
*/
public boolean isLayersVisible()
{
return layersVisible;
}
/**
* Make layers visible on this canvas (default = true).
*/
public void setLayersVisible(boolean value)
{
if (layersVisible != value)
{
layersVisible = value;
firePropertyChange(PROPERTY_LAYERS_VISIBLE, !value, value);
final Component comp = getViewComponent();
if (comp != null)
comp.repaint();
}
}
/**
* @return the viewer
*/
public Viewer getViewer()
{
return viewer;
}
/**
* @return the sequence
*/
public Sequence getSequence()
{
return viewer.getSequence();
}
/**
* @return the main view component
*/
public abstract Component getViewComponent();
/**
* @return the Z navigation bar panel
*/
public ZNavigationPanel getZNavigationPanel()
{
return zNav;
}
/**
* @return the T navigation bar panel
*/
public TNavigationPanel getTNavigationPanel()
{
return tNav;
}
/**
* @return the mouse image informations panel
*/
public MouseImageInfosPanel getMouseImageInfosPanel()
{
return mouseInfPanel;
}
/**
* @return the LUT
*/
public LUT getLut()
{
// ensure we have the good lut
setLut(viewer.getLut(), true);
return lut;
}
/**
* set canvas LUT
*/
private void setLut(LUT lut, boolean event)
{
if (this.lut != lut)
{
if (this.lut != null)
this.lut.removeListener(this);
this.lut = lut;
// add listener to the new lut
if (lut != null)
lut.addListener(this);
// launch a lutChanged event if wanted
if (event)
lutChanged(new LUTEvent(lut, -1, LUTEventType.COLORMAP_CHANGED));
}
}
/**
* @deprecated Use {@link #customizeToolbar(JToolBar)} instead.
*/
@SuppressWarnings("unused")
@Deprecated
public void addViewerToolbarComponents(JToolBar toolBar)
{
}
/**
* Called by the parent viewer when building the toolbar.<br>
* This way the canvas can customize it by adding specific command for instance.<br>
*
* @param toolBar
* the parent toolbar to customize
*/
public void customizeToolbar(JToolBar toolBar)
{
addViewerToolbarComponents(toolBar);
}
/**
* Returns the setting panel of this canvas.<br>
* The setting panel is displayed in the inspector so user can change canvas parameters.
*/
public JPanel getPanel()
{
return panel;
}
/**
* Returns all layers attached to this canvas.<br/>
*
* @param sorted
* If <code>true</code> the returned list is sorted on the layer priority.<br>
* Sort operation is cached so the method could take sometime when sort cache need to be
* rebuild.
*/
public List<Layer> getLayers(boolean sorted)
{
if (sorted)
{
// need to rebuild sorted layer list ?
if (orderedLayersOutdated)
{
// build and sort the list
synchronized (layers)
{
orderedLayers = new ArrayList<Layer>(layers.values());
}
Collections.sort(orderedLayers);
orderedLayersOutdated = false;
}
return new ArrayList<Layer>(orderedLayers);
}
synchronized (layers)
{
return new ArrayList<Layer>(layers.values());
}
}
/**
* Returns all layers attached to this canvas.<br/>
* The returned list is sorted on the layer priority.<br>
* Sort operation is cached so the method could take sometime when cache need to be rebuild.
*/
public List<Layer> getLayers()
{
return getLayers(true);
}
/**
* Returns all visible layers (visible property set to <code>true</code>) attached to this
* canvas.
*
* @param sorted
* If <code>true</code> the returned list is sorted on the layer priority.<br>
* Sort operation is cached so the method could take sometime when sort cache need to be
* rebuild.
*/
public List<Layer> getVisibleLayers(boolean sorted)
{
final List<Layer> olayers = getLayers(sorted);
final List<Layer> result = new ArrayList<Layer>(olayers.size());
for (Layer l : olayers)
if (l.isVisible())
result.add(l);
return result;
}
/**
* Returns all visible layers (visible property set to <code>true</code>) attached to this
* canvas.<br/>
* The list is sorted on the layer priority.
*/
public ArrayList<Layer> getVisibleLayers()
{
return (ArrayList<Layer>) getVisibleLayers(true);
}
/**
* @deprecated Use {@link #getLayers()} instead (sorted on Layer priority).
*/
@Deprecated
public List<Layer> getOrderedLayersForEvent()
{
return getLayers();
}
/**
* @deprecated Use {@link #getVisibleLayers()} instead (sorted on Layer priority).
*/
@Deprecated
public List<Layer> getVisibleOrderedLayersForEvent()
{
return getVisibleLayers();
}
/**
* @deprecated Use {@link #getOverlays()} instead.
*/
@Deprecated
public List<Painter> getLayersPainter()
{
final ArrayList<Painter> result = new ArrayList<Painter>();
for (Overlay overlay : getOverlays())
{
if (overlay instanceof OverlayWrapper)
result.add(((OverlayWrapper) overlay).getPainter());
else
result.add(overlay);
}
return result;
}
/**
* Directly returns a {@link Set} of all Overlay displayed by this canvas.
*/
public Set<Overlay> getOverlays()
{
synchronized (layers)
{
return new HashSet<Overlay>(layers.keySet());
}
}
/**
* @return the SyncId
*/
public int getSyncId()
{
return syncId;
}
/**
* Set the synchronization group id (0 means unsynchronized).<br>
*
* @return <code>false</code> if the canvas do not support synchronization group.
* @param id
* the syncId to set
*/
public boolean setSyncId(int id)
{
if (!isSynchronizationSupported())
return false;
if (this.syncId != id)
{
this.syncId = id;
// notify sync has changed
updater.changed(new IcyCanvasEvent(this, IcyCanvasEventType.SYNC_CHANGED));
}
return true;
}
/**
* Return true if this canvas support synchronization
*/
public boolean isSynchronizationSupported()
{
// default (override it when supported)
return false;
}
/**
* Return true if this canvas is synchronized
*/
public boolean isSynchronized()
{
return syncId > 0;
}
/**
* Return true if current canvas is synchronized and is currently the synchronize leader.
*/
public boolean isSynchMaster()
{
return synchMaster;
}
/**
* @deprecated Use {@link #isSynchMaster()} instead.
*/
@Deprecated
public boolean isSynchHeader()
{
return isSynchMaster();
}
/**
* Return true if current canvas is synchronized and it's not the synchronize master
*/
public boolean isSynchSlave()
{
if (isSynchronized())
{
if (isSynchMaster())
return false;
// search for a master in synchronized canvas
for (IcyCanvas cnv : getSynchronizedCanvas())
if (cnv.isSynchMaster())
return true;
}
return false;
}
/**
* Return true if this canvas is synchronized on view (offset, zoom and rotation).
*/
public boolean isSynchOnView()
{
return (syncId == 1) || (syncId == 2) || (syncId == 3);
}
/**
* Return true if this canvas is synchronized on slice (T and Z position)
*/
public boolean isSynchOnSlice()
{
return (syncId == 1) || (syncId == 2) || (syncId == 4);
}
/**
* Return true if this canvas is synchronized on cursor (mouse cursor)
*/
public boolean isSynchOnCursor()
{
return (syncId > 0);
}
/**
* Return true if we get the synchronizer master from synchronized canvas
*/
protected boolean getSynchMaster()
{
return getSynchMaster(getSynchronizedCanvas());
}
/**
* @deprecated Use {@link #getSynchMaster()} instead.
*/
@Deprecated
protected boolean getSynchHeader()
{
return getSynchMaster();
}
/**
* Return true if we get the synchronizer master from specified canvas list.
*/
protected boolean getSynchMaster(List<IcyCanvas> canvasList)
{
for (IcyCanvas canvas : canvasList)
if (canvas.isSynchMaster())
return canvas == this;
// no master found so we are master
synchMaster = true;
return true;
}
/**
* @deprecated Use {@link #getSynchMaster(List)} instead.
*/
@Deprecated
protected boolean getSynchHeader(List<IcyCanvas> canvasList)
{
return getSynchMaster(canvasList);
}
/**
* Release synchronizer master
*/
protected void releaseSynchMaster()
{
synchMaster = false;
}
/**
* @deprecated Use {@link #releaseSynchMaster()} instead.
*/
@Deprecated
protected void releaseSynchHeader()
{
releaseSynchMaster();
}
/**
* Return the list of canvas which are synchronized with the current one
*/
private List<IcyCanvas> getSynchronizedCanvas()
{
final List<IcyCanvas> result = new ArrayList<IcyCanvas>();
if (isSynchronized())
{
final List<Viewer> viewers = Icy.getMainInterface().getViewers();
for (int i = viewers.size() - 1; i >= 0; i--)
{
final IcyCanvas cnv = viewers.get(i).getCanvas();
if ((cnv == this) || (cnv.getSyncId() != syncId))
viewers.remove(i);
}
for (Viewer v : viewers)
{
final IcyCanvas cnv = v.getCanvas();
// only permit same class
if (cnv.getClass().isInstance(this))
result.add(cnv);
}
}
return result;
}
/**
* Synchronize views of specified list of canvas
*/
protected void synchronizeCanvas(List<IcyCanvas> canvasList, IcyCanvasEvent event, boolean processAll)
{
final IcyCanvasEventType type = event.getType();
final DimensionId dim = event.getDim();
// position synchronization
if (isSynchOnSlice())
{
if (processAll || (type == IcyCanvasEventType.POSITION_CHANGED))
{
// no information about dimension --> set all
if (processAll || (dim == DimensionId.NULL))
{
final int x = getPositionX();
final int y = getPositionY();
final int z = getPositionZ();
final int t = getPositionT();
final int c = getPositionC();
for (IcyCanvas cnv : canvasList)
{
if (x != -1)
cnv.setPositionX(x);
if (y != -1)
cnv.setPositionY(y);
if (z != -1)
cnv.setPositionZ(z);
if (t != -1)
cnv.setPositionT(t);
if (c != -1)
cnv.setPositionC(c);
}
}
else
{
for (IcyCanvas cnv : canvasList)
{
final int pos = getPosition(dim);
if (pos != -1)
cnv.setPosition(dim, pos);
}
}
}
}
// view synchronization
if (isSynchOnView())
{
if (processAll || (type == IcyCanvasEventType.SCALE_CHANGED))
{
// no information about dimension --> set all
if (processAll || (dim == DimensionId.NULL))
{
final double sX = getScaleX();
final double sY = getScaleY();
final double sZ = getScaleZ();
final double sT = getScaleT();
final double sC = getScaleC();
for (IcyCanvas cnv : canvasList)
{
cnv.setScaleX(sX);
cnv.setScaleY(sY);
cnv.setScaleZ(sZ);
cnv.setScaleT(sT);
cnv.setScaleC(sC);
}
}
else
{
for (IcyCanvas cnv : canvasList)
cnv.setScale(dim, getScale(dim));
}
}
if (processAll || (type == IcyCanvasEventType.ROTATION_CHANGED))
{
// no information about dimension --> set all
if (processAll || (dim == DimensionId.NULL))
{
final double rotX = getRotationX();
final double rotY = getRotationY();
final double rotZ = getRotationZ();
final double rotT = getRotationT();
final double rotC = getRotationC();
for (IcyCanvas cnv : canvasList)
{
cnv.setRotationX(rotX);
cnv.setRotationY(rotY);
cnv.setRotationZ(rotZ);
cnv.setRotationT(rotT);
cnv.setRotationC(rotC);
}
}
else
{
for (IcyCanvas cnv : canvasList)
cnv.setRotation(dim, getRotation(dim));
}
}
// process offset in last as it can be limited depending destination scale value
if (processAll || (type == IcyCanvasEventType.OFFSET_CHANGED))
{
// no information about dimension --> set all
if (processAll || (dim == DimensionId.NULL))
{
final int offX = getOffsetX();
final int offY = getOffsetY();
final int offZ = getOffsetZ();
final int offT = getOffsetT();
final int offC = getOffsetC();
for (IcyCanvas cnv : canvasList)
{
cnv.setOffsetX(offX);
cnv.setOffsetY(offY);
cnv.setOffsetZ(offZ);
cnv.setOffsetT(offT);
cnv.setOffsetC(offC);
}
}
else
{
for (IcyCanvas cnv : canvasList)
cnv.setOffset(dim, getOffset(dim));
}
}
}
// cursor synchronization
if (isSynchOnCursor())
{
// mouse synchronization
if (processAll || (type == IcyCanvasEventType.MOUSE_IMAGE_POSITION_CHANGED))
{
// no information about dimension --> set all
if (processAll || (dim == DimensionId.NULL))
{
final double mipX = getMouseImagePosX();
final double mipY = getMouseImagePosY();
final double mipZ = getMouseImagePosZ();
final double mipT = getMouseImagePosT();
final double mipC = getMouseImagePosC();
for (IcyCanvas cnv : canvasList)
{
cnv.setMouseImagePosX(mipX);
cnv.setMouseImagePosY(mipY);
cnv.setMouseImagePosZ(mipZ);
cnv.setMouseImagePosT(mipT);
cnv.setMouseImagePosC(mipC);
}
}
else
{
for (IcyCanvas cnv : canvasList)
cnv.setMouseImagePos(dim, getMouseImagePos(dim));
}
}
}
}
/**
* Get position for specified dimension
*/
public int getPosition(DimensionId dim)
{
switch (dim)
{
case X:
return getPositionX();
case Y:
return getPositionY();
case Z:
return getPositionZ();
case T:
return getPositionT();
case C:
return getPositionC();
}
return 0;
}
/**
* @return current X (-1 if all selected)
*/
public int getPositionX()
{
return -1;
}
/**
* @return current Y (-1 if all selected)
*/
public int getPositionY()
{
return -1;
}
/**
* @return current Z (-1 if all selected)
*/
public int getPositionZ()
{
return posZ;
}
/**
* @return current T (-1 if all selected)
*/
public int getPositionT()
{
return posT;
}
/**
* @return current C (-1 if all selected)
*/
public int getPositionC()
{
return posC;
}
/**
* Returns the 5D canvas position (-1 mean that the complete dimension is selected)
*/
public Point5D.Integer getPosition5D()
{
return new Point5D.Integer(getPositionX(), getPositionY(), getPositionZ(), getPositionT(), getPositionC());
}
/**
* @return current Z (-1 if all selected)
* @deprecated uses getPositionZ() instead
*/
@Deprecated
public int getZ()
{
return getPositionZ();
}
/**
* @return current T (-1 if all selected)
* @deprecated uses getPositionT() instead
*/
@Deprecated
public int getT()
{
return getPositionT();
}
/**
* @return current C (-1 if all selected)
* @deprecated uses getPositionC() instead
*/
@Deprecated
public int getC()
{
return getPositionC();
}
/**
* Get maximum position for specified dimension
*/
public double getMaxPosition(DimensionId dim)
{
switch (dim)
{
case X:
return getMaxPositionX();
case Y:
return getMaxPositionY();
case Z:
return getMaxPositionZ();
case T:
return getMaxPositionT();
case C:
return getMaxPositionC();
}
return 0;
}
/**
* Get maximum X value
*/
public int getMaxPositionX()
{
final Sequence sequence = getSequence();
// have to test this as we release sequence reference on closed
if (sequence == null)
return 0;
return Math.max(0, getImageSizeX() - 1);
}
/**
* Get maximum Y value
*/
public int getMaxPositionY()
{
final Sequence sequence = getSequence();
// have to test this as we release sequence reference on closed
if (sequence == null)
return 0;
return Math.max(0, getImageSizeY() - 1);
}
/**
* Get maximum Z value
*/
public int getMaxPositionZ()
{
final Sequence sequence = getSequence();
// have to test this as we release sequence reference on closed
if (sequence == null)
return 0;
return Math.max(0, getImageSizeZ() - 1);
}
/**
* Get maximum T value
*/
public int getMaxPositionT()
{
final Sequence sequence = getSequence();
// have to test this as we release sequence reference on closed
if (sequence == null)
return 0;
return Math.max(0, getImageSizeT() - 1);
}
/**
* Get maximum C value
*/
public int getMaxPositionC()
{
final Sequence sequence = getSequence();
// have to test this as we release sequence reference on closed
if (sequence == null)
return 0;
return Math.max(0, getImageSizeC() - 1);
}
/**
* Get the maximum 5D position for the canvas.
*
* @see #getPosition5D()
*/
public Point5D.Integer getMaxPosition5D()
{
return new Point5D.Integer(getMaxPositionX(), getMaxPositionY(), getMaxPositionZ(), getMaxPositionT(),
getMaxPositionC());
}
/**
* @deprecated Use {@link #getMaxPosition(DimensionId)} instead
*/
@Deprecated
public double getMax(DimensionId dim)
{
return getMaxPosition(dim);
}
/**
* @deprecated Use {@link #getMaxPositionX()} instead
*/
@Deprecated
public int getMaxX()
{
return getMaxPositionX();
}
/**
* @deprecated Use {@link #getMaxPositionY()} instead
*/
@Deprecated
public int getMaxY()
{
return getMaxPositionY();
}
/**
* @deprecated Use {@link #getMaxPositionZ()} instead
*/
@Deprecated
public int getMaxZ()
{
return getMaxPositionZ();
}
/**
* @deprecated Use {@link #getMaxPositionT()} instead
*/
@Deprecated
public int getMaxT()
{
return getMaxPositionT();
}
/**
* @deprecated Use {@link #getMaxPositionC()} instead
*/
@Deprecated
public int getMaxC()
{
return getMaxPositionC();
}
/**
* Get canvas view size for specified Dimension
*/
public int getCanvasSize(DimensionId dim)
{
switch (dim)
{
case X:
return getCanvasSizeX();
case Y:
return getCanvasSizeY();
case Z:
return getCanvasSizeZ();
case T:
return getCanvasSizeT();
case C:
return getCanvasSizeC();
}
// size not supported
return -1;
}
/**
* Returns the canvas view size X.
*/
public int getCanvasSizeX()
{
final Component comp = getViewComponent();
int res = 0;
if (comp != null)
{
// by default we use view component width
res = comp.getWidth();
// preferred width if size not yet set
if (res == 0)
res = comp.getPreferredSize().width;
}
return res;
}
/**
* Returns the canvas view size Y.
*/
public int getCanvasSizeY()
{
final Component comp = getViewComponent();
int res = 0;
if (comp != null)
{
// by default we use view component width
res = comp.getHeight();
// preferred width if size not yet set
if (res == 0)
res = comp.getPreferredSize().height;
}
return res;
}
/**
* Returns the canvas view size Z.
*/
public int getCanvasSizeZ()
{
// by default : no Z dimension
return 1;
}
/**
* Returns the canvas view size T.
*/
public int getCanvasSizeT()
{
// by default : no T dimension
return 1;
}
/**
* Returns the canvas view size C.
*/
public int getCanvasSizeC()
{
// by default : no C dimension
return 1;
}
/**
* Returns the mouse position (in canvas coordinate space).
*/
public Point getMousePos()
{
return (Point) mousePos.clone();
}
/**
* Get mouse image position for specified Dimension
*/
public double getMouseImagePos(DimensionId dim)
{
switch (dim)
{
case X:
return getMouseImagePosX();
case Y:
return getMouseImagePosY();
case Z:
return getMouseImagePosZ();
case T:
return getMouseImagePosT();
case C:
return getMouseImagePosC();
}
return 0;
}
/**
* mouse X image position
*/
public double getMouseImagePosX()
{
// default implementation
return getPositionX();
}
/**
* mouse Y image position
*/
public double getMouseImagePosY()
{
// default implementation
return getPositionY();
}
/**
* mouse Z image position
*/
public double getMouseImagePosZ()
{
// default implementation
return getPositionZ();
}
/**
* mouse T image position
*/
public double getMouseImagePosT()
{
// default implementation
return getPositionT();
}
/**
* mouse C image position
*/
public double getMouseImagePosC()
{
// default implementation
return getPositionC();
}
/**
* Returns the 5D mouse image position
*/
public Point5D.Double getMouseImagePos5D()
{
return new Point5D.Double(getMouseImagePosX(), getMouseImagePosY(), getMouseImagePosZ(), getMouseImagePosT(),
getMouseImagePosC());
}
/**
* Get offset for specified Dimension
*/
public int getOffset(DimensionId dim)
{
switch (dim)
{
case X:
return getOffsetX();
case Y:
return getOffsetY();
case Z:
return getOffsetZ();
case T:
return getOffsetT();
case C:
return getOffsetC();
}
return 0;
}
/**
* X offset
*/
public int getOffsetX()
{
return 0;
}
/**
* Y offset
*/
public int getOffsetY()
{
return 0;
}
/**
* Z offset
*/
public int getOffsetZ()
{
return 0;
}
/**
* T offset
*/
public int getOffsetT()
{
return 0;
}
/**
* C offset
*/
public int getOffsetC()
{
return 0;
}
/**
* Returns the 5D offset.
*/
public Point5D.Integer getOffset5D()
{
return new Point5D.Integer(getOffsetX(), getOffsetY(), getOffsetZ(), getOffsetT(), getOffsetC());
}
/**
* X image offset
*
* @deprecated use getOffsetX() instead
*/
@Deprecated
public int getImageOffsetX()
{
return 0;
}
/**
* Y image offset
*
* @deprecated use getOffsetY() instead
*/
@Deprecated
public int getImageOffsetY()
{
return 0;
}
/**
* Z image offset
*
* @deprecated use getOffsetZ() instead
*/
@Deprecated
public int getImageOffsetZ()
{
return 0;
}
/**
* T image offset
*
* @deprecated use getOffsetT() instead
*/
@Deprecated
public int getImageOffsetT()
{
return 0;
}
/**
* C image offset
*
* @deprecated use getOffsetC() instead
*/
@Deprecated
public int getImageOffsetC()
{
return 0;
}
/**
* X canvas offset
*
* @deprecated use getOffsetX() instead
*/
@Deprecated
public int getCanvasOffsetX()
{
return 0;
}
/**
* Y canvas offset
*
* @deprecated use getOffsetY() instead
*/
@Deprecated
public int getCanvasOffsetY()
{
return 0;
}
/**
* Z canvas offset
*
* @deprecated use getOffsetZ() instead
*/
@Deprecated
public int getCanvasOffsetZ()
{
return 0;
}
/**
* T canvas offset
*
* @deprecated use getOffsetT() instead
*/
@Deprecated
public int getCanvasOffsetT()
{
return 0;
}
/**
* C canvas offset
*
* @deprecated use getOffsetC() instead
*/
@Deprecated
public int getCanvasOffsetC()
{
return 0;
}
/**
* X scale factor
*
* @deprecated use getScaleX() instead
*/
@Deprecated
public double getScaleFactorX()
{
return getScaleX();
}
/**
* Y scale factor
*
* @deprecated use getScaleY() instead
*/
@Deprecated
public double getScaleFactorY()
{
return getScaleY();
}
/**
* Z scale factor
*
* @deprecated use getScaleZ() instead
*/
@Deprecated
public double getScaleFactorZ()
{
return getScaleZ();
}
/**
* T scale factor
*
* @deprecated use getScaleT() instead
*/
@Deprecated
public double getScaleFactorT()
{
return getScaleT();
}
/**
* C scale factor
*
* @deprecated use getScaleC() instead
*/
@Deprecated
public double getScaleFactorC()
{
return getScaleC();
}
/**
* Get scale factor for specified Dimension
*/
public double getScale(DimensionId dim)
{
switch (dim)
{
case X:
return getScaleX();
case Y:
return getScaleY();
case Z:
return getScaleZ();
case T:
return getScaleT();
case C:
return getScaleC();
}
return 1d;
}
/**
* X scale factor
*/
public double getScaleX()
{
return 1d;
}
/**
* Y scale factor
*/
public double getScaleY()
{
return 1d;
}
/**
* Z scale factor
*/
public double getScaleZ()
{
return 1d;
}
/**
* T scale factor
*/
public double getScaleT()
{
return 1d;
}
/**
* C scale factor
*/
public double getScaleC()
{
return 1d;
}
/**
* Get rotation angle (radian) for specified Dimension
*/
public double getRotation(DimensionId dim)
{
switch (dim)
{
case X:
return getRotationX();
case Y:
return getRotationY();
case Z:
return getRotationZ();
case T:
return getRotationT();
case C:
return getRotationC();
}
return 1d;
}
/**
* X rotation angle (radian)
*/
public double getRotationX()
{
return 0d;
}
/**
* Y rotation angle (radian)
*/
public double getRotationY()
{
return 0d;
}
/**
* Z rotation angle (radian)
*/
public double getRotationZ()
{
return 0d;
}
/**
* T rotation angle (radian)
*/
public double getRotationT()
{
return 0d;
}
/**
* C rotation angle (radian)
*/
public double getRotationC()
{
return 0d;
}
/**
* Get image size for specified Dimension
*/
public int getImageSize(DimensionId dim)
{
switch (dim)
{
case X:
return getImageSizeX();
case Y:
return getImageSizeY();
case Z:
return getImageSizeZ();
case T:
return getImageSizeT();
case C:
return getImageSizeC();
}
return 0;
}
/**
* Get image size X
*/
public int getImageSizeX()
{
final Sequence seq = getSequence();
if (seq != null)
return seq.getSizeX();
return 0;
}
/**
* Get image size Y
*/
public int getImageSizeY()
{
final Sequence seq = getSequence();
if (seq != null)
return seq.getSizeY();
return 0;
}
/**
* Get image size Z
*/
public int getImageSizeZ()
{
final Sequence seq = getSequence();
if (seq != null)
return seq.getSizeZ();
return 0;
}
/**
* Get image size T
*/
public int getImageSizeT()
{
final Sequence seq = getSequence();
if (seq != null)
return seq.getSizeT();
return 0;
}
/**
* Get image size C
*/
public int getImageSizeC()
{
final Sequence seq = getSequence();
if (seq != null)
return seq.getSizeC();
return 0;
}
/**
* Get image size in canvas pixel coordinate for specified Dimension
*
* @deprecated doesn't take rotation transformation in account.<br>
* Use IcyCanvasXD.getImageCanvasSize(..) instead
*/
@Deprecated
public int getImageCanvasSize(DimensionId dim)
{
switch (dim)
{
case X:
return getImageCanvasSizeX();
case Y:
return getImageCanvasSizeY();
case Z:
return getImageCanvasSizeZ();
case T:
return getImageCanvasSizeT();
case C:
return getImageCanvasSizeC();
}
return 0;
}
/**
* Get image size X in canvas pixel coordinate
*
* @deprecated doesn't take rotation transformation in account.<br>
* Use IcyCanvasXD.getImageCanvasSize(..) instead
*/
@Deprecated
public int getImageCanvasSizeX()
{
return imageToCanvasDeltaX(getImageSizeX());
}
/**
* Get image size Y in canvas pixel coordinate
*
* @deprecated doesn't take rotation transformation in account.<br>
* Use IcyCanvasXD.getImageCanvasSize(..) instead
*/
@Deprecated
public int getImageCanvasSizeY()
{
return imageToCanvasDeltaY(getImageSizeY());
}
/**
* Get image size Z in canvas pixel coordinate
*
* @deprecated doesn't take rotation transformation in account.<br>
* Use IcyCanvasXD.getImageCanvasSize(..) instead
*/
@Deprecated
public int getImageCanvasSizeZ()
{
return imageToCanvasDeltaZ(getImageSizeZ());
}
/**
* Get image size T in canvas pixel coordinate
*
* @deprecated doesn't take rotation transformation in account.<br>
* Use IcyCanvasXD.getImageCanvasSize(..) instead
*/
@Deprecated
public int getImageCanvasSizeT()
{
return imageToCanvasDeltaT(getImageSizeT());
}
/**
* Get image size C in canvas pixel coordinate
*
* @deprecated doesn't take rotation transformation in account.<br>
* Use IcyCanvasXD.getImageCanvasSize(..) instead
*/
@Deprecated
public int getImageCanvasSizeC()
{
return imageToCanvasDeltaC(getImageSizeC());
}
/**
* Set position for specified dimension
*/
public void setPosition(DimensionId dim, int value)
{
switch (dim)
{
case X:
setPositionX(value);
break;
case Y:
setPositionY(value);
break;
case Z:
setPositionZ(value);
break;
case T:
setPositionT(value);
break;
case C:
setPositionC(value);
break;
}
}
/**
* Set Z position
*
* @deprecated uses setPositionZ(int) instead
*/
@Deprecated
public void setZ(int z)
{
setPositionZ(z);
}
/**
* Set T position
*
* @deprecated uses setPositionT(int) instead
*/
@Deprecated
public void setT(int t)
{
setPositionT(t);
}
/**
* Set C position
*
* @deprecated uses setPositionC(int) instead
*/
@Deprecated
public void setC(int c)
{
setPositionC(c);
}
/**
* Set X position
*/
public void setPositionX(int x)
{
final int adjX = Math.max(-1, Math.min(x, getMaxPositionX()));
if (getPositionX() != adjX)
setPositionXInternal(adjX);
}
/**
* Set Y position
*/
public void setPositionY(int y)
{
final int adjY = Math.max(-1, Math.min(y, getMaxPositionY()));
if (getPositionY() != adjY)
setPositionYInternal(adjY);
}
/**
* Set Z position
*/
public void setPositionZ(int z)
{
final int adjZ = Math.max(-1, Math.min(z, getMaxPositionZ()));
if (getPositionZ() != adjZ)
setPositionZInternal(adjZ);
}
/**
* Set T position
*/
public void setPositionT(int t)
{
final int adjT = Math.max(-1, Math.min(t, getMaxPositionT()));
if (getPositionT() != adjT)
setPositionTInternal(adjT);
}
/**
* Set C position
*/
public void setPositionC(int c)
{
final int adjC = Math.max(-1, Math.min(c, getMaxPositionC()));
if (getPositionC() != adjC)
setPositionCInternal(adjC);
}
/**
* Set X position internal
*/
protected void setPositionXInternal(int x)
{
posX = x;
// common process on position change
positionChanged(DimensionId.X);
}
/**
* Set Y position internal
*/
protected void setPositionYInternal(int y)
{
posY = y;
// common process on position change
positionChanged(DimensionId.Y);
}
/**
* Set Z position internal
*/
protected void setPositionZInternal(int z)
{
posZ = z;
// common process on position change
positionChanged(DimensionId.Z);
}
/**
* Set T position internal
*/
protected void setPositionTInternal(int t)
{
posT = t;
// common process on position change
positionChanged(DimensionId.T);
}
/**
* Set C position internal
*/
protected void setPositionCInternal(int c)
{
posC = c;
// common process on position change
positionChanged(DimensionId.C);
}
/**
* Set mouse position (in canvas coordinate space).<br>
* The method returns <code>true</code> if the mouse position actually changed.
*/
public boolean setMousePos(int x, int y)
{
if ((mousePos.x != x) || (mousePos.y != y))
{
mousePos.x = x;
mousePos.y = y;
// mouse image position as probably changed so this method should be overridden
// to implement the correct calculation for the mouse iamge position change
return true;
}
return false;
}
/**
* Set mouse position (in canvas coordinate space)
*/
public void setMousePos(Point point)
{
setMousePos(point.x, point.y);
}
/**
* Set mouse image position for specified dimension (required for synchronization)
*/
public void setMouseImagePos(DimensionId dim, double value)
{
switch (dim)
{
case X:
setMouseImagePosX(value);
break;
case Y:
setMouseImagePosY(value);
break;
case Z:
setMouseImagePosZ(value);
break;
case T:
setMouseImagePosT(value);
break;
case C:
setMouseImagePosC(value);
break;
}
}
/**
* Set mouse X image position
*/
public void setMouseImagePosX(double value)
{
if (getMouseImagePosX() != value)
// internal set
setMouseImagePosXInternal(value);
}
/**
* Set mouse Y image position
*/
public void setMouseImagePosY(double value)
{
if (getMouseImagePosY() != value)
// internal set
setMouseImagePosYInternal(value);
}
/**
* Set mouse Z image position
*/
public void setMouseImagePosZ(double value)
{
if (getMouseImagePosZ() != value)
// internal set
setMouseImagePosZInternal(value);
}
/**
* Set mouse T image position
*/
public void setMouseImagePosT(double value)
{
if (getMouseImagePosT() != value)
// internal set
setMouseImagePosTInternal(value);
}
/**
* Set mouse C image position
*/
public void setMouseImagePosC(double value)
{
if (getMouseImagePosC() != value)
// internal set
setMouseImagePosCInternal(value);
}
/**
* Set offset X internal
*/
protected void setMouseImagePosXInternal(double value)
{
// notify change
mouseImagePositionChanged(DimensionId.X);
}
/**
* Set offset Y internal
*/
protected void setMouseImagePosYInternal(double value)
{
// notify change
mouseImagePositionChanged(DimensionId.Y);
}
/**
* Set offset Z internal
*/
protected void setMouseImagePosZInternal(double value)
{
// notify change
mouseImagePositionChanged(DimensionId.Z);
}
/**
* Set offset T internal
*/
protected void setMouseImagePosTInternal(double value)
{
// notify change
mouseImagePositionChanged(DimensionId.T);
}
/**
* Set offset C internal
*/
protected void setMouseImagePosCInternal(double value)
{
// notify change
mouseImagePositionChanged(DimensionId.C);
}
/**
* Set offset for specified dimension
*/
public void setOffset(DimensionId dim, int value)
{
switch (dim)
{
case X:
setOffsetX(value);
break;
case Y:
setOffsetY(value);
break;
case Z:
setOffsetZ(value);
break;
case T:
setOffsetT(value);
break;
case C:
setOffsetC(value);
break;
}
}
/**
* Set offset X
*/
public void setOffsetX(int value)
{
if (getOffsetX() != value)
// internal set
setOffsetXInternal(value);
}
/**
* Set offset Y
*/
public void setOffsetY(int value)
{
if (getOffsetY() != value)
// internal set
setOffsetYInternal(value);
}
/**
* Set offset Z
*/
public void setOffsetZ(int value)
{
if (getOffsetZ() != value)
// internal set
setOffsetZInternal(value);
}
/**
* Set offset T
*/
public void setOffsetT(int value)
{
if (getOffsetT() != value)
// internal set
setOffsetTInternal(value);
}
/**
* Set offset C
*/
public void setOffsetC(int value)
{
if (getOffsetC() != value)
// internal set
setOffsetCInternal(value);
}
/**
* Set offset X internal
*/
protected void setOffsetXInternal(int value)
{
// notify change
offsetChanged(DimensionId.X);
}
/**
* Set offset Y internal
*/
protected void setOffsetYInternal(int value)
{
// notify change
offsetChanged(DimensionId.Y);
}
/**
* Set offset Z internal
*/
protected void setOffsetZInternal(int value)
{
// notify change
offsetChanged(DimensionId.Z);
}
/**
* Set offset T internal
*/
protected void setOffsetTInternal(int value)
{
// notify change
offsetChanged(DimensionId.T);
}
/**
* Set offset C internal
*/
protected void setOffsetCInternal(int value)
{
// notify change
offsetChanged(DimensionId.C);
}
/**
* Set scale factor for specified dimension
*/
public void setScale(DimensionId dim, double value)
{
switch (dim)
{
case X:
setScaleX(value);
break;
case Y:
setScaleY(value);
break;
case Z:
setScaleZ(value);
break;
case T:
setScaleT(value);
break;
case C:
setScaleC(value);
break;
}
}
/**
* Set scale factor X
*/
public void setScaleX(double value)
{
if (getScaleX() != value)
// internal set
setScaleXInternal(value);
}
/**
* Set scale factor Y
*/
public void setScaleY(double value)
{
if (getScaleY() != value)
// internal set
setScaleYInternal(value);
}
/**
* Set scale factor Z
*/
public void setScaleZ(double value)
{
if (getScaleZ() != value)
// internal set
setScaleZInternal(value);
}
/**
* Set scale factor T
*/
public void setScaleT(double value)
{
if (getScaleT() != value)
// internal set
setScaleTInternal(value);
}
/**
* Set scale factor C
*/
public void setScaleC(double value)
{
if (getScaleC() != value)
// internal set
setScaleCInternal(value);
}
/**
* Set scale factor X internal
*/
protected void setScaleXInternal(double value)
{
// notify change
scaleChanged(DimensionId.X);
}
/**
* Set scale factor Y internal
*/
protected void setScaleYInternal(double value)
{
// notify change
scaleChanged(DimensionId.Y);
}
/**
* Set scale factor Z internal
*/
protected void setScaleZInternal(double value)
{
// notify change
scaleChanged(DimensionId.Z);
}
/**
* Set scale factor T internal
*/
protected void setScaleTInternal(double value)
{
// notify change
scaleChanged(DimensionId.T);
}
/**
* Set scale factor C internal
*/
protected void setScaleCInternal(double value)
{
// notify change
scaleChanged(DimensionId.C);
}
/**
* Set rotation angle (radian) for specified dimension
*/
public void setRotation(DimensionId dim, double value)
{
switch (dim)
{
case X:
setRotationX(value);
break;
case Y:
setRotationY(value);
break;
case Z:
setRotationZ(value);
break;
case T:
setRotationT(value);
break;
case C:
setRotationC(value);
break;
}
}
/**
* Set X rotation angle (radian)
*/
public void setRotationX(double value)
{
if (getRotationX() != value)
// internal set
setRotationXInternal(value);
}
/**
* Set Y rotation angle (radian)
*/
public void setRotationY(double value)
{
if (getRotationY() != value)
// internal set
setRotationYInternal(value);
}
/**
* Set Z rotation angle (radian)
*/
public void setRotationZ(double value)
{
if (getRotationZ() != value)
// internal set
setRotationZInternal(value);
}
/**
* Set T rotation angle (radian)
*/
public void setRotationT(double value)
{
if (getRotationT() != value)
// internal set
setRotationTInternal(value);
}
/**
* Set C rotation angle (radian)
*/
public void setRotationC(double value)
{
if (getRotationC() != value)
// internal set
setRotationCInternal(value);
}
/**
* Set X rotation angle internal
*/
protected void setRotationXInternal(double value)
{
// notify change
rotationChanged(DimensionId.X);
}
/**
* Set Y rotation angle internal
*/
protected void setRotationYInternal(double value)
{
// notify change
rotationChanged(DimensionId.Y);
}
/**
* Set Z rotation angle internal
*/
protected void setRotationZInternal(double value)
{
// notify change
rotationChanged(DimensionId.Z);
}
/**
* Set T rotation angle internal
*/
protected void setRotationTInternal(double value)
{
// notify change
rotationChanged(DimensionId.T);
}
/**
* Set C rotation angle internal
*/
protected void setRotationCInternal(double value)
{
// notify change
rotationChanged(DimensionId.C);
}
/**
* Called when mouse image position changed
*/
public void mouseImagePositionChanged(DimensionId dim)
{
// handle with updater
updater.changed(new IcyCanvasEvent(this, IcyCanvasEventType.MOUSE_IMAGE_POSITION_CHANGED, dim));
}
/**
* Called when canvas offset changed
*/
public void offsetChanged(DimensionId dim)
{
// handle with updater
updater.changed(new IcyCanvasEvent(this, IcyCanvasEventType.OFFSET_CHANGED, dim));
}
/**
* Called when scale factor changed
*/
public void scaleChanged(DimensionId dim)
{
// handle with updater
updater.changed(new IcyCanvasEvent(this, IcyCanvasEventType.SCALE_CHANGED, dim));
}
/**
* Called when rotation angle changed
*/
public void rotationChanged(DimensionId dim)
{
// handle with updater
updater.changed(new IcyCanvasEvent(this, IcyCanvasEventType.ROTATION_CHANGED, dim));
}
/**
* Convert specified canvas delta X to image delta X.<br>
* WARNING: Does not take in account the rotation transformation.<br>
* Use the IcyCanvasXD.canvasToImageDelta(...) method instead for rotation transformed delta.
*/
public double canvasToImageDeltaX(int value)
{
return value / getScaleX();
}
/**
* Convert specified canvas delta Y to image delta Y.<br>
* WARNING: Does not take in account the rotation transformation.<br>
* Use the IcyCanvasXD.canvasToImageDelta(...) method instead for rotation transformed delta.
*/
public double canvasToImageDeltaY(int value)
{
return value / getScaleY();
}
/**
* Convert specified canvas delta Z to image delta Z.<br>
* WARNING: Does not take in account the rotation transformation.<br>
* Use the IcyCanvasXD.canvasToImageDelta(...) method instead for rotation transformed delta.
*/
public double canvasToImageDeltaZ(int value)
{
return value / getScaleZ();
}
/**
* Convert specified canvas delta T to image delta T.<br>
* WARNING: Does not take in account the rotation transformation.<br>
* Use the IcyCanvasXD.canvasToImageDelta(...) method instead for rotation transformed delta.
*/
public double canvasToImageDeltaT(int value)
{
return value / getScaleT();
}
/**
* Convert specified canvas delta C to image delta C.<br>
* WARNING: Does not take in account the rotation transformation.<br>
* Use the IcyCanvasXD.canvasToImageDelta(...) method instead for rotation transformed delta.
*/
public double canvasToImageDeltaC(int value)
{
return value / getScaleC();
}
/**
* Convert specified canvas delta X to log image delta X.<br>
* The conversion is still affected by zoom ratio but with specified logarithm form.<br>
* WARNING: Does not take in account the rotation transformation.<br>
* Use the IcyCanvasXD.canvasToImageLogDelta(...) method instead for rotation transformed delta.
*/
public double canvasToImageLogDeltaX(int value, double logFactor)
{
final double scaleFactor = getScaleX();
// keep the zoom ratio but in a log perspective
return value / (scaleFactor / Math.pow(10, Math.log10(scaleFactor) / logFactor));
}
/**
* Convert specified canvas delta X to log image delta X.<br>
* The conversion is still affected by zoom ratio but with logarithm form.<br>
* WARNING: Does not take in account the rotation transformation.<br>
* Use the IcyCanvasXD.canvasToImageLogDelta(...) method instead for rotation transformed delta.
*/
public double canvasToImageLogDeltaX(int value)
{
return canvasToImageLogDeltaX(value, 5d);
}
/**
* Convert specified canvas delta Y to log image delta Y.<br>
* The conversion is still affected by zoom ratio but with specified logarithm form.<br>
* WARNING: Does not take in account the rotation transformation.<br>
* Use the IcyCanvasXD.canvasToImageLogDelta(...) method instead for rotation transformed delta.
*/
public double canvasToImageLogDeltaY(int value, double logFactor)
{
final double scaleFactor = getScaleY();
// keep the zoom ratio but in a log perspective
return value / (scaleFactor / Math.pow(10, Math.log10(scaleFactor) / logFactor));
}
/**
* Convert specified canvas delta Y to log image delta Y.<br>
* The conversion is still affected by zoom ratio but with logarithm form.<br>
* WARNING: Does not take in account the rotation transformation.<br>
* Use the IcyCanvasXD.canvasToImageLogDelta(...) method instead for rotation transformed delta.
*/
public double canvasToImageLogDeltaY(int value)
{
return canvasToImageLogDeltaY(value, 5d);
}
/**
* Convert specified canvas X coordinate to image X coordinate
*
* @deprecated Cannot give correct result if rotation is applied so use
* IcyCanvasXD.canvasToImage(...) instead
*/
@Deprecated
public double canvasToImageX(int value)
{
return canvasToImageDeltaX(value - getOffsetX());
}
/**
* Convert specified canvas Y coordinate to image Y coordinate
*
* @deprecated Cannot give correct result if rotation is applied so use
* IcyCanvasXD.canvasToImage(...) instead
*/
@Deprecated
public double canvasToImageY(int value)
{
return canvasToImageDeltaY(value - getOffsetY());
}
/**
* Convert specified canvas Z coordinate to image Z coordinate
*
* @deprecated Cannot give correct result if rotation is applied so use
* IcyCanvasXD.canvasToImage(...) instead
*/
@Deprecated
public double canvasToImageZ(int value)
{
return canvasToImageDeltaZ(value - getOffsetZ());
}
/**
* Convert specified canvas T coordinate to image T coordinate
*
* @deprecated Cannot give correct result if rotation is applied so use
* IcyCanvasXD.canvasToImage(...) instead
*/
@Deprecated
public double canvasToImageT(int value)
{
return canvasToImageDeltaT(value - getOffsetT());
}
/**
* Convert specified canvas C coordinate to image C coordinate
*
* @deprecated Cannot give correct result if rotation is applied so use
* IcyCanvasXD.canvasToImage(...) instead
*/
@Deprecated
public double canvasToImageC(int value)
{
return canvasToImageDeltaC(value - getOffsetC());
}
/**
* Convert specified image delta X to canvas delta X.<br>
* WARNING: Does not take in account the rotation transformation.<br>
* Use the IcyCanvasXD.imageToCanvasDelta(...) method instead for rotation transformed delta.
*/
public int imageToCanvasDeltaX(double value)
{
return (int) (value * getScaleX());
}
/**
* Convert specified image delta Y to canvas delta Y.<br>
* WARNING: Does not take in account the rotation transformation.<br>
* Use the IcyCanvasXD.imageToCanvasDelta(...) method instead for rotation transformed delta.
*/
public int imageToCanvasDeltaY(double value)
{
return (int) (value * getScaleY());
}
/**
* Convert specified image delta Z to canvas delta Z.<br>
* WARNING: Does not take in account the rotation transformation.<br>
* Use the IcyCanvasXD.imageToCanvasDelta(...) method instead for rotation transformed delta.
*/
public int imageToCanvasDeltaZ(double value)
{
return (int) (value * getScaleZ());
}
/**
* Convert specified image delta T to canvas delta T.<br>
* WARNING: Does not take in account the rotation transformation.<br>
* Use the IcyCanvasXD.imageToCanvasDelta(...) method instead for rotation transformed delta.
*/
public int imageToCanvasDeltaT(double value)
{
return (int) (value * getScaleT());
}
/**
* Convert specified image delta C to canvas delta C.<br>
* WARNING: Does not take in account the rotation transformation.<br>
* Use the IcyCanvasXD.imageToCanvasDelta(...) method instead for rotation transformed delta.
*/
public int imageToCanvasDeltaC(double value)
{
return (int) (value * getScaleC());
}
/**
* Convert specified image X coordinate to canvas X coordinate
*
* @deprecated Cannot give correct result if rotation is applied so use
* IcyCanvasXD.imageToCanvas(...) instead
*/
@Deprecated
public int imageToCanvasX(double value)
{
return imageToCanvasDeltaX(value) + getOffsetX();
}
/**
* Convert specified image Y coordinate to canvas Y coordinate
*
* @deprecated Cannot give correct result if rotation is applied so use
* IcyCanvasXD.imageToCanvas(...) instead
*/
@Deprecated
public int imageToCanvasY(double value)
{
return imageToCanvasDeltaY(value) + getOffsetY();
}
/**
* Convert specified image Z coordinate to canvas Z coordinate
*
* @deprecated Cannot give correct result if rotation is applied so use
* IcyCanvasXD.imageToCanvas(...) instead
*/
@Deprecated
public int imageToCanvasZ(double value)
{
return imageToCanvasDeltaZ(value) + getOffsetZ();
}
/**
* Convert specified image T coordinate to canvas T coordinate
*
* @deprecated Cannot give correct result if rotation is applied so use
* IcyCanvasXD.imageToCanvas(...) instead
*/
@Deprecated
public int imageToCanvasT(double value)
{
return imageToCanvasDeltaT(value) + getOffsetT();
}
/**
* Convert specified image C coordinate to canvas C coordinate
*
* @deprecated Cannot give correct result if rotation is applied so use
* IcyCanvasXD.imageToCanvas(...) instead
*/
@Deprecated
public int imageToCanvasC(double value)
{
return imageToCanvasDeltaC(value) + getOffsetC();
}
/**
* Helper to forward mouse press event to the overlays.
*
* @param event
* original mouse event
* @param pt
* mouse image position
*/
public void mousePressed(MouseEvent event, Point5D.Double pt)
{
final boolean globalVisible = isLayersVisible();
// send mouse event to overlays after so mouse canvas position is ok
for (Layer layer : getLayers(true))
{
if ((globalVisible && layer.isVisible()) || layer.getReceiveMouseEventOnHidden())
layer.getOverlay().mousePressed(event, pt, this);
}
}
/**
* Helper to forward mouse press event to the overlays.
*
* @param event
* original mouse event
*/
public void mousePressed(MouseEvent event)
{
mousePressed(event, getMouseImagePos5D());
}
/**
* Helper to forward mouse release event to the overlays.
*
* @param event
* original mouse event
* @param pt
* mouse image position
*/
public void mouseReleased(MouseEvent event, Point5D.Double pt)
{
final boolean globalVisible = isLayersVisible();
// send mouse event to overlays after so mouse canvas position is ok
for (Layer layer : getLayers(true))
{
if ((globalVisible && layer.isVisible()) || layer.getReceiveMouseEventOnHidden())
layer.getOverlay().mouseReleased(event, pt, this);
}
}
/**
* Helper to forward mouse release event to the overlays.
*
* @param event
* original mouse event
*/
public void mouseReleased(MouseEvent event)
{
mouseReleased(event, getMouseImagePos5D());
}
/**
* Helper to forward mouse click event to the overlays.
*
* @param event
* original mouse event
* @param pt
* mouse image position
*/
public void mouseClick(MouseEvent event, Point5D.Double pt)
{
final boolean globalVisible = isLayersVisible();
// send mouse event to overlays after so mouse canvas position is ok
for (Layer layer : getLayers(true))
{
if ((globalVisible && layer.isVisible()) || layer.getReceiveMouseEventOnHidden())
layer.getOverlay().mouseClick(event, pt, this);
}
}
/**
* Helper to forward mouse click event to the overlays.
*
* @param event
* original mouse event
*/
public void mouseClick(MouseEvent event)
{
mouseClick(event, getMouseImagePos5D());
}
/**
* Helper to forward mouse move event to the overlays.
*
* @param event
* original mouse event
* @param pt
* mouse image position
*/
public void mouseMove(MouseEvent event, Point5D.Double pt)
{
final boolean globalVisible = isLayersVisible();
// send mouse event to overlays after so mouse canvas position is ok
for (Layer layer : getLayers(true))
{
if ((globalVisible && layer.isVisible()) || layer.getReceiveMouseEventOnHidden())
layer.getOverlay().mouseMove(event, pt, this);
}
}
/**
* Helper to forward mouse mouse event to the overlays.
*
* @param event
* original mouse event
*/
public void mouseMove(MouseEvent event)
{
mouseMove(event, getMouseImagePos5D());
}
/**
* Helper to forward mouse drag event to the overlays.
*
* @param event
* original mouse event
* @param pt
* mouse image position
*/
public void mouseDrag(MouseEvent event, Point5D.Double pt)
{
final boolean globalVisible = isLayersVisible();
// send mouse event to overlays after so mouse canvas position is ok
for (Layer layer : getLayers(true))
{
if ((globalVisible && layer.isVisible()) || layer.getReceiveMouseEventOnHidden())
layer.getOverlay().mouseDrag(event, pt, this);
}
}
/**
* Helper to forward mouse drag event to the overlays.
*
* @param event
* original mouse event
*/
public void mouseDrag(MouseEvent event)
{
mouseDrag(event, getMouseImagePos5D());
}
/**
* Helper to forward mouse enter event to the overlays.
*
* @param event
* original mouse event
* @param pt
* mouse image position
*/
public void mouseEntered(MouseEvent event, Point5D.Double pt)
{
final boolean globalVisible = isLayersVisible();
// send mouse event to overlays after so mouse canvas position is ok
for (Layer layer : getLayers(true))
{
if ((globalVisible && layer.isVisible()) || layer.getReceiveMouseEventOnHidden())
layer.getOverlay().mouseEntered(event, pt, this);
}
}
/**
* Helper to forward mouse entered event to the overlays.
*
* @param event
* original mouse event
*/
public void mouseEntered(MouseEvent event)
{
mouseEntered(event, getMouseImagePos5D());
}
/**
* Helper to forward mouse exit event to the overlays.
*
* @param event
* original mouse event
* @param pt
* mouse image position
*/
public void mouseExited(MouseEvent event, Point5D.Double pt)
{
final boolean globalVisible = isLayersVisible();
// send mouse event to overlays after so mouse canvas position is ok
for (Layer layer : getLayers(true))
{
if ((globalVisible && layer.isVisible()) || layer.getReceiveMouseEventOnHidden())
layer.getOverlay().mouseExited(event, pt, this);
}
}
/**
* Helper to forward mouse exited event to the overlays.
*
* @param event
* original mouse event
*/
public void mouseExited(MouseEvent event)
{
mouseExited(event, getMouseImagePos5D());
}
/**
* Helper to forward mouse wheel event to the overlays.
*
* @param event
* original mouse event
* @param pt
* mouse image position
*/
public void mouseWheelMoved(MouseWheelEvent event, Point5D.Double pt)
{
final boolean globalVisible = isLayersVisible();
// send mouse event to overlays after so mouse canvas position is ok
for (Layer layer : getLayers(true))
{
if ((globalVisible && layer.isVisible()) || layer.getReceiveMouseEventOnHidden())
layer.getOverlay().mouseWheelMoved(event, pt, this);
}
}
/**
* Helper to forward mouse wheel event to the overlays.
*
* @param event
* original mouse event
*/
public void mouseWheelMoved(MouseWheelEvent event)
{
mouseWheelMoved(event, getMouseImagePos5D());
}
@Override
public void keyTyped(KeyEvent e)
{
}
@Override
public void keyPressed(KeyEvent e)
{
final boolean globalVisible = isLayersVisible();
final Point5D.Double pt = getMouseImagePos5D();
// forward event to overlays
for (Layer layer : getLayers(true))
{
if ((globalVisible && layer.isVisible()) || layer.getReceiveKeyEventOnHidden())
layer.getOverlay().keyPressed(e, pt, this);
}
if (!e.isConsumed())
{
switch (e.getKeyCode())
{
case KeyEvent.VK_0:
if (EventUtil.isShiftDown(e, true))
{
if (CanvasActions.globalDisableSyncAction.isEnabled())
{
CanvasActions.globalDisableSyncAction.execute();
e.consume();
}
}
else if (EventUtil.isNoModifier(e))
{
if (CanvasActions.disableSyncAction.isEnabled())
{
CanvasActions.disableSyncAction.execute();
e.consume();
}
}
break;
case KeyEvent.VK_1:
if (EventUtil.isShiftDown(e, true))
{
if (CanvasActions.globalSyncGroup1Action.isEnabled())
{
CanvasActions.globalSyncGroup1Action.execute();
e.consume();
}
}
else if (EventUtil.isNoModifier(e))
{
if (CanvasActions.syncGroup1Action.isEnabled())
{
CanvasActions.syncGroup1Action.execute();
e.consume();
}
}
break;
case KeyEvent.VK_2:
if (EventUtil.isShiftDown(e, true))
{
if (CanvasActions.globalSyncGroup2Action.isEnabled())
{
CanvasActions.globalSyncGroup2Action.execute();
e.consume();
}
}
else if (EventUtil.isNoModifier(e))
{
if (CanvasActions.syncGroup2Action.isEnabled())
{
CanvasActions.syncGroup2Action.execute();
e.consume();
}
}
break;
case KeyEvent.VK_3:
if (EventUtil.isShiftDown(e, true))
{
if (CanvasActions.globalSyncGroup3Action.isEnabled())
{
CanvasActions.globalSyncGroup3Action.execute();
e.consume();
}
}
else if (EventUtil.isNoModifier(e))
{
if (CanvasActions.syncGroup3Action.isEnabled())
{
CanvasActions.syncGroup3Action.execute();
e.consume();
}
}
break;
case KeyEvent.VK_4:
if (EventUtil.isShiftDown(e, true))
{
if (CanvasActions.globalSyncGroup4Action.isEnabled())
{
CanvasActions.globalSyncGroup4Action.execute();
e.consume();
}
}
else if (EventUtil.isNoModifier(e))
{
if (CanvasActions.syncGroup4Action.isEnabled())
{
CanvasActions.syncGroup4Action.execute();
e.consume();
}
}
break;
case KeyEvent.VK_G:
if (EventUtil.isShiftDown(e, true))
{
if (WindowActions.gridTileAction.isEnabled())
{
WindowActions.gridTileAction.execute();
e.consume();
}
}
break;
case KeyEvent.VK_H:
if (EventUtil.isShiftDown(e, true))
{
if (WindowActions.horizontalTileAction.isEnabled())
{
WindowActions.horizontalTileAction.execute();
e.consume();
}
}
break;
case KeyEvent.VK_A:
if (EventUtil.isMenuControlDown(e, true))
{
if (RoiActions.selectAllAction.isEnabled())
{
RoiActions.selectAllAction.execute();
e.consume();
}
}
break;
case KeyEvent.VK_V:
if (EventUtil.isShiftDown(e, true))
{
if (WindowActions.verticalTileAction.isEnabled())
{
WindowActions.verticalTileAction.execute();
e.consume();
}
}
else if (EventUtil.isMenuControlDown(e, true))
{
if (GeneralActions.pasteImageAction.isEnabled())
{
GeneralActions.pasteImageAction.execute();
e.consume();
}
else if (RoiActions.pasteAction.isEnabled())
{
RoiActions.pasteAction.execute();
e.consume();
}
}
else if (EventUtil.isAltDown(e, true))
{
if (RoiActions.pasteLinkAction.isEnabled())
{
RoiActions.pasteLinkAction.execute();
e.consume();
}
}
break;
case KeyEvent.VK_C:
if (EventUtil.isMenuControlDown(e, true))
{
// do this one first else copyImage hide it
if (RoiActions.copyAction.isEnabled())
{
// copy them to icy clipboard
RoiActions.copyAction.execute();
e.consume();
}
else if (GeneralActions.copyImageAction.isEnabled())
{
// copy image to system clipboard
GeneralActions.copyImageAction.execute();
e.consume();
}
}
else if (EventUtil.isAltDown(e, true))
{
if (RoiActions.copyLinkAction.isEnabled())
{
// copy link of selected ROI to clipboard
RoiActions.copyLinkAction.execute();
e.consume();
}
}
break;
}
}
}
@Override
public void keyReleased(KeyEvent e)
{
final boolean globalVisible = isLayersVisible();
final Point5D.Double pt = getMouseImagePos5D();
// forward event to overlays
for (Layer layer : getLayers(true))
{
if ((globalVisible && layer.isVisible()) || layer.getReceiveKeyEventOnHidden())
layer.getOverlay().keyReleased(e, pt, this);
}
}
/**
* Gets the image at position (t, z, c).
*/
public IcyBufferedImage getImage(int t, int z, int c)
{
if ((t == -1) || (z == -1))
return null;
final Sequence sequence = getSequence();
// have to test this as sequence reference can be release in viewer
if (sequence != null)
return sequence.getImage(t, z, c);
return null;
}
/**
* @deprecated Use {@link #getImage(int, int, int)} with C = -1 instead.
*/
@Deprecated
public IcyBufferedImage getImage(int t, int z)
{
return getImage(t, z, -1);
}
/**
* Get the current image.
*/
public IcyBufferedImage getCurrentImage()
{
return getImage(getPositionT(), getPositionZ(), getPositionC());
}
/**
* @deprecated use {@link #getRenderedImage(int, int, int, boolean)} instead
*/
@Deprecated
public final BufferedImage getRenderedImage(int t, int z, int c, int imageType, boolean canvasView)
{
return getRenderedImage(t, z, c, canvasView);
}
/**
* @deprecated use {@link #getRenderedSequence(boolean)} instead
*/
@Deprecated
public final Sequence getRenderedSequence(int imageType, boolean canvasView)
{
return getRenderedSequence(canvasView);
}
/**
* Returns a RGB or ARGB (depending support) BufferedImage representing the canvas view for
* image at position (t, z, c).
* Free feel to the canvas to handle or not a specific dimension.
*
* @param t
* T position of wanted image (-1 for complete sequence)
* @param z
* Z position of wanted image (-1 for complete stack)
* @param c
* C position of wanted image (-1 for all channels)
* @param canvasView
* render with canvas view if true else use default sequence dimension
*/
public abstract BufferedImage getRenderedImage(int t, int z, int c, boolean canvasView);
/**
* @deprecated Use {@link #getRenderedImage(int, int, int, boolean)} instead.
*/
@Deprecated
public BufferedImage getRenderedImage(int t, int z, int c)
{
return getRenderedImage(t, z, c, true);
}
/**
* Return a sequence which contains rendered images.<br>
* Default implementation, override it if needed in your canvas.
*
* @param canvasView
* render with canvas view if true else use default sequence dimension
* @param progressListener
* progress listener which receive notifications about progression
*/
public Sequence getRenderedSequence(boolean canvasView, ProgressListener progressListener)
{
final Sequence seqIn = getSequence();
// create output sequence
final Sequence result = new Sequence();
if (seqIn != null)
{
// derive original metadata
result.setMetaData(OMEUtil.createOMEMetadata(seqIn.getMetadata()));
int t = getPositionT();
int z = getPositionZ();
int c = getPositionC();
final int sizeT = getImageSizeT();
final int sizeZ = getImageSizeZ();
final int sizeC = getImageSizeC();
int pos = 0;
int len = 1;
if (t != -1)
len *= sizeT;
if (z != -1)
len *= sizeZ;
if (c != -1)
len *= sizeC;
result.beginUpdate();
// This cause position changed event to not be sent during rendering.
// Painters have to take care of that, they should check the canvas position
// in the paint() method
beginUpdate();
try
{
if (t != -1)
{
for (t = 0; t < sizeT; t++)
{
if (z != -1)
{
for (z = 0; z < sizeZ; z++)
{
if (c != -1)
{
final List<BufferedImage> images = new ArrayList<BufferedImage>();
for (c = 0; c < sizeC; c++)
{
images.add(getRenderedImage(t, z, c, canvasView));
pos++;
if (progressListener != null)
progressListener.notifyProgress(pos, len);
}
result.setImage(t, z, IcyBufferedImage.createFrom(images));
}
else
{
result.setImage(t, z, getRenderedImage(t, z, -1, canvasView));
pos++;
if (progressListener != null)
progressListener.notifyProgress(pos, len);
}
}
}
else
{
result.setImage(t, 0, getRenderedImage(t, -1, -1, canvasView));
pos++;
if (progressListener != null)
progressListener.notifyProgress(pos, len);
}
}
}
else
{
if (z != -1)
{
for (z = 0; z < sizeZ; z++)
{
if (c != -1)
{
final ArrayList<BufferedImage> images = new ArrayList<BufferedImage>();
for (c = 0; c < sizeC; c++)
{
images.add(getRenderedImage(-1, z, c, canvasView));
pos++;
if (progressListener != null)
progressListener.notifyProgress(pos, len);
}
result.setImage(0, z, IcyBufferedImage.createFrom(images));
}
else
{
result.setImage(0, z, getRenderedImage(-1, z, -1, canvasView));
pos++;
if (progressListener != null)
progressListener.notifyProgress(pos, len);
}
}
}
else
{
if (c != -1)
{
final ArrayList<BufferedImage> images = new ArrayList<BufferedImage>();
for (c = 0; c < sizeC; c++)
{
images.add(getRenderedImage(-1, -1, c, canvasView));
pos++;
if (progressListener != null)
progressListener.notifyProgress(pos, len);
}
result.setImage(0, 0, IcyBufferedImage.createFrom(images));
}
else
{
result.setImage(0, 0, getRenderedImage(-1, -1, -1, canvasView));
pos++;
if (progressListener != null)
progressListener.notifyProgress(pos, len);
}
}
}
}
finally
{
endUpdate();
result.endUpdate();
}
}
return result;
}
/**
* @deprecated Use {@link #getRenderedSequence(boolean, ProgressListener)} instead.
*/
@Deprecated
public Sequence getRenderedSequence(boolean canvasView)
{
return getRenderedSequence(canvasView, null);
}
/**
* @deprecated Use {@link #getRenderedSequence(boolean, ProgressListener)} instead.
*/
@Deprecated
public Sequence getRenderedSequence()
{
return getRenderedSequence(true, null);
}
/**
* Return the number of "selected" samples
*/
public int getNumSelectedSamples()
{
final Sequence sequence = getSequence();
// have to test this as we release sequence reference on closed
if (sequence == null)
return 0;
final int base_len = getImageSizeX() * getImageSizeY() * getImageSizeC();
if (getPositionT() == -1)
{
if (getPositionZ() == -1)
return base_len * getImageSizeZ() * getImageSizeT();
return base_len * getImageSizeT();
}
if (getPositionZ() == -1)
return base_len * getImageSizeZ();
return base_len;
}
/**
* Returns the frame rate (given in frame per second) for play command (T navigation panel).
*/
public int getFrameRate()
{
return tNav.getFrameRate();
}
/**
* Sets the frame rate (given in frame per second) for play command (T navigation panel).
*/
public void setFrameRate(int fps)
{
tNav.setFrameRate(fps);
}
/**
* update Z slider state
*/
protected void updateZNav()
{
final int maxZ = getMaxPositionZ();
final int z = getPositionZ();
zNav.setMaximum(maxZ);
if (z != -1)
{
zNav.setValue(z);
zNav.setVisible(maxZ > 0);
}
else
zNav.setVisible(false);
}
/**
* update T slider state
*/
protected void updateTNav()
{
final int maxT = getMaxPositionT();
final int t = getPositionT();
tNav.setMaximum(maxT);
if (t != -1)
{
tNav.setValue(t);
tNav.setVisible(maxT > 0);
}
else
tNav.setVisible(false);
}
/**
* @deprecated Use {@link #getLayer(Overlay)} instead.
*/
@Deprecated
public Layer getLayer(Painter painter)
{
for (Layer layer : getLayers(false))
if (layer.getPainter() == painter)
return layer;
return null;
}
/**
* Find the layer corresponding to the specified Overlay
*/
public Layer getLayer(Overlay overlay)
{
return layers.get(overlay);
}
/**
* Find the layer corresponding to the specified ROI (use the ROI overlay internally).
*/
public Layer getLayer(ROI roi)
{
return getLayer(roi.getOverlay());
}
/**
* @deprecated Use {@link #hasLayer(Overlay)} instead.
*/
@Deprecated
public boolean hasLayer(Painter painter)
{
return getLayer(painter) != null;
}
/**
* Returns true if the canvas contains a layer for the specified {@link Overlay}.
*/
public boolean hasLayer(Overlay overlay)
{
synchronized (layers)
{
return layers.containsKey(overlay);
}
}
public boolean hasLayer(Layer layer)
{
synchronized (layers)
{
return layers.containsValue(layer);
}
}
/**
* @deprecated Use {@link #addLayer(Overlay)} instead.
*/
@Deprecated
public void addLayer(Painter painter)
{
if (!hasLayer(painter))
addLayer(new Layer(painter));
}
public Layer addLayer(Overlay overlay)
{
if (!hasLayer(overlay))
return addLayer(new Layer(overlay));
return null;
}
protected Layer addLayer(Layer layer)
{
if (layer != null)
{
// listen layer
layer.addListener(this);
// add to list
synchronized (layers)
{
layers.put(layer.getOverlay(), layer);
if (Layer.DEFAULT_NAME.equals(layer))
layer.setName("layer " + layers.size());
}
// added
layerAdded(layer);
}
return layer;
}
/**
* @deprecated Use {@link #removeLayer(Overlay)} instead.
*/
@Deprecated
public void removeLayer(Painter painter)
{
removeLayer(getLayer(painter));
}
/**
* Remove the layer for the specified {@link Overlay} from the canvas.<br/>
* Returns <code>true</code> if the method succeed.
*/
public boolean removeLayer(Overlay overlay)
{
final Layer layer;
// remove from list
synchronized (layers)
{
layer = layers.remove(overlay);
}
if (layer != null)
{
// stop listening layer
layer.removeListener(this);
// notify remove
layerRemoved(layer);
return true;
}
return false;
}
/**
* Remove the specified layer from the canvas.
*/
public void removeLayer(Layer layer)
{
removeLayer(layer.getOverlay());
}
/**
* @deprecated Use {@link #addLayerListener(CanvasLayerListener)} instead.
*/
@Deprecated
public void addLayersListener(CanvasLayerListener listener)
{
addLayerListener(listener);
}
/**
* @deprecated Use {@link #removeLayerListener(CanvasLayerListener)} instead.
*/
@Deprecated
public void removeLayersListener(CanvasLayerListener listener)
{
removeLayerListener(listener);
}
/**
* Add a layer listener
*
* @param listener
*/
public void addLayerListener(CanvasLayerListener listener)
{
listenerList.add(CanvasLayerListener.class, listener);
}
/**
* Remove a layer listener
*
* @param listener
*/
public void removeLayerListener(CanvasLayerListener listener)
{
listenerList.remove(CanvasLayerListener.class, listener);
}
protected void fireLayerChangedEvent(CanvasLayerEvent event)
{
for (CanvasLayerListener listener : getListeners(CanvasLayerListener.class))
listener.canvasLayerChanged(event);
}
/**
* Add a IcyCanvas listener
*
* @param listener
*/
public void addCanvasListener(IcyCanvasListener listener)
{
listenerList.add(IcyCanvasListener.class, listener);
}
/**
* Remove a IcyCanvas listener
*
* @param listener
*/
public void removeCanvasListener(IcyCanvasListener listener)
{
listenerList.remove(IcyCanvasListener.class, listener);
}
protected void fireCanvasChangedEvent(IcyCanvasEvent event)
{
for (IcyCanvasListener listener : getListeners(IcyCanvasListener.class))
listener.canvasChanged(event);
}
public void beginUpdate()
{
updater.beginUpdate();
}
public void endUpdate()
{
updater.endUpdate();
}
public boolean isUpdating()
{
return updater.isUpdating();
}
/**
* layer added
*
* @param layer
*/
protected void layerAdded(Layer layer)
{
// handle with updater
updater.changed(new CanvasLayerEvent(layer, LayersEventType.ADDED));
}
/**
* layer removed
*
* @param layer
*/
protected void layerRemoved(Layer layer)
{
// handle with updater
updater.changed(new CanvasLayerEvent(layer, LayersEventType.REMOVED));
}
/**
* layer has changed
*/
@Override
public void layerChanged(Layer layer, String propertyName)
{
// handle with updater
updater.changed(new CanvasLayerEvent(layer, LayersEventType.CHANGED, propertyName));
}
/**
* canvas changed (packed event).<br>
* do global changes processing here
*/
public void changed(IcyCanvasEvent event)
{
final IcyCanvasEventType eventType = event.getType();
// handle synchronized canvas
if (isSynchronized())
{
final List<IcyCanvas> synchCanvasList = getSynchronizedCanvas();
// this is the synchronizer master so dispatch view changes to others canvas
if (getSynchMaster(synchCanvasList))
{
try
{
// synchronize all events when the view has just been synchronized
final boolean synchAll = (eventType == IcyCanvasEventType.SYNC_CHANGED);
synchronizeCanvas(synchCanvasList, event, synchAll);
}
finally
{
releaseSynchMaster();
}
}
}
switch (eventType)
{
case POSITION_CHANGED:
final int curZ = getPositionZ();
final int curT = getPositionT();
final int curC = getPositionC();
switch (event.getDim())
{
case Z:
// ensure Z slider position
if (curZ != -1)
zNav.setValue(curZ);
break;
case T:
// ensure T slider position
if (curT != -1)
tNav.setValue(curT);
break;
case C:
// single channel mode
final int maxC = getMaxPositionC();
// disabled others channels
for (int c = 0; c <= maxC; c++)
getLut().getLutChannel(c).setEnabled((curC == -1) || (curC == c));
break;
case NULL:
// ensure Z slider position
if (curZ != -1)
zNav.setValue(curZ);
// ensure T slider position
if (curT != -1)
tNav.setValue(curT);
break;
}
// refresh mouse panel informations
mouseInfPanel.updateInfos(this);
break;
case MOUSE_IMAGE_POSITION_CHANGED:
// refresh mouse panel informations
mouseInfPanel.updateInfos(this);
break;
}
// notify listeners that canvas have changed
fireCanvasChangedEvent(event);
}
/**
* layer property has changed (packed event)
*/
protected void layerChanged(CanvasLayerEvent event)
{
final String property = event.getProperty();
// we need to rebuild sorted layer list
if ((event.getType() != LayersEventType.CHANGED) || (property == null) || (property == Layer.PROPERTY_PRIORITY))
orderedLayersOutdated = true;
// notify listeners that layers have changed
fireLayerChangedEvent(event);
}
/**
* position has changed<br>
*
* @param dim
* define the position which has changed
*/
protected void positionChanged(DimensionId dim)
{
// handle with updater
updater.changed(new IcyCanvasEvent(this, IcyCanvasEventType.POSITION_CHANGED, dim));
}
@Override
public void lutChanged(LUTEvent event)
{
final int curC = getPositionC();
// single channel mode ?
if (curC != -1)
{
final int channel = event.getComponent();
// channel is enabled --> change C position
if ((channel != -1) && getLut().getLutChannel(channel).isEnabled())
setPositionC(channel);
else
// ensure we have 1 channel enable
getLut().getLutChannel(curC).setEnabled(true);
}
lutChanged(event.getComponent());
}
/**
* lut changed
*
* @param component
*/
protected void lutChanged(int component)
{
}
/**
* sequence meta data has changed
*/
protected void sequenceMetaChanged(String metadataName)
{
}
/**
* sequence type has changed
*/
protected void sequenceTypeChanged()
{
}
/**
* sequence component bounds has changed
*
* @param colorModel
* @param component
*/
protected void sequenceComponentBoundsChanged(IcyColorModel colorModel, int component)
{
}
/**
* sequence component bounds has changed
*
* @param colorModel
* @param component
*/
protected void sequenceColorMapChanged(IcyColorModel colorModel, int component)
{
}
/**
* sequence data has changed
*
* @param image
* image which has changed (null if global data changed)
* @param type
* event type
*/
protected void sequenceDataChanged(IcyBufferedImage image, SequenceEventType type)
{
ThreadUtil.runSingle(guiUpdater);
}
/**
* @deprecated Use {@link #sequenceOverlayChanged(Overlay, SequenceEventType)} instead.
*/
@SuppressWarnings("unused")
@Deprecated
protected void sequencePainterChanged(Painter painter, SequenceEventType type)
{
// no more stuff here
}
/**
* Sequence overlay has changed
*
* @param overlay
* overlay which has changed (null if global overlay changed)
* @param type
* event type
*/
protected void sequenceOverlayChanged(Overlay overlay, SequenceEventType type)
{
final Sequence sequence = getSequence();
switch (type)
{
case ADDED:
// handle special case of multiple adds
if (overlay == null)
{
if (sequence != null)
{
final Set<Overlay> overlays = getOverlays();
beginUpdate();
try
{
// add layers which are present in sequence and not in canvas
for (Overlay seqOverlay : sequence.getOverlaySet())
if (!overlays.contains(seqOverlay))
addLayer(seqOverlay);
}
finally
{
endUpdate();
}
}
}
else
addLayer(overlay);
break;
case REMOVED:
// handle special case of multiple removes
if (overlay == null)
{
if (sequence != null)
{
final Set<Overlay> seqOverlays = sequence.getOverlaySet();
beginUpdate();
try
{
// remove layers which are not anymore present in sequence
for (Overlay o : getOverlays())
if ((o != imageOverlay) && !seqOverlays.contains(o))
removeLayer(o);
}
finally
{
endUpdate();
}
}
}
else
removeLayer(overlay);
break;
case CHANGED:
// handle special case of multiple removes or/and adds
if (overlay == null)
{
if (sequence != null)
{
final Set<Overlay> overlays = getOverlays();
final Set<Overlay> seqOverlays = sequence.getOverlaySet();
beginUpdate();
try
{
// remove layers which are not anymore present in sequence
for (Overlay o : getOverlays())
if ((o != imageOverlay) && !seqOverlays.contains(o))
removeLayer(o);
// add layers which are present in sequence and not in canvas
for (Overlay seqOverlay : seqOverlays)
if (!overlays.contains(seqOverlay))
addLayer(seqOverlay);
}
finally
{
endUpdate();
}
}
}
break;
}
}
/**
* sequence roi has changed
*
* @param roi
* roi which has changed (null if global roi changed)
* @param type
* event type
*/
protected void sequenceROIChanged(ROI roi, SequenceEventType type)
{
// nothing here
}
@Override
public void viewerChanged(ViewerEvent event)
{
switch (event.getType())
{
case POSITION_CHANGED:
// ignore this event as we are launching it
break;
case LUT_CHANGED:
// set new lut
setLut(viewer.getLut(), true);
break;
case CANVAS_CHANGED:
// nothing to do
break;
}
}
@Override
public void viewerClosed(Viewer viewer)
{
// nothing to do here
}
@Override
public final void sequenceChanged(SequenceEvent event)
{
switch (event.getSourceType())
{
case SEQUENCE_META:
sequenceMetaChanged((String) event.getSource());
break;
case SEQUENCE_TYPE:
sequenceTypeChanged();
break;
case SEQUENCE_COMPONENTBOUNDS:
sequenceComponentBoundsChanged((IcyColorModel) event.getSource(), event.getParam());
break;
case SEQUENCE_COLORMAP:
sequenceColorMapChanged((IcyColorModel) event.getSource(), event.getParam());
break;
case SEQUENCE_DATA:
sequenceDataChanged((IcyBufferedImage) event.getSource(), event.getType());
break;
case SEQUENCE_OVERLAY:
final Overlay overlay = (Overlay) event.getSource();
sequenceOverlayChanged(overlay, event.getType());
// backward compatibility
@SuppressWarnings("deprecation")
final Painter painter;
if (overlay instanceof OverlayWrapper)
painter = ((OverlayWrapper) overlay).getPainter();
else
painter = overlay;
sequencePainterChanged(painter, event.getType());
break;
case SEQUENCE_ROI:
sequenceROIChanged((ROI) event.getSource(), event.getType());
break;
}
}
@Override
public void sequenceClosed(Sequence sequence)
{
// nothing to do here
}
@Override
public void onChanged(EventHierarchicalChecker event)
{
if (event instanceof CanvasLayerEvent)
layerChanged((CanvasLayerEvent) event);
if (event instanceof IcyCanvasEvent)
changed((IcyCanvasEvent) event);
}
}
diff --git a/icy/gui/component/math/HistogramPanel.java b/icy/gui/component/math/HistogramPanel.java
index 3b34dc5..7f033b1 100644
--- a/icy/gui/component/math/HistogramPanel.java
+++ b/icy/gui/component/math/HistogramPanel.java
@@ -1,638 +1,638 @@
/*
* Copyright 2010-2013 Institut Pasteur.
*
* This file is part of Icy.
*
* Icy 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.
*
* Icy 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 Icy. If not, see <http://www.gnu.org/licenses/>.
*/
package icy.gui.component.math;
import icy.gui.component.BorderedPanel;
import icy.math.ArrayMath;
import icy.math.Histogram;
import icy.math.MathUtil;
import icy.type.collection.array.Array1DUtil;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.EventListener;
import javax.swing.BorderFactory;
/**
* @author Stephane
*/
public class HistogramPanel extends BorderedPanel
{
public static interface HistogramPanelListener extends EventListener
{
/**
* histogram need to be refreshed (send values for recalculation)
*/
public void histogramNeedRefresh(HistogramPanel source);
}
/**
*
*/
private static final long serialVersionUID = -3932807727576675217L;
protected static final int BORDER_WIDTH = 2;
protected static final int BORDER_HEIGHT = 2;
protected static final int MIN_SIZE = 16;
/**
* internal histogram
*/
Histogram histogram;
/**
* histogram data cache
*/
private double[] histogramData;
/**
* histogram properties
*/
double minValue;
double maxValue;
boolean integer;
/**
* display properties
*/
boolean logScaling;
boolean useLAFColors;
Color color;
Color backgroundColor;
/**
* internals
*/
boolean updating;
/**
* Create a new histogram panel for the specified value range.<br>
* By default it uses a Logarithm representation (modifiable via {@link #setLogScaling(boolean)}
*
* @param minValue
* @param maxValue
* @param integer
*/
public HistogramPanel(double minValue, double maxValue, boolean integer)
{
super();
setBorder(BorderFactory.createEmptyBorder(BORDER_HEIGHT, BORDER_WIDTH, BORDER_HEIGHT, BORDER_WIDTH));
setMinimumSize(new Dimension(100, 100));
setMaximumSize(new Dimension(Short.MAX_VALUE, Short.MAX_VALUE));
histogram = new Histogram(0d, 1d, 1, true);
histogramData = new double[0];
this.minValue = minValue;
this.maxValue = maxValue;
this.integer = integer;
logScaling = true;
useLAFColors = true;
// default drawing color
color = Color.white;
backgroundColor = Color.darkGray;
buildHistogram(minValue, maxValue, integer);
updating = false;
}
/**
* Returns true when histogram is being calculated.
*/
public boolean isUpdating()
{
return updating;
}
/**
* Call this method to inform you start histogram computation (allow the panel to display
* "computing" message).</br>
* You need to call {@link #done()} when computation is done.
*
* @see #done()
*/
public void reset()
{
histogram.reset();
// start histogram calculation
updating = true;
}
/**
* @deprecated Use <code>getHistogram.addValue(double)</code> instead.
*/
@Deprecated
public void addValue(double value)
{
histogram.addValue(value);
}
/**
* @deprecated Use <code>getHistogram.addValue(Object, boolean signed)</code> instead.
*/
@Deprecated
public void addValues(Object array, boolean signed)
{
histogram.addValues(array, signed);
}
/**
* @deprecated Use <code>getHistogram.addValue(byte[])</code> instead.
*/
@Deprecated
public void addValues(byte[] array, boolean signed)
{
histogram.addValues(array, signed);
}
/**
* @deprecated Use <code>getHistogram.addValue(short[])</code> instead.
*/
@Deprecated
public void addValues(short[] array, boolean signed)
{
histogram.addValues(array, signed);
}
/**
* @deprecated Use <code>getHistogram.addValue(int[])</code> instead.
*/
@Deprecated
public void addValues(int[] array, boolean signed)
{
histogram.addValues(array, signed);
}
/**
* @deprecated Use <code>getHistogram.addValue(long[])</code> instead.
*/
@Deprecated
public void addValues(long[] array, boolean signed)
{
histogram.addValues(array, signed);
}
/**
* @deprecated Use <code>getHistogram.addValue(float[])</code> instead.
*/
@Deprecated
public void addValues(float[] array)
{
histogram.addValues(array);
}
/**
* @deprecated Use <code>getHistogram.addValue(double[])</code> instead.
*/
@Deprecated
public void addValues(double[] array)
{
histogram.addValues(array);
}
/**
* Returns the adjusted size (linear / log normalized) of the specified bin.
*
* @see #getBinSize(int)
*/
public double getAdjustedBinSize(int index)
{
// cache
final double[] data = histogramData;
- if (index < data.length)
+ if ((index >= 0) && (index < data.length))
return data[index];
return 0d;
}
/**
* Returns the size of the specified bin (number of element in the bin)
*
* @see icy.math.Histogram#getBinSize(int)
*/
public int getBinSize(int index)
{
return histogram.getBinSize(index);
}
/**
* @see icy.math.Histogram#getBinNumber()
*/
public int getBinNumber()
{
return histogram.getBinNumber();
}
/**
* @see icy.math.Histogram#getBinWidth()
*/
public double getBinWidth()
{
return histogram.getBinWidth();
}
/**
* @see icy.math.Histogram#getBins()
*/
public int[] getBins()
{
return histogram.getBins();
}
/**
* Invoke this method when the histogram calculation has been completed to refresh data cache.
*/
public void done()
{
refreshDataCache();
// end histogram calculation
updating = false;
}
/**
* Returns the minimum allowed value of the histogram.
*/
public double getMinValue()
{
return histogram.getMinValue();
}
/**
* Returns the maximum allowed value of the histogram.
*/
public double getMaxValue()
{
return histogram.getMaxValue();
}
/**
* Returns true if the input value are integer values only.<br>
* This is used to adapt the bin number of histogram..
*/
public boolean isIntegerType()
{
return histogram.isIntegerType();
}
/**
* Returns true if histogram is displayed with LOG scaling
*/
public boolean getLogScaling()
{
return logScaling;
}
/**
* Returns true if histogram use LAF color scheme.
*
* @see #getColor()
* @see #getBackgroundColor()
*/
public boolean getUseLAFColors()
{
return useLAFColors;
}
/**
* Returns the drawing color
*/
public Color getColor()
{
return color;
}
/**
* Returns the background color
*/
public Color getBackgroundColor()
{
return color;
}
/**
* Get histogram object
*/
public Histogram getHistogram()
{
return histogram;
}
/**
* Get computed histogram data
*/
public double[] getHistogramData()
{
return histogramData;
}
/**
* Set minimum, maximum and integer values at once
*/
public void setMinMaxIntValues(double min, double max, boolean intType)
{
// test with cached value first
if ((minValue != min) || (maxValue != max) || (integer != intType))
buildHistogram(min, max, intType);
// then test with uncached value (histo being updated)
else if ((histogram.getMinValue() != min) || (histogram.getMaxValue() != max)
|| (histogram.isIntegerType() != intType))
buildHistogram(min, max, intType);
}
/**
* Set to true to display histogram with LOG scaling (else it uses linear scaling).
*/
public void setLogScaling(boolean value)
{
if (logScaling != value)
{
logScaling = value;
refreshDataCache();
}
}
/**
* Set to true to use LAF color scheme.
*
* @see #setColor(Color)
* @see #setBackgroundColor(Color)
*/
public void setUseLAFColors(boolean value)
{
if (useLAFColors != value)
{
useLAFColors = value;
repaint();
}
}
/**
* Set the drawing color
*/
public void setColor(Color value)
{
if (!color.equals(value))
{
color = value;
if (!useLAFColors)
repaint();
}
}
/**
* Set the background color
*/
public void setBackgroundColor(Color value)
{
if (!backgroundColor.equals(value))
{
backgroundColor = value;
if (!useLAFColors)
repaint();
}
}
protected void checkHisto()
{
// create temporary histogram
final Histogram newHisto = new Histogram(histogram.getMinValue(), histogram.getMaxValue(), Math.max(
getClientWidth(), MIN_SIZE), histogram.isIntegerType());
// histogram properties changed ?
if (!hasSameProperties(newHisto))
{
// set new histogram
histogram = newHisto;
// notify listeners so they can fill it
fireHistogramNeedRefresh();
}
}
protected void buildHistogram(double min, double max, boolean intType)
{
// create temporary histogram
final Histogram newHisto = new Histogram(min, max, Math.max(getClientWidth(), MIN_SIZE), intType);
// histogram properties changed ?
if (!hasSameProperties(newHisto))
{
// set new histogram
histogram = newHisto;
// notify listeners so they can fill it
fireHistogramNeedRefresh();
}
}
/**
* Return true if specified histogram has same bounds and number of bin than current one
*/
protected boolean hasSameProperties(Histogram h)
{
return (histogram.getBinNumber() == h.getBinNumber()) && (histogram.getMinValue() == h.getMinValue())
&& (histogram.getMaxValue() == h.getMaxValue()) && (histogram.isIntegerType() == h.isIntegerType());
}
/**
* update histogram data cache
*/
protected void refreshDataCache()
{
// get histogram data
final double[] newHistogramData = Array1DUtil.intArrayToDoubleArray(histogram.getBins(), false);
// we want all values to >= 1
final double min = ArrayMath.min(newHistogramData);
MathUtil.add(newHistogramData, min + 1f);
// log
if (logScaling)
MathUtil.log(newHistogramData);
// normalize data
MathUtil.normalize(newHistogramData);
// get new data cache and apply min, max, integer type
histogramData = newHistogramData;
minValue = getMinValue();
maxValue = getMaxValue();
integer = isIntegerType();
// request repaint
repaint();
}
/**
* Returns the ratio to convert a data value to corresponding pixel X position
*/
protected double getDataToPixelRatio()
{
final double pixelRange = Math.max(getClientWidth() - 1, 32);
final double dataRange = maxValue - minValue;
if (dataRange != 0d)
return pixelRange / dataRange;
return 0d;
}
/**
* Returns the ratio to convert a pixel X position to corresponding data value
*/
protected double getPixelToDataRatio()
{
final double pixelRange = Math.max(getClientWidth() - 1, 32);
final double dataRange = maxValue - minValue;
if (pixelRange != 0d)
return dataRange / pixelRange;
return 0d;
}
/**
* Returns the ratio to convert a pixel X position to corresponding histo bin
*/
protected double getPixelToHistoRatio()
{
final double histogramRange = histogramData.length - 1;
final double pixelRange = Math.max(getClientWidth() - 1, 32);
if (pixelRange != 0d)
return histogramRange / pixelRange;
return 0d;
}
/**
* Convert a data value to the corresponding pixel position
*/
public int dataToPixel(double value)
{
return (int) Math.round(((value - minValue) * getDataToPixelRatio())) + getClientX();
}
/**
* Convert a pixel position to corresponding data value
*/
public double pixelToData(int value)
{
final double data = ((value - getClientX()) * getPixelToDataRatio()) + minValue;
return Math.min(Math.max(data, minValue), maxValue);
}
/**
* Convert a pixel position to corresponding bin index
*/
public int pixelToBin(int value)
{
final int index = (int) Math.round((value - getClientX()) * getPixelToHistoRatio());
return Math.min(Math.max(index, 0), histogramData.length - 1);
}
/**
* Notify all listeners that histogram need to be recomputed
*/
protected void fireHistogramNeedRefresh()
{
for (HistogramPanelListener l : listenerList.getListeners(HistogramPanelListener.class))
l.histogramNeedRefresh(this);
}
public void addListener(HistogramPanelListener l)
{
listenerList.add(HistogramPanelListener.class, l);
}
public void removeListener(HistogramPanelListener l)
{
listenerList.remove(HistogramPanelListener.class, l);
}
@Override
protected void paintComponent(Graphics g)
{
final Color fc;
final Color bc;
if (useLAFColors)
{
fc = getForeground();
bc = getBackground();
}
else
{
fc = color;
bc = backgroundColor;
}
final Graphics2D g2 = (Graphics2D) g.create();
g2.setColor(fc);
g2.setBackground(bc);
// background color
if (isOpaque())
g2.clearRect(0, 0, getWidth(), getHeight());
// data cache
final double ratio = getPixelToHistoRatio();
final double[] data = histogramData;
// not yet computed
if (data.length != 0)
{
final int histoRange = data.length - 1;
final int hRange = getClientHeight() - 1;
final int bottom = getClientY() + hRange;
final int l = getClientX();
final int r = l + getClientWidth();
for (int i = l; i < r; i++)
{
int index = (int) Math.round((i - l) * ratio);
if (index < 0)
index = 0;
else if (index > histoRange)
index = histoRange;
g2.drawLine(i, bottom, i, bottom - (int) Math.round(data[index] * hRange));
}
}
if ((data.length == 0) || updating)
{
final int x = (getWidth() / 2) - 60;
final int y = (getHeight() / 2) - 20;
g2.drawString("computing...", x, y);
}
g2.dispose();
// just check for histogram properties change
checkHisto();
}
}
diff --git a/icy/gui/viewer/Viewer.java b/icy/gui/viewer/Viewer.java
index 53ac7bf..9d9286c 100644
--- a/icy/gui/viewer/Viewer.java
+++ b/icy/gui/viewer/Viewer.java
@@ -1,1432 +1,1432 @@
/*
* Copyright 2010-2013 Institut Pasteur.
*
* This file is part of Icy.
*
* Icy 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.
*
* Icy 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 Icy. If not, see <http://www.gnu.org/licenses/>.
*/
package icy.gui.viewer;
import icy.action.CanvasActions;
import icy.action.CanvasActions.ToggleLayersAction;
import icy.action.ViewerActions;
import icy.action.WindowActions;
import icy.canvas.IcyCanvas;
import icy.canvas.IcyCanvas2D;
import icy.canvas.IcyCanvasEvent;
import icy.canvas.IcyCanvasListener;
import icy.common.MenuCallback;
import icy.common.listener.ProgressListener;
import icy.gui.component.button.IcyButton;
import icy.gui.component.button.IcyToggleButton;
import icy.gui.component.renderer.LabelComboBoxRenderer;
import icy.gui.dialog.MessageDialog;
import icy.gui.frame.IcyFrame;
import icy.gui.frame.IcyFrameAdapter;
import icy.gui.frame.IcyFrameEvent;
import icy.gui.lut.LUTViewer;
import icy.gui.lut.abstract_.IcyLutViewer;
import icy.gui.plugin.PluginComboBoxRenderer;
import icy.gui.util.ComponentUtil;
import icy.gui.viewer.ViewerEvent.ViewerEventType;
import icy.image.IcyBufferedImage;
import icy.image.lut.LUT;
import icy.imagej.ImageJWrapper;
import icy.main.Icy;
import icy.plugin.PluginLoader;
import icy.plugin.PluginLoader.PluginLoaderEvent;
import icy.plugin.PluginLoader.PluginLoaderListener;
import icy.plugin.interface_.PluginCanvas;
import icy.sequence.DimensionId;
import icy.sequence.Sequence;
import icy.sequence.SequenceEvent;
import icy.sequence.SequenceListener;
import icy.system.thread.ThreadUtil;
import icy.util.Random;
import icy.util.StringUtil;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.KeyboardFocusManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.util.ArrayList;
import javax.swing.ActionMap;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.InputMap;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.event.EventListenerList;
/**
* Viewer send an event if the IcyCanvas change.
*
* @author Fabrice de Chaumont & Stephane
*/
public class Viewer extends IcyFrame implements KeyListener, SequenceListener, IcyCanvasListener, PluginLoaderListener
{
/**
* associated LUT
*/
private LUT lut;
/**
* associated canvas
*/
IcyCanvas canvas;
/**
* associated sequence
*/
Sequence sequence;
/***/
private final EventListenerList listeners = new EventListenerList();
/**
* GUI
*/
private JToolBar toolBar;
private JPanel mainPanel;
private LUTViewer lutViewer;
JComboBox canvasComboBox;
JComboBox lockComboBox;
IcyToggleButton layersEnabledButton;
IcyButton screenShotButton;
IcyButton screenShotAlternateButton;
IcyButton duplicateButton;
IcyButton switchStateButton;
/**
* internals
*/
boolean initialized;
final Runnable lutUpdater;
public Viewer(Sequence sequence, boolean visible)
{
super("Viewer", true, true, true, true);
if (sequence == null)
throw new IllegalArgumentException("Can't open a null sequence.");
this.sequence = sequence;
// default
canvas = null;
lut = null;
lutViewer = null;
initialized = false;
lutUpdater = new Runnable()
{
@Override
public void run()
{
// don't need to update that too much
ThreadUtil.sleep(1);
ThreadUtil.invokeNow(new Runnable()
{
@Override
public void run()
{
final LUT lut = getLut();
// closed --> ignore
if (lut != null)
{
// refresh LUT viewer
setLutViewer(new LUTViewer(Viewer.this, lut));
// notify
fireViewerChanged(ViewerEventType.LUT_CHANGED);
}
}
});
}
};
mainPanel = new JPanel();
// set menu directly in system menu so we don't need a extra MenuBar
setSystemMenuCallback(new MenuCallback()
{
@Override
public JMenu getMenu()
{
return Viewer.this.getMenu();
}
});
// build tool bar
buildToolBar();
mainPanel.setLayout(new BorderLayout());
// create a new compatible LUT
final LUT lut = sequence.createCompatibleLUT();
// restore user colormaps (without alpha)
lut.setColorMaps(sequence.getUserLUT(), false);
// set lut (this modify lutPanel)
setLut(lut);
// set default canvas to first available canvas plugin (Canvas2D should be first)
setCanvas(IcyCanvas.getCanvasPluginNames().get(0));
setLayout(new BorderLayout());
add(toolBar, BorderLayout.NORTH);
add(mainPanel, BorderLayout.CENTER);
// setting frame
refreshViewerTitle();
setFocusable(true);
// set position depending window mode
setLocationInternal(20 + Random.nextInt(100), 20 + Random.nextInt(60));
setLocationExternal(100 + Random.nextInt(200), 100 + Random.nextInt(150));
setSize(640, 480);
// initial position in sequence
if (sequence.isEmpty())
setPositionZ(0);
else
setPositionZ(((sequence.getSizeZ() + 1) / 2) - 1);
addFrameListener(new IcyFrameAdapter()
{
@Override
public void icyFrameOpened(IcyFrameEvent e)
{
if (!initialized)
{
if ((Viewer.this.sequence != null) && !Viewer.this.sequence.isEmpty())
{
adjustViewerToImageSize();
initialized = true;
}
}
}
@Override
public void icyFrameActivated(IcyFrameEvent e)
{
Icy.getMainInterface().setActiveViewer(Viewer.this);
// lost focus on ImageJ image
final ImageJWrapper ij = Icy.getMainInterface().getImageJ();
if (ij != null)
ij.setActiveImage(null);
}
@Override
public void icyFrameExternalized(IcyFrameEvent e)
{
refreshToolBar();
}
@Override
public void icyFrameInternalized(IcyFrameEvent e)
{
refreshToolBar();
}
});
addKeyListener(this);
sequence.addListener(this);
PluginLoader.addListener(this);
// do this when viewer is initialized
Icy.getMainInterface().registerViewer(this);
// automatically add it to the desktop pane
addToDesktopPane();
if (visible)
{
setVisible(true);
requestFocus();
}
else
setVisible(false);
// can be done after setVisible
buildActionMap();
}
public Viewer(Sequence sequence)
{
this(sequence, true);
}
void buildActionMap()
{
// global input map
buildActionMap(getInputMap(JComponent.WHEN_FOCUSED), getActionMap());
}
private void buildActionMap(InputMap imap, ActionMap amap)
{
imap.put(WindowActions.gridTileAction.getKeyStroke(), WindowActions.gridTileAction.getName());
imap.put(WindowActions.horizontalTileAction.getKeyStroke(), WindowActions.horizontalTileAction.getName());
imap.put(WindowActions.verticalTileAction.getKeyStroke(), WindowActions.verticalTileAction.getName());
imap.put(CanvasActions.globalDisableSyncAction.getKeyStroke(), CanvasActions.globalDisableSyncAction.getName());
imap.put(CanvasActions.globalSyncGroup1Action.getKeyStroke(), CanvasActions.globalSyncGroup1Action.getName());
imap.put(CanvasActions.globalSyncGroup2Action.getKeyStroke(), CanvasActions.globalSyncGroup2Action.getName());
imap.put(CanvasActions.globalSyncGroup3Action.getKeyStroke(), CanvasActions.globalSyncGroup3Action.getName());
imap.put(CanvasActions.globalSyncGroup4Action.getKeyStroke(), CanvasActions.globalSyncGroup4Action.getName());
amap.put(WindowActions.gridTileAction.getName(), WindowActions.gridTileAction);
amap.put(WindowActions.horizontalTileAction.getName(), WindowActions.horizontalTileAction);
amap.put(WindowActions.verticalTileAction.getName(), WindowActions.verticalTileAction);
amap.put(CanvasActions.globalDisableSyncAction.getName(), CanvasActions.globalDisableSyncAction);
amap.put(CanvasActions.globalSyncGroup1Action.getName(), CanvasActions.globalSyncGroup1Action);
amap.put(CanvasActions.globalSyncGroup2Action.getName(), CanvasActions.globalSyncGroup2Action);
amap.put(CanvasActions.globalSyncGroup3Action.getName(), CanvasActions.globalSyncGroup3Action);
amap.put(CanvasActions.globalSyncGroup4Action.getName(), CanvasActions.globalSyncGroup4Action);
}
/**
* Called when viewer is closed.<br>
* Free as much references we can here because of the
* <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4759312">
* JInternalFrame bug</a>.
*/
@Override
public void onClosed()
{
// notify close
fireViewerClosed();
// remove listeners
sequence.removeListener(this);
if (canvas != null)
canvas.removeCanvasListener(this);
PluginLoader.removeListener(this);
icy.main.Icy.getMainInterface().unRegisterViewer(this);
// AWT JDesktopPane keep reference on last closed JInternalFrame
// it's good to free as much reference we can here
- canvas.shutDown();
-
+ if (canvas != null)
+ canvas.shutDown();
if (lutViewer != null)
lutViewer.dispose();
if (mainPanel != null)
mainPanel.removeAll();
if (toolBar != null)
toolBar.removeAll();
// remove all listeners for this viewer
ViewerListener[] vls = listeners.getListeners(ViewerListener.class);
for (ViewerListener vl : vls)
listeners.remove(ViewerListener.class, vl);
lutViewer = null;
mainPanel = null;
canvas = null;
sequence = null;
lut = null;
toolBar = null;
canvasComboBox = null;
lockComboBox = null;
duplicateButton = null;
layersEnabledButton = null;
screenShotAlternateButton = null;
screenShotButton = null;
switchStateButton = null;
super.onClosed();
}
void adjustViewerToImageSize()
{
if (canvas instanceof IcyCanvas2D)
{
final IcyCanvas2D cnv = (IcyCanvas2D) canvas;
final int ix = cnv.getImageSizeX();
final int iy = cnv.getImageSizeY();
if ((ix > 0) && (iy > 0))
{
// find scale factor to fit image in a 640x540 sized window
// and limit zoom to 100%
final double scale = Math.min(Math.min(640d / ix, 540d / iy), 1d);
cnv.setScaleX(scale);
cnv.setScaleY(scale);
// this actually resize viewer as canvas size depend from it
cnv.fitCanvasToImage();
}
}
// minimum size to start : 400, 240
final Dimension size = new Dimension(Math.max(getWidth(), 400), Math.max(getHeight(), 240));
// minimum size global : 200, 140
final Dimension minSize = new Dimension(200, 140);
// adjust size of both frames
setSizeExternal(size);
setSizeInternal(size);
setMinimumSizeInternal(minSize);
setMinimumSizeExternal(minSize);
}
/**
* Rebuild and return viewer menu
*/
JMenu getMenu()
{
final JMenu result = getDefaultSystemMenu();
final JMenuItem overlayItem = new JMenuItem(CanvasActions.toggleLayersAction);
if ((canvas != null) && canvas.isLayersVisible())
overlayItem.setText("Hide layers");
else
overlayItem.setText("Show layers");
final JMenuItem duplicateItem = new JMenuItem(ViewerActions.duplicateAction);
// set menu
result.insert(overlayItem, 0);
result.insertSeparator(1);
result.insert(duplicateItem, 2);
return result;
}
private void buildLockCombo()
{
final ArrayList<JLabel> labels = new ArrayList<JLabel>();
// get sync action labels
labels.add(CanvasActions.disableSyncAction.getLabelComponent(true, false));
labels.add(CanvasActions.syncGroup1Action.getLabelComponent(true, false));
labels.add(CanvasActions.syncGroup2Action.getLabelComponent(true, false));
labels.add(CanvasActions.syncGroup3Action.getLabelComponent(true, false));
labels.add(CanvasActions.syncGroup4Action.getLabelComponent(true, false));
// build comboBox with lock id
lockComboBox = new JComboBox(labels.toArray());
// set specific renderer
lockComboBox.setRenderer(new LabelComboBoxRenderer(lockComboBox));
// limit size
ComponentUtil.setFixedWidth(lockComboBox, 48);
lockComboBox.setToolTipText("Select synchronisation group");
// don't want focusable here
lockComboBox.setFocusable(false);
// needed because of VTK
lockComboBox.setLightWeightPopupEnabled(false);
// action on canvas change
lockComboBox.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
// adjust lock id
setViewSyncId(lockComboBox.getSelectedIndex());
}
});
}
void buildCanvasCombo()
{
// build comboBox with canvas plugins
canvasComboBox = new JComboBox(IcyCanvas.getCanvasPluginNames().toArray());
// specific renderer
canvasComboBox.setRenderer(new PluginComboBoxRenderer(canvasComboBox, false));
// limit size
ComponentUtil.setFixedWidth(canvasComboBox, 48);
canvasComboBox.setToolTipText("Select canvas type");
// don't want focusable here
canvasComboBox.setFocusable(false);
// needed because of VTK
canvasComboBox.setLightWeightPopupEnabled(false);
// action on canvas change
canvasComboBox.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
// set selected canvas
setCanvas((String) canvasComboBox.getSelectedItem());
}
});
}
/**
* build the toolBar
*/
private void buildToolBar()
{
// build combo box
buildLockCombo();
buildCanvasCombo();
// build buttons
layersEnabledButton = new IcyToggleButton(new ToggleLayersAction(true));
layersEnabledButton.setHideActionText(true);
layersEnabledButton.setFocusable(false);
layersEnabledButton.setSelected(true);
screenShotButton = new IcyButton(CanvasActions.screenShotAction);
screenShotButton.setFocusable(false);
screenShotButton.setHideActionText(true);
screenShotAlternateButton = new IcyButton(CanvasActions.screenShotAlternateAction);
screenShotAlternateButton.setFocusable(false);
screenShotAlternateButton.setHideActionText(true);
duplicateButton = new IcyButton(ViewerActions.duplicateAction);
duplicateButton.setFocusable(false);
duplicateButton.setHideActionText(true);
// duplicateButton.setToolTipText("Duplicate view (no data duplication)");
switchStateButton = new IcyButton(getSwitchStateAction());
switchStateButton.setFocusable(false);
switchStateButton.setHideActionText(true);
// and build the toolbar
toolBar = new JToolBar();
toolBar.setFloatable(false);
// so we don't have any border
toolBar.setBorder(BorderFactory.createEmptyBorder(1, 0, 1, 0));
ComponentUtil.setPreferredHeight(toolBar, 26);
updateToolbarComponents();
}
void updateToolbarComponents()
{
toolBar.removeAll();
toolBar.add(lockComboBox);
toolBar.addSeparator();
toolBar.add(canvasComboBox);
toolBar.addSeparator();
toolBar.add(layersEnabledButton);
if (canvas != null)
canvas.customizeToolbar(toolBar);
toolBar.add(Box.createHorizontalGlue());
toolBar.addSeparator();
toolBar.add(screenShotButton);
toolBar.add(screenShotAlternateButton);
toolBar.addSeparator();
toolBar.add(duplicateButton);
toolBar.add(switchStateButton);
}
void refreshLockCombo()
{
final int syncId = getViewSyncId();
lockComboBox.setEnabled(isSynchronizedViewSupported());
lockComboBox.setSelectedIndex(syncId);
switch (syncId)
{
case 0:
lockComboBox.setBackground(Color.gray);
lockComboBox.setToolTipText("Synchronization disabled");
break;
case 1:
lockComboBox.setBackground(Color.green);
lockComboBox.setToolTipText("Full synchronization group 1 (view and Z/T position)");
break;
case 2:
lockComboBox.setBackground(Color.yellow);
lockComboBox.setToolTipText("Full synchronization group 2 (view and Z/T position)");
break;
case 3:
lockComboBox.setBackground(Color.blue);
lockComboBox.setToolTipText("View synchronization group (view synched but not Z/T position)");
break;
case 4:
lockComboBox.setBackground(Color.red);
lockComboBox.setToolTipText("Slice synchronization group (Z/T position synched but not view)");
break;
}
}
void refreshCanvasCombo()
{
if (canvas != null)
{
// get plugin class name for this canvas
final String pluginName = IcyCanvas.getPluginClassName(canvas.getClass().getName());
if (pluginName != null)
{
// align canvas combo to plugin name
if (!canvasComboBox.getSelectedItem().equals(pluginName))
canvasComboBox.setSelectedItem(pluginName);
}
}
}
void refreshToolBar()
{
// FIXME : switchStateButton stay selected after action
final boolean layersVisible = (canvas != null) ? canvas.isLayersVisible() : false;
layersEnabledButton.setSelected(layersVisible);
if (layersVisible)
layersEnabledButton.setToolTipText("Hide layers");
else
layersEnabledButton.setToolTipText("Show layers");
// refresh combos
refreshLockCombo();
refreshCanvasCombo();
}
/**
* @return the sequence
*/
public Sequence getSequence()
{
return sequence;
}
/**
* Set the specified LUT for the viewer.
*/
public void setLut(LUT value)
{
if ((lut != value) && sequence.isLutCompatible(value))
{
// set new lut & notify change
lut = value;
lutChanged();
}
}
/**
* Returns the viewer LUT
*/
public LUT getLut()
{
// have to test this as we release sequence reference on closed
if (sequence == null)
return lut;
// sequence can be asynchronously modified so we have to test change on Getter
if ((lut == null) || !sequence.isLutCompatible(lut))
{
// sequence type has changed, we need to recreate a compatible LUT
final LUT newLut = sequence.getDefaultLUT();
// keep the color map of previous LUT if they have the same number of channels
if ((lut != null) && (lut.getNumChannel() == newLut.getNumChannel()))
newLut.getColorSpace().setColorMaps(lut.getColorSpace(), true);
// set the new lut
setLut(newLut);
}
return lut;
}
/**
* Set the specified canvas for the viewer (from the {@link PluginCanvas} class name).
*
* @see IcyCanvas#getCanvasPluginNames()
*/
public void setCanvas(String pluginClassName)
{
// not the same canvas ?
if ((canvas == null) || !canvas.getClass().getName().equals(IcyCanvas.getCanvasClassName(pluginClassName)))
{
final int saveX;
final int saveY;
final int saveZ;
final int saveT;
final int saveC;
if (canvas != null)
{
// save position
saveX = canvas.getPositionX();
saveY = canvas.getPositionY();
saveZ = canvas.getPositionZ();
saveT = canvas.getPositionT();
saveC = canvas.getPositionC();
canvas.removePropertyChangeListener(IcyCanvas.PROPERTY_LAYERS_VISIBLE, this);
canvas.removeCanvasListener(this);
canvas.shutDown();
// remove from mainPanel
mainPanel.remove(canvas);
}
else
saveX = saveY = saveZ = saveT = saveC = -1;
// set new canvas
canvas = IcyCanvas.create(pluginClassName, this);
if (canvas != null)
{
canvas.addCanvasListener(this);
canvas.addPropertyChangeListener(IcyCanvas.PROPERTY_LAYERS_VISIBLE, this);
// add to mainPanel
mainPanel.add(canvas, BorderLayout.CENTER);
// restore position
if (saveX != -1)
canvas.setPositionX(saveX);
if (saveY != -1)
canvas.setPositionY(saveY);
if (saveZ != -1)
canvas.setPositionZ(saveZ);
if (saveT != -1)
canvas.setPositionT(saveT);
if (saveC != -1)
canvas.setPositionC(saveC);
}
else
{
// new canvas not created ?
MessageDialog.showDialog("Cannot create Canvas from plugin " + pluginClassName + " !",
MessageDialog.ERROR_MESSAGE);
}
mainPanel.revalidate();
// refresh viewer menu (so overlay checkbox is correctly set)
updateSystemMenu();
updateToolbarComponents();
refreshToolBar();
// fix the OSX lost keyboard focus on canvas change in detached mode.
KeyboardFocusManager.getCurrentKeyboardFocusManager().upFocusCycle(getCanvas());
// notify canvas changed to listener
fireViewerChanged(ViewerEventType.CANVAS_CHANGED);
}
}
/**
* @deprecated Use {@link #setCanvas(String)} instead.
*/
@Deprecated
public void setCanvas(IcyCanvas value)
{
if (canvas == value)
return;
final int saveX;
final int saveY;
final int saveZ;
final int saveT;
final int saveC;
if (canvas != null)
{
// save position
saveX = canvas.getPositionX();
saveY = canvas.getPositionY();
saveZ = canvas.getPositionZ();
saveT = canvas.getPositionT();
saveC = canvas.getPositionC();
canvas.removePropertyChangeListener(IcyCanvas.PROPERTY_LAYERS_VISIBLE, this);
canvas.removeCanvasListener(this);
canvas.shutDown();
// remove from mainPanel
mainPanel.remove(canvas);
}
else
saveX = saveY = saveZ = saveT = saveC = -1;
// set new canvas
canvas = value;
if (canvas != null)
{
canvas.addCanvasListener(this);
canvas.addPropertyChangeListener(IcyCanvas.PROPERTY_LAYERS_VISIBLE, this);
// add to mainPanel
mainPanel.add(canvas, BorderLayout.CENTER);
// restore position
if (saveX != -1)
canvas.setPositionX(saveX);
if (saveY != -1)
canvas.setPositionY(saveY);
if (saveZ != -1)
canvas.setPositionZ(saveZ);
if (saveT != -1)
canvas.setPositionT(saveT);
if (saveC != -1)
canvas.setPositionC(saveC);
}
mainPanel.revalidate();
// refresh viewer menu (so overlay checkbox is correctly set)
updateSystemMenu();
updateToolbarComponents();
refreshToolBar();
// fix the OSX lost keyboard focus on canvas change in detached mode.
KeyboardFocusManager.getCurrentKeyboardFocusManager().upFocusCycle(getCanvas());
// notify canvas changed to listener
fireViewerChanged(ViewerEventType.CANVAS_CHANGED);
}
/**
* Returns true if the viewer initialization (correct image resizing) is completed.
*/
public boolean isInitialized()
{
return initialized;
}
/**
* Return the viewer Canvas object
*/
public IcyCanvas getCanvas()
{
return canvas;
}
/**
* Return the viewer Canvas panel
*/
public JPanel getCanvasPanel()
{
if (canvas != null)
return canvas.getPanel();
return null;
}
/**
* Return the viewer Lut panel
*/
public LUTViewer getLutViewer()
{
return lutViewer;
}
/**
* Set the {@link LUTViewer} for this viewer.
*/
public void setLutViewer(LUTViewer value)
{
if (lutViewer != value)
{
if (lutViewer != null)
lutViewer.dispose();
lutViewer = value;
}
}
/**
* @deprecated Use {@link #getLutViewer()} instead
*/
@Deprecated
public IcyLutViewer getLutPanel()
{
return getLutViewer();
}
/**
* @deprecated Use {@link #setLutViewer(LUTViewer)} instead.
*/
@Deprecated
public void setLutPanel(IcyLutViewer lutViewer)
{
setLutViewer((LUTViewer) lutViewer);
}
/**
* Return the viewer ToolBar object
*/
public JToolBar getToolBar()
{
return toolBar;
}
/**
* @return current T (-1 if all selected/displayed)
*/
public int getPositionT()
{
if (canvas != null)
return canvas.getPositionT();
return 0;
}
/**
* Set the current T position (for multi frame sequence).
*/
public void setPositionT(int t)
{
if (canvas != null)
canvas.setPositionT(t);
}
/**
* @return current Z (-1 if all selected/displayed)
*/
public int getPositionZ()
{
if (canvas != null)
return canvas.getPositionZ();
return 0;
}
/**
* Set the current Z position (for stack sequence).
*/
public void setPositionZ(int z)
{
if (canvas != null)
canvas.setPositionZ(z);
}
/**
* @return current C (-1 if all selected/displayed)
*/
public int getPositionC()
{
if (canvas != null)
return canvas.getPositionC();
return 0;
}
/**
* Set the current C (channel) position (multi channel sequence)
*/
public void setPositionC(int c)
{
if (canvas != null)
canvas.setPositionC(c);
}
/**
* @deprecated Use {@link #getPositionT()} instead.
*/
@Deprecated
public int getT()
{
return getPositionT();
}
/**
* @deprecated Use {@link #setPositionT(int)} instead.
*/
@Deprecated
public void setT(int t)
{
setPositionT(t);
}
/**
* @deprecated Use {@link #getPositionZ()} instead.
*/
@Deprecated
public int getZ()
{
return getPositionZ();
}
/**
* @deprecated Use {@link #setPositionZ(int)} instead.
*/
@Deprecated
public void setZ(int z)
{
setPositionZ(z);
}
/**
* @deprecated Use {@link #getPositionZ()} instead.
*/
@Deprecated
public int getC()
{
return getPositionC();
}
/**
* @deprecated Use {@link #setPositionZ(int)} instead.
*/
@Deprecated
public void setC(int c)
{
setPositionC(c);
}
/**
* Get maximum T value
*/
public int getMaxT()
{
if (canvas != null)
return canvas.getMaxPositionT();
return 0;
}
/**
* Get maximum Z value
*/
public int getMaxZ()
{
if (canvas != null)
return canvas.getMaxPositionZ();
return 0;
}
/**
* Get maximum C value
*/
public int getMaxC()
{
if (canvas != null)
return canvas.getMaxPositionC();
return 0;
}
/**
* return true if current canvas's viewer does support synchronized view
*/
public boolean isSynchronizedViewSupported()
{
if (canvas != null)
return canvas.isSynchronizationSupported();
return false;
}
/**
* @return the viewSyncId
*/
public int getViewSyncId()
{
if (canvas != null)
return canvas.getSyncId();
return -1;
}
/**
* Set the view synchronization group id (0 means unsynchronized).
*
* @param id
* the view synchronization id to set
* @see IcyCanvas#setSyncId(int)
*/
public boolean setViewSyncId(int id)
{
if (canvas != null)
return canvas.setSyncId(id);
return false;
}
/**
* Return true if this viewer has its view synchronized
*/
public boolean isViewSynchronized()
{
if (canvas != null)
return canvas.isSynchronized();
return false;
}
/**
* Delegation for {@link IcyCanvas#getImage(int, int, int)}
*/
public IcyBufferedImage getImage(int t, int z, int c)
{
if (canvas != null)
return canvas.getImage(t, z, c);
return null;
}
/**
* @deprecated Use {@link #getImage(int, int, int)} with C = -1 instead.
*/
@Deprecated
public IcyBufferedImage getImage(int t, int z)
{
return getImage(t, z, -1);
}
/**
* Get the current image
*
* @return current image
*/
public IcyBufferedImage getCurrentImage()
{
if (canvas != null)
return canvas.getCurrentImage();
return null;
}
/**
* Return the number of "selected" samples
*/
public int getNumSelectedSamples()
{
if (canvas != null)
return canvas.getNumSelectedSamples();
return 0;
}
/**
* @see icy.canvas.IcyCanvas#getRenderedImage(int, int, int, boolean)
*/
public BufferedImage getRenderedImage(int t, int z, int c, boolean canvasView)
{
if (canvas == null)
return null;
return canvas.getRenderedImage(t, z, c, canvasView);
}
/**
* @see icy.canvas.IcyCanvas#getRenderedSequence(boolean, icy.common.listener.ProgressListener)
*/
public Sequence getRenderedSequence(boolean canvasView, ProgressListener progressListener)
{
if (canvas == null)
return null;
return canvas.getRenderedSequence(canvasView, progressListener);
}
/**
* Returns the T navigation panel.
*/
protected TNavigationPanel getTNavigationPanel()
{
if (canvas == null)
return null;
return canvas.getTNavigationPanel();
}
/**
* Returns the frame rate (given in frame per second) for play command.
*/
public int getFrameRate()
{
final TNavigationPanel tNav = getTNavigationPanel();
if (tNav != null)
return tNav.getFrameRate();
return 0;
}
/**
* Sets the frame rate (given in frame per second) for play command.
*/
public void setFrameRate(int fps)
{
final TNavigationPanel tNav = getTNavigationPanel();
if (tNav != null)
tNav.setFrameRate(fps);
}
/**
* Returns true if <code>repeat</code> is enabled for play command.
*/
public boolean isRepeat()
{
final TNavigationPanel tNav = getTNavigationPanel();
if (tNav != null)
return tNav.isRepeat();
return false;
}
/**
* Set <code>repeat</code> mode for play command.
*/
public void setRepeat(boolean value)
{
final TNavigationPanel tNav = getTNavigationPanel();
if (tNav != null)
tNav.setRepeat(value);
}
/**
* Returns true if currently playing.
*/
public boolean isPlaying()
{
final TNavigationPanel tNav = getTNavigationPanel();
if (tNav != null)
return tNav.isPlaying();
return false;
}
/**
* Start sequence play.
*
* @see #stopPlay()
* @see #setRepeat(boolean)
*/
public void startPlay()
{
final TNavigationPanel tNav = getTNavigationPanel();
if (tNav != null)
tNav.startPlay();
}
/**
* Stop sequence play.
*
* @see #startPlay()
*/
public void stopPlay()
{
final TNavigationPanel tNav = getTNavigationPanel();
if (tNav != null)
tNav.stopPlay();
}
/**
* Return true if only this viewer is currently displaying its attached sequence
*/
public boolean isUnique()
{
return Icy.getMainInterface().isUniqueViewer(this);
}
private void lutChanged()
{
// can be called from external thread, replace it in AWT dispatch thread
ThreadUtil.bgRunSingle(lutUpdater);
}
private void positionChanged(DimensionId dim)
{
fireViewerChanged(ViewerEventType.POSITION_CHANGED, dim);
}
/**
* Add a listener
*
* @param listener
*/
public void addListener(ViewerListener listener)
{
listeners.add(ViewerListener.class, listener);
}
/**
* Remove a listener
*
* @param listener
*/
public void removeListener(ViewerListener listener)
{
listeners.remove(ViewerListener.class, listener);
}
void fireViewerChanged(ViewerEventType eventType, DimensionId dim)
{
final ViewerEvent event = new ViewerEvent(this, eventType, dim);
for (ViewerListener viewerListener : listeners.getListeners(ViewerListener.class))
viewerListener.viewerChanged(event);
}
void fireViewerChanged(ViewerEventType event)
{
fireViewerChanged(event, DimensionId.NULL);
}
private void fireViewerClosed()
{
for (ViewerListener viewerListener : listeners.getListeners(ViewerListener.class))
viewerListener.viewerClosed(this);
}
@Override
public void keyPressed(KeyEvent e)
{
// forward to canvas
if ((canvas != null) && (!e.isConsumed()))
canvas.keyPressed(e);
}
@Override
public void keyReleased(KeyEvent e)
{
// forward to canvas
if ((canvas != null) && (!e.isConsumed()))
canvas.keyReleased(e);
}
@Override
public void keyTyped(KeyEvent e)
{
// forward to canvas
if ((canvas != null) && (!e.isConsumed()))
canvas.keyTyped(e);
}
/**
* Change the frame's title.
*/
private void refreshViewerTitle()
{
// have to test this as we release sequence reference on closed
if (sequence != null)
setTitle(sequence.getName());
}
@Override
public void sequenceChanged(SequenceEvent event)
{
switch (event.getSourceType())
{
case SEQUENCE_META:
final String meta = (String) event.getSource();
if (StringUtil.isEmpty(meta) || StringUtil.equals(meta, Sequence.ID_NAME))
refreshViewerTitle();
break;
case SEQUENCE_DATA:
break;
case SEQUENCE_TYPE:
// might need initialization
if (!initialized && (sequence != null) && !sequence.isEmpty())
{
adjustViewerToImageSize();
initialized = true;
}
// we update LUT on type change directly on getLut() method
// // try to keep current LUT if possible
if (!sequence.isLutCompatible(lut))
// need to update the lut according to the colormodel change
setLut(sequence.getDefaultLUT());
break;
case SEQUENCE_COLORMAP:
break;
case SEQUENCE_COMPONENTBOUNDS:
// refresh lut scalers from sequence default lut
final LUT sequenceLut = sequence.getDefaultLUT();
if (!sequenceLut.isCompatible(lut) || (lutViewer == null))
lut.setScalers(sequenceLut);
break;
}
}
@Override
public void sequenceClosed(Sequence sequence)
{
}
@Override
public void canvasChanged(IcyCanvasEvent event)
{
switch (event.getType())
{
case POSITION_CHANGED:
// common process on position change
positionChanged(event.getDim());
break;
case SYNC_CHANGED:
ThreadUtil.invokeLater(new Runnable()
{
@Override
public void run()
{
refreshLockCombo();
}
});
break;
}
}
/**
* called when Canvas property "layer visible" changed
*/
@Override
public void propertyChange(PropertyChangeEvent evt)
{
super.propertyChange(evt);
refreshToolBar();
updateSystemMenu();
}
@Override
public void pluginLoaderChanged(PluginLoaderEvent e)
{
ThreadUtil.invokeLater(new Runnable()
{
@Override
public void run()
{
// refresh available canvas
buildCanvasCombo();
// and refresh components
refreshCanvasCombo();
updateToolbarComponents();
}
});
}
}
diff --git a/icy/image/colormap/IcyColorMap.java b/icy/image/colormap/IcyColorMap.java
index 538deda..c3a9f84 100644
--- a/icy/image/colormap/IcyColorMap.java
+++ b/icy/image/colormap/IcyColorMap.java
@@ -1,1262 +1,1262 @@
/*
* Copyright 2010-2013 Institut Pasteur.
*
* This file is part of Icy.
*
* Icy 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.
*
* Icy 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 Icy. If not, see <http://www.gnu.org/licenses/>.
*/
package icy.image.colormap;
import icy.common.EventHierarchicalChecker;
import icy.common.UpdateEventHandler;
import icy.common.listener.ChangeListener;
import icy.file.xml.XMLPersistent;
import icy.image.colormap.IcyColorMapEvent.IcyColorMapEventType;
import icy.util.ColorUtil;
import icy.util.XMLUtil;
import java.awt.Color;
import java.util.Arrays;
import javax.swing.event.EventListenerList;
import org.w3c.dom.Node;
/**
* @author stephane
*/
public class IcyColorMap implements ChangeListener, XMLPersistent
{
public enum IcyColorMapType
{
RGB, GRAY, ALPHA
};
private static final String ID_TYPE = "type";
private static final String ID_NAME = "name";
private static final String ID_ENABLED = "enabled";
private static final String ID_RED = "red";
private static final String ID_GREEN = "green";
private static final String ID_BLUE = "blue";
private static final String ID_GRAY = "gray";
private static final String ID_ALPHA = "alpha";
/**
* define the wanted colormap bits resolution (never change it)
*/
public static final int COLORMAP_BITS = 8;
public static final int MAX_LEVEL = (1 << COLORMAP_BITS) - 1;
/**
* define colormap size
*/
public static final int SIZE = 256;
public static final int MAX_INDEX = SIZE - 1;
/**
* colormap name
*/
private String name;
/**
* enabled flag
*/
private boolean enabled;
/**
* RED band
*/
public final IcyColorMapComponent red;
/**
* GREEN band
*/
public final IcyColorMapComponent green;
/**
* BLUE band
*/
public final IcyColorMapComponent blue;
/**
* GRAY band
*/
public final IcyColorMapComponent gray;
/**
* ALPHA band
*/
public final IcyColorMapComponent alpha;
/**
* colormap type
*/
private IcyColorMapType type;
/**
* pre-multiplied RGB caches
*/
private final int premulRGB[][];
private final float premulRGBNorm[][];
/**
* listeners
*/
private final EventListenerList listeners;
/**
* internal updater
*/
private final UpdateEventHandler updater;
public IcyColorMap(String name, IcyColorMapType type)
{
this.name = name;
enabled = true;
listeners = new EventListenerList();
updater = new UpdateEventHandler(this, false);
// colormap band
red = createColorMapBand((short) 0);
green = createColorMapBand((short) 0);
blue = createColorMapBand((short) 0);
gray = createColorMapBand((short) 0);
alpha = createColorMapBand((short) 255);
this.type = type;
// allocating and init RGB cache
premulRGB = new int[IcyColorMap.SIZE][3];
premulRGBNorm = new float[IcyColorMap.SIZE][3];
}
public IcyColorMap(String name)
{
this(name, IcyColorMapType.RGB);
}
public IcyColorMap(String name, Object maps)
{
this(name, IcyColorMapType.RGB);
if (maps instanceof byte[][])
copyFrom((byte[][]) maps);
else if (maps instanceof short[][])
copyFrom((short[][]) maps);
// try to define color map type from data
setTypeFromData(false);
}
/**
* Create a copy of specified colormap.
*/
public IcyColorMap(IcyColorMap colormap)
{
this(colormap.name, colormap.type);
copyFrom(colormap);
}
public IcyColorMap()
{
this("");
}
protected IcyColorMapComponent createColorMapBand(short initValue)
{
return new IcyColorMapComponent(IcyColorMap.this, initValue);
}
/**
* Return true if this color map is RGB type
*/
public boolean isRGB()
{
return type == IcyColorMapType.RGB;
}
/**
* Return true if this color map is GRAY type
*/
public boolean isGray()
{
return type == IcyColorMapType.GRAY;
}
/**
* Return true if this color map is ALPHA type
*/
public boolean isAlpha()
{
return type == IcyColorMapType.ALPHA;
}
/**
* @return the type
*/
public IcyColorMapType getType()
{
return type;
}
/**
* @param value
* the type to set
*/
public void setType(IcyColorMapType value)
{
if (type != value)
{
type = value;
changed(IcyColorMapEventType.TYPE_CHANGED);
}
}
/**
* @see IcyColorMap#setTypeFromData()
*/
public void setTypeFromData(boolean notifyChange)
{
boolean grayColor = true;
boolean noColor = true;
boolean hasAlpha = false;
IcyColorMapType cmType;
for (int i = 0; i < MAX_INDEX; i++)
{
final short r = red.map[i];
final short g = green.map[i];
final short b = blue.map[i];
final short a = alpha.map[i];
grayColor &= (r == g) && (r == b);
noColor &= (r == 0) && (g == 0) && (b == 0);
hasAlpha |= (a != MAX_LEVEL);
}
if (noColor && hasAlpha)
cmType = IcyColorMapType.ALPHA;
else if (grayColor && !noColor)
{
// set gray map
gray.copyFrom(red.map, 0);
cmType = IcyColorMapType.GRAY;
}
else
cmType = IcyColorMapType.RGB;
if (notifyChange)
setType(cmType);
else
type = cmType;
}
/**
* Define the type of color map depending its RGBA data.<br>
* If map contains only alpha information then type = <code>IcyColorMapType.ALPHA</code><br>
* If map contains only grey level then type = <code>IcyColorMapType.GRAY</code><br>
* else type = <code>IcyColorMapType.RGB</code>
*/
public void setTypeFromData()
{
setTypeFromData(true);
}
/**
* Set a red control point to specified index and value
*/
public void setRedControlPoint(int index, int value)
{
// set control point
red.setControlPoint(index, value);
}
/**
* Set a green control point to specified index and value
*/
public void setGreenControlPoint(int index, int value)
{
green.setControlPoint(index, value);
}
/**
* Set a blue control point to specified index and value
*/
public void setBlueControlPoint(int index, int value)
{
blue.setControlPoint(index, value);
}
/**
* Set a gray control point to specified index and value
*/
public void setGrayControlPoint(int index, int value)
{
gray.setControlPoint(index, value);
}
/**
* Set a alpha control point to specified index and value
*/
public void setAlphaControlPoint(int index, int value)
{
alpha.setControlPoint(index, value);
}
/**
* Set RGB control point values to specified index
*/
public void setRGBControlPoint(int index, Color value)
{
red.setControlPoint(index, (short) value.getRed());
green.setControlPoint(index, (short) value.getGreen());
blue.setControlPoint(index, (short) value.getBlue());
gray.setControlPoint(index, (short) ColorUtil.getGrayMix(value));
}
/**
* Set ARGB control point values to specified index
*/
public void setARGBControlPoint(int index, Color value)
{
alpha.setControlPoint(index, (short) value.getAlpha());
red.setControlPoint(index, (short) value.getRed());
green.setControlPoint(index, (short) value.getGreen());
blue.setControlPoint(index, (short) value.getBlue());
gray.setControlPoint(index, (short) ColorUtil.getGrayMix(value));
}
/**
* Returns the blue component map.<br>
* If the color map type is {@link IcyColorMapType#GRAY} then it returns the gray map instead.
* If the color map type is {@link IcyColorMapType#ALPHA} then it returns <code>null</code>.
*/
public short[] getBlueMap()
{
if (type == IcyColorMapType.RGB)
return blue.map;
if (type == IcyColorMapType.GRAY)
return gray.map;
return null;
}
/**
* Returns the green component map.<br>
* If the color map type is {@link IcyColorMapType#GRAY} then it returns the gray map instead.
* If the color map type is {@link IcyColorMapType#ALPHA} then it returns <code>null</code>.
*/
public short[] getGreenMap()
{
if (type == IcyColorMapType.RGB)
return green.map;
if (type == IcyColorMapType.GRAY)
return gray.map;
return null;
}
/**
* Returns the red component map.<br>
* If the color map type is {@link IcyColorMapType#GRAY} then it returns the gray map instead.
* If the color map type is {@link IcyColorMapType#ALPHA} then it returns <code>null</code>.
*/
public short[] getRedMap()
{
if (type == IcyColorMapType.RGB)
return red.map;
if (type == IcyColorMapType.GRAY)
return gray.map;
return null;
}
/**
* Returns the alpha component map.
*/
public short[] getAlphaMap()
{
return alpha.map;
}
/**
* Returns the normalized blue component map.<br>
* If the color map type is {@link IcyColorMapType#GRAY} then it returns the gray map instead.
* If the color map type is {@link IcyColorMapType#ALPHA} then it returns <code>null</code>.
*/
public float[] getNormalizedBlueMap()
{
if (type == IcyColorMapType.RGB)
return blue.mapf;
if (type == IcyColorMapType.GRAY)
return gray.mapf;
return null;
}
/**
* Returns the normalized green component map.<br>
* If the color map type is {@link IcyColorMapType#GRAY} then it returns the gray map instead.
* If the color map type is {@link IcyColorMapType#ALPHA} then it returns <code>null</code>.
*/
public float[] getNormalizedGreenMap()
{
if (type == IcyColorMapType.RGB)
return green.mapf;
if (type == IcyColorMapType.GRAY)
return gray.mapf;
return null;
}
/**
* Returns the normalized red component map.<br>
* If the color map type is {@link IcyColorMapType#GRAY} then it returns the gray map instead.
* If the color map type is {@link IcyColorMapType#ALPHA} then it returns <code>null</code>.
*/
public float[] getNormalizedRedMap()
{
if (type == IcyColorMapType.RGB)
return red.mapf;
if (type == IcyColorMapType.GRAY)
return gray.mapf;
return null;
}
/**
* Returns the normalized alpha component map.
*/
public float[] getNormalizedAlphaMap()
{
return alpha.mapf;
}
/**
* Get blue intensity from an input index
*
* @param index
* @return blue intensity ([0..255] range)
*/
public short getBlue(int index)
{
if (type == IcyColorMapType.RGB)
return blue.map[index];
if (type == IcyColorMapType.GRAY)
return gray.map[index];
return 0;
}
/**
* Get green intensity from an input index
*
* @param index
* @return green intensity ([0..255] range)
*/
public short getGreen(int index)
{
if (type == IcyColorMapType.RGB)
return green.map[index];
if (type == IcyColorMapType.GRAY)
return gray.map[index];
return 0;
}
/**
* Get red intensity from an input index
*
* @param index
* @return red intensity ([0..255] range)
*/
public short getRed(int index)
{
if (type == IcyColorMapType.RGB)
return red.map[index];
if (type == IcyColorMapType.GRAY)
return gray.map[index];
return 0;
}
/**
* Get alpha intensity from an input index
*
* @param index
* @return alpha intensity ([0..255] range)
*/
public short getAlpha(int index)
{
return alpha.map[index];
}
/**
* Get normalized blue intensity from an input index
*
* @param index
* @return normalized blue intensity
*/
public float getNormalizedBlue(int index)
{
if (type == IcyColorMapType.RGB)
return blue.mapf[index];
if (type == IcyColorMapType.GRAY)
return gray.mapf[index];
return 0;
}
/**
* Get normalized green intensity from an input index
*
* @param index
* @return normalized green intensity
*/
public float getNormalizedGreen(int index)
{
if (type == IcyColorMapType.RGB)
return green.mapf[index];
if (type == IcyColorMapType.GRAY)
return gray.mapf[index];
return 0;
}
/**
* Get normalized red intensity from an input index
*
* @param index
* @return normalized red intensity
*/
public float getNormalizedRed(int index)
{
if (type == IcyColorMapType.RGB)
return red.mapf[index];
if (type == IcyColorMapType.GRAY)
return gray.mapf[index];
return 0;
}
/**
* Get alpha normalized intensity from an input index
*
* @param index
* @return normalized alpha intensity
*/
public float getNormalizedAlpha(int index)
{
return alpha.mapf[index];
}
/**
* Get blue intensity from a normalized input index
*
* @param index
* @return blue intensity ([0..255] range)
*/
public short getBlue(float index)
{
return getBlue((int) (index * MAX_INDEX));
}
/**
* Get green intensity from a normalized input index
*
* @param index
* @return green intensity ([0..255] range)
*/
public short getGreen(float index)
{
return getGreen((int) (index * MAX_INDEX));
}
/**
* Get red intensity from a normalized input index
*
* @param index
* @return red intensity ([0..255] range)
*/
public short getRed(float index)
{
return getRed((int) (index * MAX_INDEX));
}
/**
* Get alpha intensity from a normalized input index
*
* @param index
* @return alpha intensity ([0..255] range)
*/
public short getAlpha(float index)
{
return getAlpha((int) (index * MAX_INDEX));
}
/**
* Get normalized blue intensity from a normalized input index
*
* @param index
* @return normalized blue intensity
*/
public float getNormalizedBlue(float index)
{
return getNormalizedBlue((int) (index * MAX_INDEX));
}
/**
* Get normalized green intensity from a normalized input index
*
* @param index
* @return normalized green intensity
*/
public float getNormalizedGreen(float index)
{
return getNormalizedGreen((int) (index * MAX_INDEX));
}
/**
* Get normalized red intensity from a normalized input index
*
* @param index
* @return normalized red intensity
*/
public float getNormalizedRed(float index)
{
return getNormalizedRed((int) (index * MAX_INDEX));
}
/**
* Get normalized alpha intensity from a normalized input index
*
* @param index
* @return normalized alpha intensity
*/
public float getNormalizedAlpha(float index)
{
return getNormalizedAlpha((int) (index * MAX_INDEX));
}
/**
* Set red intensity to specified index
*/
public void setRed(int index, short value)
{
red.setValue(index, value);
}
/**
* Set green intensity to specified index
*/
public void setGreen(int index, short value)
{
green.setValue(index, value);
}
/**
* Set blue intensity to specified index
*/
public void setBlue(int index, short value)
{
blue.setValue(index, value);
}
/**
* Set gray intensity to specified index
*/
public void setGray(int index, short value)
{
gray.setValue(index, value);
}
/**
* Set alpha intensity to specified index
*/
public void setAlpha(int index, short value)
{
alpha.setValue(index, value);
}
/**
* Set red intensity (normalized) to specified index
*/
public void setNormalizedRed(int index, float value)
{
red.setNormalizedValue(index, value);
}
/**
* Set green intensity (normalized) to specified index
*/
public void setNormalizedGreen(int index, float value)
{
green.setNormalizedValue(index, value);
}
/**
* Set blue intensity (normalized) to specified index
*/
public void setNormalizedBlue(int index, float value)
{
blue.setNormalizedValue(index, value);
}
/**
* Set gray intensity (normalized) to specified index
*/
public void setNormalizedGray(int index, float value)
{
gray.setNormalizedValue(index, value);
}
/**
* Set alpha intensity (normalized) to specified index
*/
public void setNormalizedAlpha(int index, float value)
{
alpha.setNormalizedValue(index, value);
}
/**
* Set RGB color to specified index
*/
public void setRGB(int index, int rgb)
{
alpha.setValue(index, MAX_LEVEL);
red.setValue(index, (rgb >> 16) & 0xFF);
green.setValue(index, (rgb >> 8) & 0xFF);
blue.setValue(index, (rgb >> 0) & 0xFF);
gray.setValue(index, ColorUtil.getGrayMix(rgb));
}
/**
* Set RGB color to specified index
*/
public void setRGB(int index, Color value)
{
setRGB(index, value.getRGB());
}
/**
* Set ARGB color to specified index
*/
public void setARGB(int index, int argb)
{
alpha.setValue(index, (argb >> 24) & 0xFF);
red.setValue(index, (argb >> 16) & 0xFF);
green.setValue(index, (argb >> 8) & 0xFF);
blue.setValue(index, (argb >> 0) & 0xFF);
gray.setValue(index, ColorUtil.getGrayMix(argb));
}
/**
* Set ARGB color to specified index
*/
public void setARGB(int index, Color value)
{
setARGB(index, value.getRGB());
}
/**
* Set default alpha colormap for 3D representation
*/
public void setDefaultAlphaFor3D()
{
alpha.beginUpdate();
try
{
alpha.removeAllControlPoint();
alpha.setControlPoint(0, 0f);
alpha.setControlPoint(32, 0.02f);
alpha.setControlPoint(255, 0.4f);
}
finally
{
alpha.endUpdate();
}
}
/**
* @return the name
*/
public String getName()
{
return name;
}
/**
* @param name
* the name to set
*/
public void setName(String name)
{
this.name = name;
}
/**
* @return the enabled
*/
public boolean isEnabled()
{
return enabled;
}
/**
* Set enabled flag.<br>
* This flag is used to test if the color map is enabled or not.<br>
* It is up to the developer to implement it or not.
*
* @param enabled
* the enabled to set
*/
public void setEnabled(boolean enabled)
{
if (this.enabled != enabled)
{
this.enabled = enabled;
changed(IcyColorMapEventType.ENABLED_CHANGED);
}
}
/**
* Gets a Color object representing the color at the specified index
*
* @param index
* the index of the color map to retrieve
* @return a Color object
*/
public Color getColor(int index)
{
switch (type)
{
case RGB:
return new Color(red.map[index], green.map[index], blue.map[index], alpha.map[index]);
case GRAY:
return new Color(gray.map[index], gray.map[index], gray.map[index], alpha.map[index]);
case ALPHA:
return new Color(0, 0, 0, alpha.map[index]);
}
return Color.black;
}
/**
* Return the pre-multiplied RGB cache
*/
public int[][] getPremulRGB()
{
return premulRGB;
}
/**
* Return the pre-multiplied RGB cache (normalized)
*/
public float[][] getPremulRGBNorm()
{
return premulRGBNorm;
}
/**
* Copy data from specified source colormap.
*
* @param copyAlpha
* Also copy the alpha information.
*/
public void copyFrom(IcyColorMap srcColorMap, boolean copyAlpha)
{
beginUpdate();
try
{
// copy colormap band
red.copyFrom(srcColorMap.red);
green.copyFrom(srcColorMap.green);
blue.copyFrom(srcColorMap.blue);
gray.copyFrom(srcColorMap.gray);
if (copyAlpha)
alpha.copyFrom(srcColorMap.alpha);
// copy type
setType(srcColorMap.type);
}
finally
{
endUpdate();
}
}
/**
* Copy data from specified source colormap
*/
public void copyFrom(IcyColorMap srcColorMap)
{
copyFrom(srcColorMap, true);
}
/**
* Copy data from specified 2D byte array.
*
* @param copyAlpha
* Also copy the alpha information.
*/
public void copyFrom(byte[][] maps, boolean copyAlpha)
{
final int len = maps.length;
beginUpdate();
try
{
// red component
if (len > 0)
red.copyFrom(maps[0]);
if (len > 1)
green.copyFrom(maps[1]);
if (len > 2)
blue.copyFrom(maps[2]);
if (copyAlpha && (len > 3))
alpha.copyFrom(maps[3]);
}
finally
{
endUpdate();
}
}
/**
* Copy data from specified 2D byte array
*/
public void copyFrom(byte[][] maps)
{
copyFrom(maps, true);
}
/**
* Copy data from specified 2D short array.
*
* @param copyAlpha
* Also copy the alpha information.
*/
public void copyFrom(short[][] maps, boolean copyAlpha)
{
final int len = maps.length;
beginUpdate();
try
{
// red component
if (len > 0)
red.copyFrom(maps[0], 8);
if (len > 1)
green.copyFrom(maps[1], 8);
if (len > 2)
blue.copyFrom(maps[2], 8);
if (copyAlpha && (len > 3))
alpha.copyFrom(maps[3], 8);
}
finally
{
endUpdate();
}
}
/**
* Copy data from specified 2D short array.
*/
public void copyFrom(short[][] maps)
{
copyFrom(maps, true);
}
/**
* Return true if this is a linear type colormap.<br>
* Linear colormap are used to display plain gray or color image.<br>
* A non linear colormap means you usually have an indexed color image or
* you want to enhance contrast/color in display.
*/
public boolean isLinear()
{
switch (type)
{
default:
return red.isLinear() && green.isLinear() && blue.isLinear();
case GRAY:
return gray.isLinear();
case ALPHA:
return alpha.isLinear();
}
}
/**
* Return true if this is a total black colormap.
*/
public boolean isBlack()
{
switch (type)
{
case RGB:
for (int i = 0; i < MAX_INDEX; i++)
if ((red.map[i] | green.map[i] | blue.map[i]) != 0)
return false;
return true;
case GRAY:
for (int i = 0; i < MAX_INDEX; i++)
if (gray.map[i] != 0)
return false;
return true;
default:
return false;
}
}
/**
* Returns the dominant color of this colormap.<br>
* Warning: this need sometime to compute.
*/
public Color getDominantColor()
{
final Color colors[] = new Color[SIZE];
for (int i = 0; i < colors.length; i++)
colors[i] = getColor(i);
return ColorUtil.getDominantColor(colors);
}
/**
* Update internal RGB cache
*/
private void updateRGBCache()
{
for (int i = 0; i < SIZE; i++)
{
final float af = alpha.mapf[i];
final float rgbn[] = premulRGBNorm[i];
switch (type)
{
case GRAY:
final float grayValue = gray.mapf[i] * af;
rgbn[0] = grayValue;
rgbn[1] = grayValue;
rgbn[2] = grayValue;
break;
case RGB:
rgbn[0] = blue.mapf[i] * af;
rgbn[1] = green.mapf[i] * af;
rgbn[2] = red.mapf[i] * af;
break;
default:
rgbn[0] = 0f;
rgbn[1] = 0f;
rgbn[2] = 0f;
break;
}
final int rgb[] = premulRGB[i];
rgb[0] = (int) (rgbn[0] * MAX_LEVEL);
rgb[1] = (int) (rgbn[1] * MAX_LEVEL);
rgb[2] = (int) (rgbn[2] * MAX_LEVEL);
}
}
/**
* Add a listener
*
* @param listener
*/
public void addListener(IcyColorMapListener listener)
{
listeners.add(IcyColorMapListener.class, listener);
}
/**
* Remove a listener
*
* @param listener
*/
public void removeListener(IcyColorMapListener listener)
{
listeners.remove(IcyColorMapListener.class, listener);
}
/**
* fire event
*/
public void fireEvent(IcyColorMapEvent e)
{
for (IcyColorMapListener listener : listeners.getListeners(IcyColorMapListener.class))
listener.colorMapChanged(e);
}
/**
* called when colormap data changed
*/
public void changed()
{
changed(IcyColorMapEventType.MAP_CHANGED);
}
/**
* called when colormap changed
*/
private void changed(IcyColorMapEventType type)
{
// handle changed via updater object
updater.changed(new IcyColorMapEvent(this, type));
}
@Override
public void onChanged(EventHierarchicalChecker e)
{
final IcyColorMapEvent event = (IcyColorMapEvent) e;
switch (event.getType())
{
// refresh RGB cache
case MAP_CHANGED:
case TYPE_CHANGED:
updateRGBCache();
break;
}
// notify listener we have changed
fireEvent(event);
}
/**
* @see icy.common.UpdateEventHandler#beginUpdate()
*/
public void beginUpdate()
{
updater.beginUpdate();
red.beginUpdate();
green.beginUpdate();
blue.beginUpdate();
gray.beginUpdate();
alpha.beginUpdate();
}
/**
* @see icy.common.UpdateEventHandler#endUpdate()
*/
public void endUpdate()
{
alpha.endUpdate();
gray.endUpdate();
blue.endUpdate();
green.endUpdate();
red.endUpdate();
updater.endUpdate();
}
/**
* @see icy.common.UpdateEventHandler#isUpdating()
*/
public boolean isUpdating()
{
return updater.isUpdating();
}
@Override
public String toString()
{
return name + " : " + super.toString();
}
/**
* Return true if the colormap has the same type and same color intensities than specified one.
*/
@Override
public boolean equals(Object obj)
{
if (obj instanceof IcyColorMap)
{
final IcyColorMap colormap = (IcyColorMap) obj;
if (colormap.getType() != type)
return false;
if (!Arrays.equals(red.map, colormap.red.map))
return false;
if (!Arrays.equals(green.map, colormap.green.map))
return false;
if (!Arrays.equals(blue.map, colormap.blue.map))
return false;
if (!Arrays.equals(gray.map, colormap.gray.map))
return false;
if (!Arrays.equals(alpha.map, colormap.alpha.map))
return false;
return true;
}
return super.equals(obj);
}
@Override
public boolean loadFromXML(Node node)
{
if (node == null)
return false;
beginUpdate();
try
{
setName(XMLUtil.getElementValue(node, ID_NAME, ""));
setEnabled(XMLUtil.getElementBooleanValue(node, ID_ENABLED, true));
- setType(IcyColorMapType.valueOf(XMLUtil.getElementValue(node, ID_TYPE, "")));
+ setType(IcyColorMapType.valueOf(XMLUtil.getElementValue(node, ID_TYPE, IcyColorMapType.RGB.toString())));
boolean result = true;
result = result && red.loadFromXML(XMLUtil.getElement(node, ID_RED));
result = result && green.loadFromXML(XMLUtil.getElement(node, ID_GREEN));
result = result && blue.loadFromXML(XMLUtil.getElement(node, ID_BLUE));
result = result && gray.loadFromXML(XMLUtil.getElement(node, ID_GRAY));
result = result && alpha.loadFromXML(XMLUtil.getElement(node, ID_ALPHA));
return result;
}
finally
{
endUpdate();
}
}
@Override
public boolean saveToXML(Node node)
{
if (node == null)
return false;
XMLUtil.setElementValue(node, ID_NAME, getName());
XMLUtil.setElementBooleanValue(node, ID_ENABLED, isEnabled());
XMLUtil.setElementValue(node, ID_TYPE, getType().toString());
boolean result = true;
result = result && red.saveToXML(XMLUtil.setElement(node, ID_RED));
result = result && green.saveToXML(XMLUtil.setElement(node, ID_GREEN));
result = result && blue.saveToXML(XMLUtil.setElement(node, ID_BLUE));
result = result && gray.saveToXML(XMLUtil.setElement(node, ID_GRAY));
result = result && alpha.saveToXML(XMLUtil.setElement(node, ID_ALPHA));
return result;
}
}
diff --git a/icy/sequence/SequenceUtil.java b/icy/sequence/SequenceUtil.java
index 5e69ac8..c474c4a 100644
--- a/icy/sequence/SequenceUtil.java
+++ b/icy/sequence/SequenceUtil.java
@@ -1,2143 +1,2147 @@
/*
* Copyright 2010-2013 Institut Pasteur.
*
* This file is part of Icy.
*
* Icy 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.
*
* Icy 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 Icy. If not, see <http://www.gnu.org/licenses/>.
*/
package icy.sequence;
import icy.common.listener.ProgressListener;
import icy.image.IcyBufferedImage;
import icy.image.IcyBufferedImageUtil;
import icy.image.IcyBufferedImageUtil.FilterType;
import icy.image.lut.LUT;
import icy.math.Scaler;
import icy.painter.Overlay;
import icy.roi.BooleanMask2D;
import icy.roi.ROI;
import icy.type.DataType;
import icy.type.collection.array.Array1DUtil;
import icy.type.rectangle.Rectangle5D;
import icy.util.OMEUtil;
import icy.util.StringUtil;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import javax.swing.SwingConstants;
import loci.formats.ome.OMEXMLMetadataImpl;
/**
* {@link Sequence} utilities class.<br>
* You can find here tools to manipulate the sequence organization, its data type, its size...
*
* @author Stephane
*/
public class SequenceUtil
{
public static class AddZHelper
{
public static IcyBufferedImage getExtendedImage(Sequence sequence, int t, int z, int insertPosition,
int numInsert, int copyLast)
{
if (z < insertPosition)
return sequence.getImage(t, z);
final int pos = z - insertPosition;
// return new image
if (pos < numInsert)
{
// return copy of previous image(s)
if ((insertPosition > 0) && (copyLast > 0))
{
// should be < insert position
final int duplicate = Math.min(insertPosition, copyLast);
final int baseReplicate = insertPosition - duplicate;
return sequence.getImage(t, baseReplicate + (pos % duplicate));
}
// return new empty image
return new IcyBufferedImage(sequence.getSizeX(), sequence.getSizeY(), sequence.getSizeC(),
sequence.getDataType_());
}
return sequence.getImage(t, z - numInsert);
}
}
public static class AddTHelper
{
public static IcyBufferedImage getExtendedImage(Sequence sequence, int t, int z, int insertPosition,
int numInsert, int copyLast)
{
if (t < insertPosition)
return sequence.getImage(t, z);
final int pos = t - insertPosition;
// return new image
if (pos < numInsert)
{
// return copy of previous image(s)
if ((insertPosition > 0) && (copyLast > 0))
{
// should be < insert position
final int duplicate = Math.min(insertPosition, copyLast);
final int baseReplicate = insertPosition - duplicate;
return sequence.getImage(baseReplicate + (pos % duplicate), z);
}
// return new empty image
return new IcyBufferedImage(sequence.getSizeX(), sequence.getSizeY(), sequence.getSizeC(),
sequence.getDataType_());
}
return sequence.getImage(t - numInsert, z);
}
}
public static class MergeCHelper
{
private static IcyBufferedImage getImageFromSequenceInternal(Sequence seq, int t, int z, int c,
boolean fillEmpty)
{
IcyBufferedImage img = seq.getImage(t, z, c);
if ((img == null) && fillEmpty)
{
int curZ = z;
// missing Z slice ?
if (z >= seq.getSizeZ())
{
// searching in previous slice
while ((img == null) && (curZ > 0))
img = seq.getImage(t, --curZ, c);
}
if (img == null)
{
int curT = t;
// searching in previous frame
while ((img == null) && (curT > 0))
img = seq.getImage(--curT, z, c);
}
return img;
}
return img;
}
public static IcyBufferedImage getImage(Sequence[] sequences, int[] channels, int sizeX, int sizeY, int t,
int z, boolean fillEmpty, boolean rescale)
{
if (sequences.length == 0)
return null;
final List<BufferedImage> images = new ArrayList<BufferedImage>();
for (int i = 0; i < sequences.length; i++)
{
final Sequence seq = sequences[i];
final int c = channels[i];
IcyBufferedImage img = getImageFromSequenceInternal(seq, t, z, c, fillEmpty);
// create an empty image
if (img == null)
img = new IcyBufferedImage(sizeX, sizeY, 1, seq.getDataType_());
// resize X and Y dimension if needed
else if ((img.getSizeX() != sizeX) || (img.getSizeY() != sizeY))
img = IcyBufferedImageUtil.scale(img, sizeX, sizeY, rescale, SwingConstants.CENTER,
SwingConstants.CENTER, FilterType.BILINEAR);
images.add(img);
}
return IcyBufferedImage.createFrom(images);
}
}
public static class MergeZHelper
{
private static IcyBufferedImage getImageFromSequenceInternal(Sequence seq, int t, int z, boolean fillEmpty)
{
IcyBufferedImage img = seq.getImage(t, z);
if ((img == null) && fillEmpty)
{
int curZ = z;
// missing Z slice ?
if (z >= seq.getSizeZ())
{
// searching in previous slice
while ((img == null) && (curZ > 0))
img = seq.getImage(t, --curZ);
}
if (img == null)
{
int curT = t;
// searching in previous frame
while ((img == null) && (curT > 0))
img = seq.getImage(--curT, z);
}
return img;
}
return img;
}
private static IcyBufferedImage getImageInternal(Sequence[] sequences, int t, int z, boolean interlaced,
boolean fillEmpty)
{
int zRemaining = z;
if (interlaced)
{
int zInd = 0;
while (zRemaining >= 0)
{
for (Sequence seq : sequences)
{
if (zInd < seq.getSizeZ())
{
if (zRemaining-- == 0)
return getImageFromSequenceInternal(seq, t, zInd, fillEmpty);
}
}
zInd++;
}
}
else
{
for (Sequence seq : sequences)
{
final int sizeZ = seq.getSizeZ();
// we found the sequence
if (zRemaining < sizeZ)
return getImageFromSequenceInternal(seq, t, zRemaining, fillEmpty);
zRemaining -= sizeZ;
}
}
return null;
}
public static IcyBufferedImage getImage(Sequence[] sequences, int sizeX, int sizeY, int sizeC, int t, int z,
boolean interlaced, boolean fillEmpty, boolean rescale)
{
final IcyBufferedImage origin = getImageInternal(sequences, t, z, interlaced, fillEmpty);
IcyBufferedImage img = origin;
if (img != null)
{
// resize X and Y dimension if needed
if ((img.getSizeX() != sizeX) || (img.getSizeY() != sizeY))
img = IcyBufferedImageUtil.scale(img, sizeX, sizeY, rescale, SwingConstants.CENTER,
SwingConstants.CENTER, FilterType.BILINEAR);
final int imgSizeC = img.getSizeC();
// resize C dimension if needed
if (imgSizeC < sizeC)
return IcyBufferedImageUtil.addChannels(img, imgSizeC, sizeC - imgSizeC);
if (img == origin)
return img;
}
return img;
}
}
public static class MergeTHelper
{
private static IcyBufferedImage getImageFromSequenceInternal(Sequence seq, int t, int z, boolean fillEmpty)
{
IcyBufferedImage img = seq.getImage(t, z);
if ((img == null) && fillEmpty)
{
int curT = t;
// missing T frame?
if (t >= seq.getSizeT())
{
// searching in previous frame
while ((img == null) && (curT > 0))
img = seq.getImage(--curT, z);
}
if (img == null)
{
int curZ = z;
// searching in previous slice
while ((img == null) && (curZ > 0))
img = seq.getImage(t, --curZ);
}
return img;
}
return img;
}
private static IcyBufferedImage getImageInternal(Sequence[] sequences, int t, int z, boolean interlaced,
boolean fillEmpty)
{
int tRemaining = t;
if (interlaced)
{
int tInd = 0;
while (tRemaining >= 0)
{
for (Sequence seq : sequences)
{
if (tInd < seq.getSizeT())
{
if (tRemaining-- == 0)
return getImageFromSequenceInternal(seq, tInd, z, fillEmpty);
}
}
tInd++;
}
}
else
{
for (Sequence seq : sequences)
{
final int sizeT = seq.getSizeT();
// we found the sequence
if (tRemaining < sizeT)
return getImageFromSequenceInternal(seq, tRemaining, z, fillEmpty);
tRemaining -= sizeT;
}
}
return null;
}
public static IcyBufferedImage getImage(Sequence[] sequences, int sizeX, int sizeY, int sizeC, int t, int z,
boolean interlaced, boolean fillEmpty, boolean rescale)
{
final IcyBufferedImage origin = getImageInternal(sequences, t, z, interlaced, fillEmpty);
IcyBufferedImage img = origin;
if (img != null)
{
// resize X and Y dimension if needed
if ((img.getSizeX() != sizeX) || (img.getSizeY() != sizeY))
img = IcyBufferedImageUtil.scale(img, sizeX, sizeY, rescale, SwingConstants.CENTER,
SwingConstants.CENTER, FilterType.BILINEAR);
final int imgSizeC = img.getSizeC();
// resize C dimension if needed
if (imgSizeC < sizeC)
return IcyBufferedImageUtil.addChannels(img, imgSizeC, sizeC - imgSizeC);
if (img == origin)
return img;
}
return img;
}
}
public static class AdjustZTHelper
{
public static IcyBufferedImage getImage(Sequence sequence, int t, int z, int newSizeZ, int newSizeT,
boolean reverseOrder)
{
final int sizeZ = sequence.getSizeZ();
final int sizeT = sequence.getSizeT();
// out of range
if ((t >= newSizeT) || (z >= newSizeZ))
return null;
final int index;
// calculate index of wanted image
if (reverseOrder)
index = (z * newSizeT) + t;
else
index = (t * newSizeZ) + z;
final int tOrigin = index / sizeZ;
final int zOrigin = index % sizeZ;
// bounding --> return new image
if (tOrigin >= sizeT)
return new IcyBufferedImage(sequence.getSizeX(), sequence.getSizeY(), sequence.getSizeC(),
sequence.getDataType_());
return sequence.getImage(tOrigin, zOrigin);
}
}
/**
* Add one or severals frames at position t.
*
* @param t
* Position where to add frame(s)
* @param num
* Number of frame to add
* @param copyLast
* Number of last frame(s) to copy to fill added frames.<br>
* 0 means that new frames are empty.<br>
* 1 means we duplicate the last frame.<br>
* 2 means we duplicate the two last frames.<br>
* and so on...
*/
public static void addT(Sequence sequence, int t, int num, int copyLast)
{
final int sizeZ = sequence.getSizeZ();
final int sizeT = sequence.getSizeT();
sequence.beginUpdate();
try
{
moveT(sequence, t, sizeT - 1, num);
for (int i = 0; i < num; i++)
for (int z = 0; z < sizeZ; z++)
sequence.setImage(t + i, z, IcyBufferedImageUtil.getCopy(AddTHelper.getExtendedImage(sequence, t
+ i, z, t, num, copyLast)));
}
finally
{
sequence.endUpdate();
}
}
/**
* Add one or severals frames at position t.
*
* @param t
* Position where to add frame(s)
* @param num
* Number of frame to add
*/
public static void addT(Sequence sequence, int t, int num)
{
addT(sequence, t, num, 0);
}
/**
* Add one or severals frames at position t.
*
* @param num
* Number of frame to add
*/
public static void addT(Sequence sequence, int num)
{
addT(sequence, sequence.getSizeT(), num, 0);
}
/**
* Add one or severals frames at position t.
*
* @param num
* Number of frame to add
* @param copyLast
* If true then the last frame is copied in added frames.
*/
public static void addT(Sequence sequence, int num, boolean copyLast)
{
addT(sequence, sequence.getSizeT(), num, 0);
}
/**
* Exchange 2 frames position on the sequence.
*/
public static void swapT(Sequence sequence, int t1, int t2)
{
final int sizeT = sequence.getSizeT();
if ((t1 < 0) || (t2 < 0) || (t1 >= sizeT) || (t2 >= sizeT))
return;
// get volume images at position t1 & t2
final VolumetricImage vi1 = sequence.getVolumetricImage(t1);
final VolumetricImage vi2 = sequence.getVolumetricImage(t2);
sequence.beginUpdate();
try
{
// start by removing old volume image (if any)
sequence.removeAllImages(t1);
sequence.removeAllImages(t2);
// safe volume image copy (TODO : check if we can't direct set volume image internally)
if (vi1 != null)
{
final Map<Integer, IcyBufferedImage> images = vi1.getImages();
// copy images of volume image 1 at position t2
for (Entry<Integer, IcyBufferedImage> entry : images.entrySet())
sequence.setImage(t2, entry.getKey().intValue(), entry.getValue());
}
if (vi2 != null)
{
final Map<Integer, IcyBufferedImage> images = vi2.getImages();
// copy images of volume image 2 at position t1
for (Entry<Integer, IcyBufferedImage> entry : images.entrySet())
sequence.setImage(t1, entry.getKey().intValue(), entry.getValue());
}
}
finally
{
sequence.endUpdate();
}
}
/**
* Modify frame position.<br>
* The previous frame present at <code>newT</code> position is lost.
*
* @param sequence
* @param t
* current t position
* @param newT
* wanted t position
*/
public static void moveT(Sequence sequence, int t, int newT)
{
final int sizeT = sequence.getSizeT();
if ((t < 0) || (t >= sizeT) || (newT < 0) || (t == newT))
return;
// get volume image at position t
final VolumetricImage vi = sequence.getVolumetricImage(t);
sequence.beginUpdate();
try
{
// remove volume image (if any) at position newT
sequence.removeAllImages(newT);
if (vi != null)
{
final TreeMap<Integer, IcyBufferedImage> images = vi.getImages();
// copy images of volume image at position newT
for (Entry<Integer, IcyBufferedImage> entry : images.entrySet())
sequence.setImage(newT, entry.getKey().intValue(), entry.getValue());
// remove volume image at position t
sequence.removeAllImages(t);
}
}
finally
{
sequence.endUpdate();
}
}
/**
* Modify T position of a range of frame by the specified offset
*
* @param sequence
* @param from
* start of range (t position)
* @param to
* end of range (t position)
* @param offset
* position shift
*/
public static void moveT(Sequence sequence, int from, int to, int offset)
{
sequence.beginUpdate();
try
{
if (offset > 0)
{
for (int t = to; t >= from; t--)
moveT(sequence, t, t + offset);
}
else
{
for (int t = from; t <= to; t++)
moveT(sequence, t, t + offset);
}
}
finally
{
sequence.endUpdate();
}
}
/**
* Remove a frame at position t.
*
* @param sequence
* @param t
*/
public static void removeT(Sequence sequence, int t)
{
final int sizeT = sequence.getSizeT();
if ((t < 0) || (t >= sizeT))
return;
sequence.removeAllImages(t);
}
/**
* Remove a frame at position t and shift all the further t by -1.
*
* @param sequence
* @param t
*/
public static void removeTAndShift(Sequence sequence, int t)
{
final int sizeT = sequence.getSizeT();
if ((t < 0) || (t >= sizeT))
return;
sequence.beginUpdate();
try
{
removeT(sequence, t);
moveT(sequence, t + 1, sizeT - 1, -1);
}
finally
{
sequence.endUpdate();
}
}
/**
* Reverse T frames order.
*/
public static void reverseT(Sequence sequence)
{
final int sizeT = sequence.getSizeT();
final int sizeZ = sequence.getSizeZ();
final Sequence save = new Sequence();
save.beginUpdate();
try
{
for (int t = 0; t < sizeT; t++)
for (int z = 0; z < sizeZ; z++)
save.setImage(t, z, sequence.getImage(t, z));
}
finally
{
save.endUpdate();
}
sequence.beginUpdate();
try
{
sequence.removeAllImages();
for (int t = 0; t < sizeT; t++)
for (int z = 0; z < sizeZ; z++)
sequence.setImage(sizeT - (t + 1), z, save.getImage(t, z));
}
finally
{
sequence.endUpdate();
}
}
/**
* Add one or severals slices at position z.
*
* @param z
* Position where to add slice(s)
* @param num
* Number of slice to add
* @param copyLast
* Number of last slice(s) to copy to fill added slices.<br>
* 0 means that new slices are empty.<br>
* 1 means we duplicate the last slice.<br>
* 2 means we duplicate the two last slices.<br>
* and so on...
*/
public static void addZ(Sequence sequence, int z, int num, int copyLast)
{
final int sizeZ = sequence.getSizeZ();
final int sizeT = sequence.getSizeT();
sequence.beginUpdate();
try
{
moveZ(sequence, z, sizeZ - 1, num);
for (int i = 0; i < num; i++)
for (int t = 0; t < sizeT; t++)
sequence.setImage(t, z + i, IcyBufferedImageUtil.getCopy(AddZHelper.getExtendedImage(sequence, t, z
+ i, z, num, copyLast)));
}
finally
{
sequence.endUpdate();
}
}
/**
* Add one or severals slices at position z.
*
* @param z
* Position where to add slice(s)
* @param num
* Number of slice to add
*/
public static void addZ(Sequence sequence, int z, int num)
{
addZ(sequence, z, num, 0);
}
/**
* Add one or severals slices at position z.
*
* @param num
* Number of slice to add
*/
public static void addZ(Sequence sequence, int num)
{
addZ(sequence, sequence.getSizeZ(), num, 0);
}
/**
* Add one or severals slices at position z.
*
* @param num
* Number of slice to add
* @param copyLast
* If true then the last slice is copied in added slices.
*/
public static void addZ(Sequence sequence, int num, boolean copyLast)
{
addZ(sequence, sequence.getSizeZ(), num, 0);
}
/**
* Exchange 2 slices position on the sequence.
*/
public static void swapZ(Sequence sequence, int z1, int z2)
{
final int sizeZ = sequence.getSizeZ();
final int sizeT = sequence.getSizeT();
if ((z1 < 0) || (z2 < 0) || (z1 >= sizeZ) || (z2 >= sizeZ))
return;
sequence.beginUpdate();
try
{
for (int t = 0; t < sizeT; t++)
{
final IcyBufferedImage image1 = sequence.getImage(t, z1);
final IcyBufferedImage image2 = sequence.getImage(t, z2);
// set image at new position
if (image1 != null)
sequence.setImage(t, z2, image1);
else
sequence.removeImage(t, z2);
if (image2 != null)
sequence.setImage(t, z1, image2);
else
sequence.removeImage(t, z1);
}
}
finally
{
sequence.endUpdate();
}
}
/**
* Modify slice position.<br>
* The previous slice present at <code>newZ</code> position is lost.
*
* @param sequence
* @param z
* current z position
* @param newZ
* wanted z position
*/
public static void moveZ(Sequence sequence, int z, int newZ)
{
final int sizeZ = sequence.getSizeZ();
final int sizeT = sequence.getSizeT();
if ((z < 0) || (z >= sizeZ) || (newZ < 0) || (z == newZ))
return;
sequence.beginUpdate();
try
{
for (int t = 0; t < sizeT; t++)
{
final IcyBufferedImage image = sequence.getImage(t, z);
if (image != null)
{
// set image at new position
sequence.setImage(t, newZ, image);
// and remove image at old position z
sequence.removeImage(t, z);
}
else
// just set null image at new position (equivalent to no image)
sequence.removeImage(t, newZ);
}
}
finally
{
sequence.endUpdate();
}
}
/**
* Modify Z position of a range of slice by the specified offset
*
* @param sequence
* @param from
* start of range (z position)
* @param to
* end of range (z position)
* @param offset
* position shift
*/
public static void moveZ(Sequence sequence, int from, int to, int offset)
{
sequence.beginUpdate();
try
{
if (offset > 0)
{
for (int z = to; z >= from; z--)
moveZ(sequence, z, z + offset);
}
else
{
for (int z = from; z <= to; z++)
moveZ(sequence, z, z + offset);
}
}
finally
{
sequence.endUpdate();
}
}
/**
* Remove a slice at position Z.
*
* @param sequence
* @param z
*/
public static void removeZ(Sequence sequence, int z)
{
final int sizeZ = sequence.getSizeZ();
if ((z < 0) || (z >= sizeZ))
return;
sequence.beginUpdate();
try
{
final int maxT = sequence.getSizeT();
for (int t = 0; t < maxT; t++)
sequence.removeImage(t, z);
}
finally
{
sequence.endUpdate();
}
}
/**
* Remove a slice at position t and shift all the further t by -1.
*
* @param sequence
* @param z
*/
public static void removeZAndShift(Sequence sequence, int z)
{
final int sizeZ = sequence.getSizeZ();
if ((z < 0) || (z >= sizeZ))
return;
sequence.beginUpdate();
try
{
removeZ(sequence, z);
moveZ(sequence, z + 1, sizeZ - 1, -1);
}
finally
{
sequence.endUpdate();
}
}
/**
* Reverse Z slices order.
*/
public static void reverseZ(Sequence sequence)
{
final int sizeT = sequence.getSizeT();
final int sizeZ = sequence.getSizeZ();
final Sequence save = new Sequence();
save.beginUpdate();
try
{
for (int t = 0; t < sizeT; t++)
for (int z = 0; z < sizeZ; z++)
save.setImage(t, z, sequence.getImage(t, z));
}
finally
{
save.endUpdate();
}
sequence.beginUpdate();
try
{
sequence.removeAllImages();
for (int t = 0; t < sizeT; t++)
for (int z = 0; z < sizeZ; z++)
sequence.setImage(t, sizeZ - (z + 1), save.getImage(t, z));
}
finally
{
sequence.endUpdate();
}
}
/**
* Set all images of the sequence in T dimension.
*/
public static void convertToTime(Sequence sequence)
{
sequence.beginUpdate();
try
{
final List<IcyBufferedImage> images = sequence.getAllImage();
sequence.removeAllImages();
for (int i = 0; i < images.size(); i++)
sequence.setImage(i, 0, images.get(i));
}
finally
{
sequence.endUpdate();
}
}
/**
* Set all images of the sequence in Z dimension.
*/
public static void convertToStack(Sequence sequence)
{
sequence.beginUpdate();
try
{
final List<IcyBufferedImage> images = sequence.getAllImage();
sequence.removeAllImages();
for (int i = 0; i < images.size(); i++)
sequence.setImage(0, i, images.get(i));
}
finally
{
sequence.endUpdate();
}
}
/**
* @deprecated Use {@link #convertToStack(Sequence)} instead.
*/
@Deprecated
public static void convertToVolume(Sequence sequence)
{
convertToStack(sequence);
}
/**
* Remove the specified channel from the source sequence.
*
* @param source
* Source sequence
* @param channel
* Channel index to remove
*/
public static void removeChannel(Sequence source, int channel)
{
final int sizeC = source.getSizeC();
+
+ if (channel >= sizeC)
+ return;
+
final int[] keep = new int[sizeC - 1];
int i = 0;
for (int c = 0; c < sizeC; c++)
if (c != channel)
keep[i++] = c;
final Sequence tmp = extractChannels(source, keep);
source.beginUpdate();
try
{
// we need to clear the source sequence to change its type
source.removeAllImages();
// get back all images
for (int t = 0; t < tmp.getSizeT(); t++)
for (int z = 0; z < tmp.getSizeZ(); z++)
source.setImage(t, z, tmp.getImage(t, z));
// get back modified metadata
source.setMetaData(tmp.getMetadata());
// and colormaps
for (int c = 0; c < tmp.getSizeC(); c++)
source.setDefaultColormap(c, tmp.getDefaultColorMap(c), false);
}
finally
{
source.endUpdate();
}
}
/**
* Returns the max size of specified dimension for the given sequences.
*/
public static int getMaxDim(Sequence[] sequences, DimensionId dim)
{
int result = 0;
for (Sequence seq : sequences)
{
switch (dim)
{
case X:
result = Math.max(result, seq.getSizeX());
break;
case Y:
result = Math.max(result, seq.getSizeY());
break;
case C:
result = Math.max(result, seq.getSizeC());
break;
case Z:
result = Math.max(result, seq.getSizeZ());
break;
case T:
result = Math.max(result, seq.getSizeT());
break;
}
}
return result;
}
/**
* Create and returns a new sequence by concatenating all given sequences on C dimension.
*
* @param sequences
* Sequences to concatenate (use array order).
* @param channels
* Selected channel for each sequence (<code>channels.length = sequences.length</code>)<br>
* If you want to select 2 or more channels from a sequence, just duplicate the sequence
* entry in the <code>sequences</code> parameter :</code><br>
* <code>sequences[n] = Sequence1; channels[n] = 0;</code><br>
* <code>sequences[n+1] = Sequence1; channels[n+1] = 2;</code><br>
* <code>...</code>
* @param fillEmpty
* Replace empty image by the previous non empty one.
* @param rescale
* Images are scaled to all fit in the same XY dimension.
* @param pl
* ProgressListener to indicate processing progress.
*/
public static Sequence concatC(Sequence[] sequences, int[] channels, boolean fillEmpty, boolean rescale,
ProgressListener pl)
{
final int sizeX = getMaxDim(sequences, DimensionId.X);
final int sizeY = getMaxDim(sequences, DimensionId.Y);
final int sizeZ = getMaxDim(sequences, DimensionId.Z);
final int sizeT = getMaxDim(sequences, DimensionId.T);
final Sequence result = new Sequence();
if (sequences.length > 0)
result.setMetaData(OMEUtil.createOMEMetadata(sequences[0].getMetadata()));
result.setName("C Merge");
int ind = 0;
for (int t = 0; t < sizeT; t++)
{
for (int z = 0; z < sizeZ; z++)
{
if (pl != null)
pl.notifyProgress(ind, sizeT * sizeZ);
result.setImage(t, z,
MergeCHelper.getImage(sequences, channels, sizeX, sizeY, t, z, fillEmpty, rescale));
ind++;
}
}
int c = 0;
for (Sequence seq : sequences)
{
for (int sc = 0; sc < seq.getSizeC(); sc++, c++)
{
final String channelName = seq.getChannelName(sc);
// not default channel name --> we keep it
if (!StringUtil.equals(seq.getDefaultChannelName(sc), channelName))
result.setChannelName(c, channelName);
}
}
return result;
}
/**
* Create and returns a new sequence by concatenating all given sequences on C dimension.
*
* @param sequences
* Sequences to concatenate (use array order).
* @param fillEmpty
* Replace empty image by the previous non empty one.
* @param rescale
* Images are scaled to all fit in the same XY dimension.
* @param pl
* ProgressListener to indicate processing progress.
*/
public static Sequence concatC(Sequence[] sequences, boolean fillEmpty, boolean rescale, ProgressListener pl)
{
final int channels[] = new int[sequences.length];
Arrays.fill(channels, -1);
return concatC(sequences, channels, fillEmpty, rescale, pl);
}
/**
* Create and returns a new sequence by concatenating all given sequences on C dimension.
*
* @param sequences
* Sequences to concatenate (use array order).
* @param fillEmpty
* Replace empty image by the previous non empty one.
* @param rescale
* Images are scaled to all fit in the same XY dimension.
*/
public static Sequence concatC(Sequence[] sequences, boolean fillEmpty, boolean rescale)
{
return concatC(sequences, fillEmpty, rescale, null);
}
/**
* Create and returns a new sequence by concatenating all given sequences on C dimension.
*
* @param sequences
* Sequences to concatenate (use array order).
*/
public static Sequence concatC(Sequence[] sequences)
{
return concatC(sequences, true, false, null);
}
/**
* Create and returns a new sequence by concatenating all given sequences on Z dimension.
*
* @param sequences
* Sequences to concatenate (use array order).
* @param interlaced
* Interlace images.<br>
* normal : 1,1,1,2,2,2,3,3,..<br>
* interlaced : 1,2,3,1,2,3,..<br>
* @param fillEmpty
* Replace empty image by the previous non empty one.
* @param rescale
* Images are scaled to all fit in the same XY dimension.
* @param pl
* ProgressListener to indicate processing progress.
*/
public static Sequence concatZ(Sequence[] sequences, boolean interlaced, boolean fillEmpty, boolean rescale,
ProgressListener pl)
{
final int sizeX = getMaxDim(sequences, DimensionId.X);
final int sizeY = getMaxDim(sequences, DimensionId.Y);
final int sizeC = getMaxDim(sequences, DimensionId.C);
final int sizeT = getMaxDim(sequences, DimensionId.T);
int sizeZ = 0;
for (Sequence seq : sequences)
sizeZ += seq.getSizeZ();
final Sequence result = new Sequence();
if (sequences.length > 0)
result.setMetaData(OMEUtil.createOMEMetadata(sequences[0].getMetadata()));
result.setName("Z Merge");
int ind = 0;
for (int t = 0; t < sizeT; t++)
{
for (int z = 0; z < sizeZ; z++)
{
if (pl != null)
pl.notifyProgress(ind, sizeT * sizeZ);
result.setImage(t, z, IcyBufferedImageUtil.getCopy(MergeZHelper.getImage(sequences, sizeX, sizeY,
sizeC, t, z, interlaced, fillEmpty, rescale)));
ind++;
}
}
return result;
}
/**
* Create and returns a new sequence by concatenating all given sequences on Z dimension.
*
* @param sequences
* Sequences to concatenate (use array order).
* @param interlaced
* Interlace images.<br>
* normal : 1,1,1,2,2,2,3,3,..<br>
* interlaced : 1,2,3,1,2,3,..<br>
* @param fillEmpty
* Replace empty image by the previous non empty one.
* @param rescale
* Images are scaled to all fit in the same XY dimension.
*/
public static Sequence concatZ(Sequence[] sequences, boolean interlaced, boolean fillEmpty, boolean rescale)
{
return concatZ(sequences, interlaced, fillEmpty, rescale, null);
}
/**
* Create and returns a new sequence by concatenating all given sequences on Z dimension.
*
* @param sequences
* Sequences to concatenate (use array order).
*/
public static Sequence concatZ(Sequence[] sequences)
{
return concatZ(sequences, false, true, false, null);
}
/**
* Create and returns a new sequence by concatenating all given sequences on T dimension.
*
* @param sequences
* sequences to concatenate (use array order).
* @param interlaced
* interlace images.<br>
* normal : 1,1,1,2,2,2,3,3,..<br>
* interlaced : 1,2,3,1,2,3,..<br>
* @param fillEmpty
* replace empty image by the previous non empty one.
* @param rescale
* Images are scaled to all fit in the same XY dimension.
* @param pl
* ProgressListener to indicate processing progress.
*/
public static Sequence concatT(Sequence[] sequences, boolean interlaced, boolean fillEmpty, boolean rescale,
ProgressListener pl)
{
final int sizeX = getMaxDim(sequences, DimensionId.X);
final int sizeY = getMaxDim(sequences, DimensionId.Y);
final int sizeC = getMaxDim(sequences, DimensionId.C);
final int sizeZ = getMaxDim(sequences, DimensionId.Z);
int sizeT = 0;
for (Sequence seq : sequences)
sizeT += seq.getSizeT();
final Sequence result = new Sequence();
if (sequences.length > 0)
result.setMetaData(OMEUtil.createOMEMetadata(sequences[0].getMetadata()));
result.setName("T Merge");
int ind = 0;
for (int t = 0; t < sizeT; t++)
{
for (int z = 0; z < sizeZ; z++)
{
if (pl != null)
pl.notifyProgress(ind, sizeT * sizeZ);
result.setImage(t, z, IcyBufferedImageUtil.getCopy(MergeTHelper.getImage(sequences, sizeX, sizeY,
sizeC, t, z, interlaced, fillEmpty, rescale)));
ind++;
}
}
return result;
}
/**
* Create and returns a new sequence by concatenating all given sequences on T dimension.
*
* @param sequences
* Sequences to concatenate (use array order).
* @param interlaced
* Interlace images.<br>
* normal : 1,1,1,2,2,2,3,3,..<br>
* interlaced : 1,2,3,1,2,3,..<br>
* @param fillEmpty
* Replace empty image by the previous non empty one.
* @param rescale
* Images are scaled to all fit in the same XY dimension.
*/
public static Sequence concatT(Sequence[] sequences, boolean interlaced, boolean fillEmpty, boolean rescale)
{
return concatT(sequences, interlaced, fillEmpty, rescale, null);
}
/**
* Create and returns a new sequence by concatenating all given sequences on T dimension.
*
* @param sequences
* Sequences to concatenate (use array order).
*/
public static Sequence concatT(Sequence[] sequences)
{
return concatT(sequences, false, true, false, null);
}
/**
* Adjust Z and T dimension of the sequence.
*
* @param reverseOrder
* Means that images are T-Z ordered instead of Z-T ordered
* @param newSizeZ
* New Z size of the sequence
* @param newSizeT
* New T size of the sequence
*/
public static void adjustZT(Sequence sequence, int newSizeZ, int newSizeT, boolean reverseOrder)
{
final int sizeZ = sequence.getSizeZ();
final int sizeT = sequence.getSizeT();
final Sequence tmp = new Sequence();
tmp.beginUpdate();
sequence.beginUpdate();
try
{
try
{
for (int t = 0; t < sizeT; t++)
{
for (int z = 0; z < sizeZ; z++)
{
tmp.setImage(t, z, sequence.getImage(t, z));
sequence.removeImage(t, z);
}
}
}
finally
{
tmp.endUpdate();
}
for (int t = 0; t < newSizeT; t++)
for (int z = 0; z < newSizeZ; z++)
sequence.setImage(t, z, AdjustZTHelper.getImage(tmp, t, z, newSizeZ, newSizeT, reverseOrder));
}
finally
{
sequence.endUpdate();
}
}
/**
* Build a new single channel sequence (grey) from the specified channel of the source sequence.
*
* @param source
* Source sequence
* @param channel
* Channel index to extract from the source sequence.
* @return Sequence
*/
public static Sequence extractChannel(Sequence source, int channel)
{
return extractChannels(source, channel);
}
/**
* @deprecated Use {@link #extractChannels(Sequence, int...)} instead.
*/
@Deprecated
public static Sequence extractChannels(Sequence source, List<Integer> channels)
{
final Sequence outSequence = new Sequence(OMEUtil.createOMEMetadata(source.getMetadata()));
outSequence.beginUpdate();
try
{
for (int t = 0; t < source.getSizeT(); t++)
for (int z = 0; z < source.getSizeZ(); z++)
outSequence.setImage(t, z, IcyBufferedImageUtil.extractChannels(source.getImage(t, z), channels));
}
finally
{
outSequence.endUpdate();
}
// sequence name
if (channels.size() > 1)
{
String s = "";
for (int i = 0; i < channels.size(); i++)
s += " " + channels.get(i).toString();
outSequence.setName(source.getName() + " (channels" + s + ")");
}
else if (channels.size() == 1)
outSequence.setName(source.getName() + " (" + source.getChannelName(channels.get(0).intValue()) + ")");
// channel name
int c = 0;
for (Integer i : channels)
{
outSequence.setChannelName(c, source.getChannelName(i.intValue()));
c++;
}
return outSequence;
}
/**
* Build a new sequence by extracting the specified channels from the source sequence.
*
* @param source
* Source sequence
* @param channels
* Channel indexes to extract from the source sequence.
* @return Sequence
*/
public static Sequence extractChannels(Sequence source, int... channels)
{
final Sequence outSequence = new Sequence(OMEUtil.createOMEMetadata(source.getMetadata()));
outSequence.beginUpdate();
try
{
for (int t = 0; t < source.getSizeT(); t++)
for (int z = 0; z < source.getSizeZ(); z++)
outSequence.setImage(t, z, IcyBufferedImageUtil.extractChannels(source.getImage(t, z), channels));
}
finally
{
outSequence.endUpdate();
}
final OMEXMLMetadataImpl metadata = outSequence.getMetadata();
// remove channel metadata
for (int ch = MetaDataUtil.getNumChannel(metadata, 0) - 1; ch >= 0; ch--)
{
boolean remove = true;
for (int i : channels)
{
if (i == ch)
{
remove = false;
break;
}
}
if (remove)
MetaDataUtil.removeChannel(metadata, 0, ch);
}
// sequence name
if (channels.length > 1)
{
String s = "";
for (int i = 0; i < channels.length; i++)
s += " " + channels[i];
outSequence.setName(source.getName() + " (channels" + s + ")");
}
else if (channels.length == 1)
outSequence.setName(source.getName() + " (" + source.getChannelName(channels[0]) + ")");
// copy channel name and colormap
int c = 0;
for (int channel : channels)
{
outSequence.setChannelName(c, source.getChannelName(channel));
outSequence.setDefaultColormap(c, source.getDefaultColorMap(channel), false);
c++;
}
return outSequence;
}
/**
* Build a new sequence by extracting the specified Z slice from the source sequence.
*
* @param source
* Source sequence
* @param z
* Slice index to extract from the source sequence.
* @return Sequence
*/
public static Sequence extractSlice(Sequence source, int z)
{
final Sequence outSequence = new Sequence(OMEUtil.createOMEMetadata(source.getMetadata()));
outSequence.beginUpdate();
try
{
for (int t = 0; t < source.getSizeT(); t++)
outSequence.setImage(t, 0, source.getImage(t, z));
}
finally
{
outSequence.endUpdate();
}
outSequence.setName(source.getName() + " (slice " + z + ")");
return outSequence;
}
/**
* Build a new sequence by extracting the specified T frame from the source sequence.
*
* @param source
* Source sequence
* @param t
* Frame index to extract from the source sequence.
* @return Sequence
*/
public static Sequence extractFrame(Sequence source, int t)
{
final Sequence outSequence = new Sequence(OMEUtil.createOMEMetadata(source.getMetadata()));
outSequence.beginUpdate();
try
{
for (int z = 0; z < source.getSizeZ(); z++)
outSequence.setImage(0, z, source.getImage(t, z));
}
finally
{
outSequence.endUpdate();
}
outSequence.setName(source.getName() + " (frame " + t + ")");
return outSequence;
}
/**
* Converts the source sequence to the specified data type.<br>
* This method returns a new sequence (the source sequence is not modified).
*
* @param source
* Source sequence to convert
* @param dataType
* Data type wanted
* @param rescale
* Indicate if we want to scale data value according to data (or data type) range
* @param useDataBounds
* Only used when <code>rescale</code> parameter is true.<br>
* Specify if we use the data bounds for rescaling instead of data type bounds.
* @return converted sequence
*/
public static Sequence convertToType(Sequence source, DataType dataType, boolean rescale, boolean useDataBounds)
{
if (!rescale)
return convertToType(source, dataType, null);
// convert with rescale
final double boundsSrc[];
final double boundsDst[] = dataType.getDefaultBounds();
if (useDataBounds)
boundsSrc = source.getChannelsGlobalBounds();
else
boundsSrc = source.getChannelsGlobalTypeBounds();
// use scaler to scale data
return convertToType(source, dataType,
new Scaler(boundsSrc[0], boundsSrc[1], boundsDst[0], boundsDst[1], false));
}
/**
* Converts the source sequence to the specified data type.<br>
* This method returns a new sequence (the source sequence is not modified).
*
* @param source
* Source sequence to convert
* @param dataType
* data type wanted
* @param rescale
* indicate if we want to scale data value according to data type range
* @return converted sequence
*/
public static Sequence convertToType(Sequence source, DataType dataType, boolean rescale)
{
return convertToType(source, dataType, rescale, false);
}
/**
* Converts the source sequence to the specified data type.<br>
* This method returns a new sequence (the source sequence is not modified).
*
* @param source
* Source sequence to convert
* @param dataType
* data type wanted.
* @param scaler
* scaler for scaling internal data during conversion.
* @return converted image
*/
public static Sequence convertToType(Sequence source, DataType dataType, Scaler scaler)
{
final Sequence output = new Sequence(OMEUtil.createOMEMetadata(source.getMetadata()));
output.beginUpdate();
try
{
for (int t = 0; t < source.getSizeT(); t++)
{
for (int z = 0; z < source.getSizeZ(); z++)
{
final IcyBufferedImage converted = IcyBufferedImageUtil.convertToType(source.getImage(t, z),
dataType, scaler);
// FIXME : why we did that ??
// this is not a good idea to force bounds when rescale = false
// set bounds manually for the converted image
// for (int c = 0; c < getSizeC(); c++)
// {
// converted.setComponentBounds(c, boundsDst);
// converted.setComponentUserBounds(c, boundsDst);
// }
output.setImage(t, z, converted);
}
}
output.setName(source.getName() + " (" + output.getDataType_() + ")");
}
finally
{
output.endUpdate();
}
return output;
}
/**
* Return a rotated version of the source sequence with specified parameters.
*
* @param source
* source image
* @param xOrigin
* X origin for the rotation
* @param yOrigin
* Y origin for the rotation
* @param angle
* rotation angle in radian
* @param filterType
* filter resampling method used
*/
public static Sequence rotate(Sequence source, double xOrigin, double yOrigin, double angle, FilterType filterType)
{
final int sizeT = source.getSizeT();
final int sizeZ = source.getSizeZ();
final Sequence result = new Sequence(OMEUtil.createOMEMetadata(source.getMetadata()));
result.beginUpdate();
try
{
for (int t = 0; t < sizeT; t++)
for (int z = 0; z < sizeZ; z++)
result.setImage(t, z,
IcyBufferedImageUtil.rotate(source.getImage(t, z), xOrigin, yOrigin, angle, filterType));
}
finally
{
result.endUpdate();
}
result.setName(source.getName() + " (rotated)");
return result;
}
/**
* Return a rotated version of the source Sequence with specified parameters.
*
* @param source
* source image
* @param angle
* rotation angle in radian
* @param filterType
* filter resampling method used
*/
public static Sequence rotate(Sequence source, double angle, FilterType filterType)
{
if (source == null)
return null;
return rotate(source, source.getSizeX() / 2d, source.getSizeY() / 2d, angle, filterType);
}
/**
* Return a rotated version of the source Sequence with specified parameters.
*
* @param source
* source image
* @param angle
* rotation angle in radian
*/
public static Sequence rotate(Sequence source, double angle)
{
if (source == null)
return null;
return rotate(source, source.getSizeX() / 2d, source.getSizeY() / 2d, angle, FilterType.BILINEAR);
}
/**
* Return a copy of the source sequence with specified size, alignment rules and filter type.
*
* @param source
* source sequence
* @param resizeContent
* indicate if content should be resized or not (empty area are 0 filled)
* @param xAlign
* horizontal image alignment (SwingConstants.LEFT / CENTER / RIGHT)<br>
* (used only if resizeContent is false)
* @param yAlign
* vertical image alignment (SwingConstants.TOP / CENTER / BOTTOM)<br>
* (used only if resizeContent is false)
* @param filterType
* filter method used for scale (used only if resizeContent is true)
*/
public static Sequence scale(Sequence source, int width, int height, boolean resizeContent, int xAlign, int yAlign,
FilterType filterType)
{
final int sizeT = source.getSizeT();
final int sizeZ = source.getSizeZ();
final Sequence result = new Sequence(OMEUtil.createOMEMetadata(source.getMetadata()));
result.beginUpdate();
try
{
for (int t = 0; t < sizeT; t++)
for (int z = 0; z < sizeZ; z++)
result.setImage(t, z, IcyBufferedImageUtil.scale(source.getImage(t, z), width, height,
resizeContent, xAlign, yAlign, filterType));
}
finally
{
result.endUpdate();
}
result.setName(source.getName() + " (resized)");
// content was resized ?
if (resizeContent)
{
final double sx = (double) source.getSizeX() / result.getSizeX();
final double sy = (double) source.getSizeY() / result.getSizeY();
// update pixel size
if ((sx != 0d) && !Double.isInfinite(sx))
result.setPixelSizeX(result.getPixelSizeX() * sx);
if ((sy != 0d) && !Double.isInfinite(sy))
result.setPixelSizeY(result.getPixelSizeY() * sy);
}
return result;
}
/**
* Return a copy of the sequence with specified size.<br>
* By default the FilterType.BILINEAR is used as filter method if resizeContent is true
*
* @param source
* source sequence
* @param resizeContent
* indicate if content should be resized or not (empty area are 0 filled)
* @param xAlign
* horizontal image alignment (SwingConstants.LEFT / CENTER / RIGHT)<br>
* (used only if resizeContent is false)
* @param yAlign
* vertical image alignment (SwingConstants.TOP / CENTER / BOTTOM)<br>
* (used only if resizeContent is false)
*/
public static Sequence scale(Sequence source, int width, int height, boolean resizeContent, int xAlign, int yAlign)
{
return scale(source, width, height, resizeContent, xAlign, yAlign, FilterType.BILINEAR);
}
/**
* Return a copy of the sequence with specified size.
*
* @param source
* source sequence
* @param filterType
* filter method used for scale (used only if resizeContent is true)
*/
public static Sequence scale(Sequence source, int width, int height, FilterType filterType)
{
return scale(source, width, height, true, 0, 0, filterType);
}
/**
* Return a copy of the sequence with specified size.<br>
* By default the FilterType.BILINEAR is used as filter method.
*/
public static Sequence scale(Sequence source, int width, int height)
{
return scale(source, width, height, FilterType.BILINEAR);
}
/**
* Creates a new sequence from the specified region of the source sequence.
*/
public static Sequence getSubSequence(Sequence source, Rectangle5D.Integer region)
{
final Sequence result = new Sequence(OMEUtil.createOMEMetadata(source.getMetadata()));
final Rectangle region2d = region.toRectangle2D().getBounds();
final int startZ;
final int endZ;
final int startT;
final int endT;
if (region.isInfiniteZ())
{
startZ = 0;
endZ = source.getSizeZ();
}
else
{
startZ = Math.max(0, region.z);
endZ = Math.min(source.getSizeZ(), region.z + region.sizeZ);
}
if (region.isInfiniteT())
{
startT = 0;
endT = source.getSizeT();
}
else
{
startT = Math.max(0, region.t);
endT = Math.min(source.getSizeT(), region.t + region.sizeT);
}
result.beginUpdate();
try
{
for (int t = startT; t < endT; t++)
{
for (int z = startZ; z < endZ; z++)
{
final IcyBufferedImage img = source.getImage(t, z);
if (img != null)
result.setImage(t - startT, z - startZ,
IcyBufferedImageUtil.getSubImage(img, region2d, region.c, region.sizeC));
else
result.setImage(t - startT, z - startZ, null);
}
}
}
finally
{
result.endUpdate();
}
result.setName(source.getName() + " (crop)");
return result;
}
/**
* @deprecated Use {@link #getSubSequence(Sequence, icy.type.rectangle.Rectangle5D.Integer)}
* instead.
*/
@Deprecated
public static Sequence getSubSequence(Sequence source, int startX, int startY, int startC, int startZ, int startT,
int sizeX, int sizeY, int sizeC, int sizeZ, int sizeT)
{
return getSubSequence(source, new Rectangle5D.Integer(startX, startY, startZ, startT, startC, sizeX, sizeY,
sizeZ, sizeT, sizeC));
}
/**
* @deprecated Use {@link #getSubSequence(Sequence, icy.type.rectangle.Rectangle5D.Integer)}
* instead.
*/
@Deprecated
public static Sequence getSubSequence(Sequence source, int startX, int startY, int startZ, int startT, int sizeX,
int sizeY, int sizeZ, int sizeT)
{
return getSubSequence(source, startX, startY, 0, startZ, startT, sizeX, sizeY, source.getSizeC(), sizeZ, sizeT);
}
/**
* Creates a new sequence which is a sub part of the source sequence defined by the specified
* {@link ROI} bounds.<br>
*
* @param source
* the source sequence
* @param roi
* used to define to region to retain.
* @param nullValue
* the returned sequence is created by using the ROI rectangular bounds.<br>
* if <code>nullValue</code> is different of <code>Double.NaN</code> then any pixel
* outside the ROI region will be set to <code>nullValue</code>
*/
public static Sequence getSubSequence(Sequence source, ROI roi, double nullValue)
{
final Rectangle5D.Integer bounds = roi.getBounds5D().toInteger();
final Sequence result = getSubSequence(source, bounds);
// use null value ?
if (!Double.isNaN(nullValue))
{
final int offX = (bounds.x == Integer.MIN_VALUE) ? 0 : (int) bounds.x;
final int offY = (bounds.y == Integer.MIN_VALUE) ? 0 : (int) bounds.y;
final int offZ = (bounds.z == Integer.MIN_VALUE) ? 0 : (int) bounds.z;
final int offT = (bounds.t == Integer.MIN_VALUE) ? 0 : (int) bounds.t;
final int offC = (bounds.c == Integer.MIN_VALUE) ? 0 : (int) bounds.c;
final int sizeX = result.getSizeX();
final int sizeY = result.getSizeY();
final int sizeZ = result.getSizeZ();
final int sizeT = result.getSizeT();
final int sizeC = result.getSizeC();
final DataType dataType = result.getDataType_();
for (int t = 0; t < sizeT; t++)
{
for (int z = 0; z < sizeZ; z++)
{
for (int c = 0; c < sizeC; c++)
{
final BooleanMask2D mask = roi.getBooleanMask2D(z + offZ, t + offT, c + offC, false);
final Object data = result.getDataXY(t, z, c);
int offset = 0;
for (int y = 0; y < sizeY; y++)
for (int x = 0; x < sizeX; x++, offset++)
if (!mask.contains(x + offX, y + offY))
Array1DUtil.setValue(data, offset, dataType, nullValue);
}
}
}
result.dataChanged();
}
return result;
}
/**
* Creates a new sequence which is a sub part of the source sequence defined by the specified
* {@link ROI} bounds.
*/
public static Sequence getSubSequence(Sequence source, ROI roi)
{
return getSubSequence(source, roi, Double.NaN);
}
/**
* Creates and return a copy of the sequence.
*
* @param source
* the source sequence to copy
* @param copyROI
* Copy the ROI from source sequence
* @param copyOverlay
* Copy the Overlay from source sequence
* @param nameSuffix
* add the suffix <i>" (copy)"</i> to the new Sequence name to distinguish it
*/
public static Sequence getCopy(Sequence source, boolean copyROI, boolean copyOverlay, boolean nameSuffix)
{
final Sequence result = new Sequence(OMEUtil.createOMEMetadata(source.getMetadata()));
result.beginUpdate();
try
{
result.copyDataFrom(source);
if (copyROI)
{
for (ROI roi : source.getROIs())
result.addROI(roi);
}
if (copyOverlay)
{
for (Overlay overlay : source.getOverlays())
result.addOverlay(overlay);
}
if (nameSuffix)
result.setName(source.getName() + " (copy)");
}
finally
{
result.endUpdate();
}
return result;
}
/**
* Creates and return a copy of the sequence.<br>
* Note that only data and metadata are copied, overlays and ROIs are not preserved.
*/
public static Sequence getCopy(Sequence source)
{
return getCopy(source, false, false, true);
}
/**
* Convert the specified sequence to gray sequence (single channel)
*/
public static Sequence toGray(Sequence source)
{
return convertColor(source, BufferedImage.TYPE_BYTE_GRAY, null);
}
/**
* Convert the specified sequence to RGB sequence (3 channels)
*/
public static Sequence toRGB(Sequence source)
{
return convertColor(source, BufferedImage.TYPE_INT_RGB, null);
}
/**
* Convert the specified sequence to ARGB sequence (4 channels)
*/
public static Sequence toARGB(Sequence source)
{
return convertColor(source, BufferedImage.TYPE_INT_ARGB, null);
}
/**
* Do color conversion of the specified {@link Sequence} into the specified type.<br>
* The resulting Sequence will have 4, 3 or 1 channel(s) depending the selected type.
*
* @param source
* source sequence
* @param imageType
* wanted image type, only the following is accepted :<br>
* BufferedImage.TYPE_INT_ARGB (4 channels)<br>
* BufferedImage.TYPE_INT_RGB (3 channels)<br>
* BufferedImage.TYPE_BYTE_GRAY (1 channel)<br>
* @param lut
* lut used for color calculation (source sequence lut is used if null)
*/
public static Sequence convertColor(Sequence source, int imageType, LUT lut)
{
final Sequence result = new Sequence(OMEUtil.createOMEMetadata(source.getMetadata()));
// image receiver
final BufferedImage imgOut = new BufferedImage(source.getSizeX(), source.getSizeY(), imageType);
result.beginUpdate();
try
{
for (int t = 0; t < source.getSizeT(); t++)
for (int z = 0; z < source.getSizeZ(); z++)
result.setImage(t, z, IcyBufferedImageUtil.toBufferedImage(source.getImage(t, z), imgOut, lut));
// rename channels and set final name
switch (imageType)
{
default:
case BufferedImage.TYPE_INT_ARGB:
result.setChannelName(0, "red");
result.setChannelName(1, "green");
result.setChannelName(2, "blue");
result.setChannelName(3, "alpha");
result.setName(source.getName() + " (ARGB rendering)");
break;
case BufferedImage.TYPE_INT_RGB:
result.setChannelName(0, "red");
result.setChannelName(1, "green");
result.setChannelName(2, "blue");
result.setName(source.getName() + " (RGB rendering)");
break;
case BufferedImage.TYPE_BYTE_GRAY:
result.setChannelName(0, "gray");
result.setName(source.getName() + " (gray rendering)");
break;
}
}
finally
{
result.endUpdate();
}
return result;
}
}
| false | false | null | null |
diff --git a/src/de/typology/trainers/LuceneNGramIndexer.java b/src/de/typology/trainers/LuceneNGramIndexer.java
index 4007d875..5e3f1463 100644
--- a/src/de/typology/trainers/LuceneNGramIndexer.java
+++ b/src/de/typology/trainers/LuceneNGramIndexer.java
@@ -1,133 +1,132 @@
package de.typology.trainers;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.core.KeywordAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FloatField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import de.typology.utils.Config;
import de.typology.utils.IOHelper;
/**
*
* @author rpickhardt
*
*/
public class LuceneNGramIndexer {
/**
* @param args
*/
public static void main(String[] args) throws IOException {
}
public static void run(String normalizedNGrams, String indexNGrams)
throws NumberFormatException, IOException {
long startTime = System.currentTimeMillis();
for (int nGramType = 2; nGramType < 6; nGramType++) {
LuceneNGramIndexer indexer = new LuceneNGramIndexer(indexNGrams
+ nGramType);
indexer.index(normalizedNGrams + nGramType + "/");
indexer.close();
}
long endTime = System.currentTimeMillis();
IOHelper.strongLog((endTime - startTime) / 1000
+ " seconds for indexing " + Config.get().normalizedNGrams);
}
private BufferedReader reader;
private IndexWriter writer;
private String line;
private String[] lineSplit;
private Float edgeCount;
public LuceneNGramIndexer(String nGramDir) throws IOException {
Directory dir = FSDirectory.open(new File(nGramDir));
// TODO: change Analyzer since this one makes stuff case insensitive...
// also change this in quering: see important note:
// http://oak.cs.ucla.edu/cs144/projects/lucene/index.html in chapter
// 2.0
// http://stackoverflow.com/questions/2487736/lucene-case-sensitive-insensitive-search
// Analyzer analyzer = new TypologyAnalyzer(Version.LUCENE_40);
Analyzer analyzer = new KeywordAnalyzer();
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_40,
analyzer);
config.setOpenMode(OpenMode.CREATE);
this.writer = new IndexWriter(dir, config);
}
public void close() throws IOException {
this.writer.close();
}
/**
* Given a directory containing typology edge files, index() builds a Lucene
* index. See getDocument() for document structure.
*
* @param dataDir
* @param filter
* @return
* @throws NumberFormatException
* @throws IOException
*/
public int index(String dataDir) throws NumberFormatException, IOException {
ArrayList<File> files = IOHelper.getDirectory(new File(dataDir));
for (File file : files) {
if (file.getName().contains("distribution")) {
IOHelper.log("skipping " + file.getAbsolutePath());
continue;
}
IOHelper.log("indexing " + file.getAbsolutePath());
this.indexFile(file);
}
return files.size();
}
private int indexFile(File file) throws NumberFormatException, IOException {
this.reader = IOHelper.openReadFile(file.getAbsolutePath());
int docCount = 0;
while ((this.line = this.reader.readLine()) != null) {
this.lineSplit = this.line.split("\t#");
if (this.lineSplit.length != 2) {
IOHelper.strongLog("can;t index line split is incorrectly"
+ this.lineSplit.length);
continue;
}
this.edgeCount = Float
- .parseFloat(this.lineSplit[this.lineSplit.length - 1]
- .substring(1));
+ .parseFloat(this.lineSplit[this.lineSplit.length - 1]);
String tmp = this.lineSplit[0].replace('\t', ' ');
this.lineSplit = tmp.split(" ");
String lastword = this.lineSplit[this.lineSplit.length - 1];
tmp = tmp.substring(0, tmp.length() - (lastword.length() + 1));
// System.out.println(tmp + " " + lastword);
Document document = this.getDocument(tmp, lastword, this.edgeCount);
this.writer.addDocument(document);
docCount++;
}
return docCount;
}
private Document getDocument(String source, String target, Float count) {
Document document = new Document();
document.add(new StringField("src", source, Field.Store.NO));
document.add(new StringField("tgt", target, Field.Store.YES));
document.add(new FloatField("cnt", count, Field.Store.YES));
return document;
}
}
| true | true | private int indexFile(File file) throws NumberFormatException, IOException {
this.reader = IOHelper.openReadFile(file.getAbsolutePath());
int docCount = 0;
while ((this.line = this.reader.readLine()) != null) {
this.lineSplit = this.line.split("\t#");
if (this.lineSplit.length != 2) {
IOHelper.strongLog("can;t index line split is incorrectly"
+ this.lineSplit.length);
continue;
}
this.edgeCount = Float
.parseFloat(this.lineSplit[this.lineSplit.length - 1]
.substring(1));
String tmp = this.lineSplit[0].replace('\t', ' ');
this.lineSplit = tmp.split(" ");
String lastword = this.lineSplit[this.lineSplit.length - 1];
tmp = tmp.substring(0, tmp.length() - (lastword.length() + 1));
// System.out.println(tmp + " " + lastword);
Document document = this.getDocument(tmp, lastword, this.edgeCount);
this.writer.addDocument(document);
docCount++;
}
return docCount;
}
| private int indexFile(File file) throws NumberFormatException, IOException {
this.reader = IOHelper.openReadFile(file.getAbsolutePath());
int docCount = 0;
while ((this.line = this.reader.readLine()) != null) {
this.lineSplit = this.line.split("\t#");
if (this.lineSplit.length != 2) {
IOHelper.strongLog("can;t index line split is incorrectly"
+ this.lineSplit.length);
continue;
}
this.edgeCount = Float
.parseFloat(this.lineSplit[this.lineSplit.length - 1]);
String tmp = this.lineSplit[0].replace('\t', ' ');
this.lineSplit = tmp.split(" ");
String lastword = this.lineSplit[this.lineSplit.length - 1];
tmp = tmp.substring(0, tmp.length() - (lastword.length() + 1));
// System.out.println(tmp + " " + lastword);
Document document = this.getDocument(tmp, lastword, this.edgeCount);
this.writer.addDocument(document);
docCount++;
}
return docCount;
}
|
diff --git a/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java b/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java
index 39c81e4..b4ad10b 100644
--- a/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java
+++ b/src/de/_13ducks/cor/game/server/movement/ServerBehaviourMove.java
@@ -1,687 +1,687 @@
/*
* Copyright 2008, 2009, 2010, 2011:
* Tobias Fleig (tfg[AT]online[DOT]de),
* Michael Haas (mekhar[AT]gmx[DOT]de),
* Johannes Kattinger (johanneskattinger[AT]gmx[DOT]de)
*
* - All rights reserved -
*
*
* This file is part of Centuries of Rage.
*
* Centuries of Rage 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.
*
* Centuries of Rage 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 Centuries of Rage. If not, see <http://www.gnu.org/licenses/>.
*
*/
package de._13ducks.cor.game.server.movement;
import de._13ducks.cor.game.FloatingPointPosition;
import de._13ducks.cor.game.GameObject;
import de._13ducks.cor.game.Moveable;
import de._13ducks.cor.game.SimplePosition;
import de._13ducks.cor.game.server.Server;
import de._13ducks.cor.networks.server.behaviour.ServerBehaviour;
import de._13ducks.cor.game.server.ServerCore;
import de._13ducks.cor.map.fastfindgrid.Traceable;
import java.util.List;
import org.newdawn.slick.geom.Circle;
import org.newdawn.slick.geom.Polygon;
/**
* Lowlevel-Movemanagement
*
* Verwaltet die reine Bewegung einer einzelnen Einheit.
* Kümmert sich nicht weiter um Formationen/Kampf oder ähnliches.
* Erhält vom übergeordneten MidLevelManager einen Richtungsvektor und eine Zielkoordinate.
* Läuft dann dort hin. Tut sonst nichts.
* Hat exklusive Kontrolle über die Einheitenposition.
* Weigert sich, sich schneller als die maximale Einheitengeschwindigkeit zu bewegen.
* Dadurch werden Sprünge verhindert.
*
* Wenn eine Kollision festgestellt wird, wird der überliegende GroupManager gefragt was zu tun ist.
* Der GroupManager entscheidet dann über die Ausweichroute oder lässt uns warten.
*/
public class ServerBehaviourMove extends ServerBehaviour {
private Moveable caster2;
private Traceable caster3;
private SimplePosition target;
/**
* Mittelpunkt für arc-Bewegungen
*/
private SimplePosition around;
/**
* Aktuelle Bewegung eine Kurve?
*/
private boolean arc;
/**
* Richtung der Kurve (true = Plus)
*/
private boolean arcDirection;
/**
* Wie weit (im Bogenmaß) wir auf dem Kreis laufen müssen
*/
private double tethaDist;
/**
* Wie weit wir (im Bogenmaß) auf dem Kreis schon gelaufen sind
*/
private double movedTetha;
private double speed;
private boolean stopUnit = false;
private long lastTick;
private SimplePosition clientTarget;
private MovementMap moveMap;
private GroupMember pathManager;
/**
* Die Systemzeit zu dem Zeitpunkt, an dem mit dem Warten begonnen wurde
*/
private long waitStartTime;
/**
* Gibt an, ob gerade gewartet wird
* (z.B. wenn etwas im Weg steht und man wartet bis es den Weg freimacht)
*/
private boolean wait;
/**
* Die Zeit, die gewartet wird (in Nanosekunden) (eine milliarde ist eine sekunde)
*/
private static final long waitTime = 3000000000l;
/**
* Eine minimale Distanz, die Einheiten beim Aufstellen wegen einer Kollision berücksichtigen.
* Damit wird verhindert, dass aufgrund von Rundungsfehlern Kolision auf ursprünlich als frei
* eingestuften Flächen berechnet wird.
*/
public static final double MIN_DISTANCE = 0.1;
/**
* Ein simples Flag, das nach dem Kollisionstest gesetzt ist.
*/
private boolean colliding = false;
/**
* Zeigt nach dem Kollisionstest auf das letzte (kollidierende) Objekt.
*/
private Moveable lastObstacle;
/**
* Wegen wem wir zuletzt warten mussten.
*/
private Moveable waitFor;
public ServerBehaviourMove(ServerCore.InnerServer newinner, GameObject caster1, Moveable caster2, Traceable caster3, MovementMap moveMap) {
super(newinner, caster1, 1, 20, true);
this.caster2 = caster2;
this.caster3 = caster3;
this.moveMap = moveMap;
}
@Override
public void activate() {
active = true;
trigger();
}
@Override
public void deactivate() {
active = false;
}
@Override
public synchronized void execute() {
// Auto-Ende:
if (target == null || speed <= 0) {
deactivate();
return;
}
// Wir laufen also.
// Aktuelle Position berechnen:
// Erstmal default-Berechnung für gerades laufen
FloatingPointPosition oldPos = caster2.getPrecisePosition();
long ticktime = System.nanoTime();
Vector vec = target.toFPP().subtract(oldPos).toVector();
vec.normalizeMe();
vec.multiplyMe((ticktime - lastTick) / 1000000000.0 * speed);
FloatingPointPosition newpos = vec.toFPP().add(oldPos);
if (arc) {
// Kreisbewegung berechnen:
double rad = Math.sqrt((oldPos.x() - around.x()) * (oldPos.x() - around.x()) + (oldPos.y() - around.y()) * (oldPos.y() - around.y()));
double tetha = Math.atan2(oldPos.y() - around.y(), oldPos.x() - around.x());
double delta = vec.length(); // Wie weit wir auf diesem Kreis laufen
if (!arcDirection) { // Falls Richtung negativ delta invertieren
delta *= -1;
}
double newTetha = ((tetha * rad) + delta) / rad; // Strahlensatz, u = 2*PI*r
movedTetha += Math.abs(newTetha - tetha);
// Über-/Unterläufe behandeln:
if (newTetha > Math.PI) {
newTetha = -2 * Math.PI + newTetha;
} else if (newTetha < -Math.PI) {
newTetha = 2 * Math.PI + newTetha;
}
Vector newPvec = new Vector(Math.cos(newTetha), Math.sin(newTetha));
newPvec = newPvec.multiply(rad);
newpos = around.toVector().add(newPvec).toFPP();
}
// Ob die Kollision später noch geprüft werden muss. Kann durch ein Weiterlaufen nach warten überschrieben werden.
boolean checkCollision = true;
// Wir sind im Warten-Modus. Jetzt also testen, ob wir zur nächsten Position können
if (wait) {
// Testen, ob wir schon weiterlaufen können:
// Echtzeitkollision:
newpos = checkAndMaxMove(oldPos, newpos);
if (colliding) {
waitFor = lastObstacle;
if (caster2.getMidLevelManager().stayWaiting(caster2, waitFor)) {
// Immer noch Kollision
if (System.nanoTime() - waitStartTime < waitTime) {
// Das ist ok, einfach weiter warten
lastTick = System.nanoTime();
return;
} else {
// Wartezeit abgelaufen
wait = false;
// Wir stehen schon, der Client auch --> nichts weiter zu tun.
target = null;
deactivate();
System.out.println("STOP waiting: " + caster2);
return;
}
} else {
// Es wurde eine Umleitung eingestellt
wait = false;
trigger();
return;
}
} else {
// Nichtmehr weiter warten - Bewegung wieder starten
System.out.println("GO! Weiter mit " + caster2 + " " + newpos + " nach " + target);
wait = false;
checkCollision = false;
}
}
if (!target.equals(clientTarget) && !stopUnit) {
// An Client senden
rgi.netctrl.broadcastMoveVec(caster2.getNetID(), target.toFPP(), speed);
clientTarget = target.toFPP();
}
if (checkCollision) {
// Zu laufenden Weg auf Kollision prüfen
newpos = checkAndMaxMove(oldPos, newpos);
if (!stopUnit && colliding) {
// Kollision. Gruppenmanager muss entscheiden, ob wir warten oder ne Alternativroute suchen.
wait = this.caster2.getMidLevelManager().collisionDetected(this.caster2, lastObstacle);
if (wait) {
waitStartTime = System.nanoTime();
waitFor = lastObstacle;
// Spezielle Stopfunktion: (hält den Client in einem Pseudozustand)
// Der Client muss das auch mitbekommen
rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY())));
setMoveable(oldPos, newpos);
clientTarget = null;
System.out.println("WAIT-COLLISION " + caster2 + " with " + lastObstacle + " stop at " + newpos);
return; // Nicht weiter ausführen!
} else {
// Nochmal laufen, wir haben ein neues Ziel!
trigger();
return;
}
}
}
// Ziel schon erreicht?
Vector nextVec = target.toFPP().subtract(newpos).toVector();
boolean arcDone = false;
if (arc) {
arcDone = movedTetha >= tethaDist;
}
if (((!arc && vec.isOpposite(nextVec)) || arcDone || newpos.equals(target)) && !stopUnit) {
// Zielvektor erreicht
// Wir sind warscheinlich drüber - egal einfach auf dem Ziel halten.
setMoveable(oldPos, target.toFPP());
// Neuen Wegpunkt anfordern:
if (!pathManager.reachedTarget(caster2)) {
// Wenn das false gibt, gibts keine weiteren, dann hier halten.
target = null;
stopUnit = false; // Es ist wohl besser auf dem Ziel zu stoppen als kurz dahinter!
deactivate();
}
} else {
// Sofort stoppen?
if (stopUnit) {
// Der Client muss das auch mitbekommen
rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 24, caster2.getNetID(), 0, Float.floatToIntBits((float) newpos.getfX()), Float.floatToIntBits((float) newpos.getfY())));
System.out.println("MANUSTOP: " + caster2 + " at " + newpos);
setMoveable(oldPos, newpos);
target = null;
stopUnit = false;
deactivate();
} else {
// Weiterlaufen
setMoveable(oldPos, newpos);
lastTick = System.nanoTime();
}
}
}
private void setMoveable(FloatingPointPosition from, FloatingPointPosition to) {
caster2.setMainPosition(to);
// Neuer Sektor?
while (pathManager.nextSectorBorder() != null && pathManager.nextSectorBorder().sidesDiffer(from, to)) {
// Ja, alten löschen und neuen setzen!
SectorChangingEdge edge = pathManager.borderCrossed();
caster2.setMyPoly(edge.getNext(caster2.getMyPoly()));
}
// Schnellsuchraster aktualisieren:
caster3.setCell(Server.getInnerServer().netmap.getFastFindGrid().getNewCell(caster3));
}
@Override
public void gotSignal(byte[] packet) {
}
@Override
public void pause() {
caster2.pause();
}
@Override
public void unpause() {
caster2.unpause();
}
/**
* Setzt den Zielvektor für diese Einheit.
* Es wird nicht untersucht, ob das Ziel in irgendeiner Weise ok ist, die Einheit beginnt sofort loszulaufen.
* In der Regel sollte noch eine Geschwindigkeit angegeben werden.
* Wehrt sich gegen nicht existente Ziele.
* Falls arc true ist, werden arcDirection und arcCenter ausgewertet, sonst nicht.
* @param pos die Zielposition
* @param arc ob das Ziel auf einer Kurve angesteuert werden soll (true)
* @param arcDirection Richtung der Kurve (true - Bogenmaß-Plusrichtung)
* @param arcCenter um welchen Punkt gedreht werden soll.
*/
public synchronized void setTargetVector(SimplePosition pos, boolean arc, boolean arcDirection, SimplePosition arcCenter) {
if (pos == null) {
throw new IllegalArgumentException("Cannot send " + caster2 + " to null (" + arc + ")");
}
if (!pos.toVector().isValid()) {
throw new IllegalArgumentException("Cannot send " + caster2 + " to invalid position (" + arc + ")");
}
target = pos;
lastTick = System.nanoTime();
clientTarget = Vector.ZERO;
this.arc = arc;
this.arcDirection = arcDirection;
this.around = arcCenter;
this.movedTetha = 0;
if (arc) {
// Länge des Kreissegments berechnen
double startTetha = Math.atan2(caster2.getPrecisePosition().y() - around.y(), caster2.getPrecisePosition().x() - around.x());
double targetTetha = Math.atan2(target.y() - around.y(), target.x() - around.x());
if (arcDirection) {
tethaDist = targetTetha - startTetha;
} else {
tethaDist = startTetha - targetTetha;
}
if (tethaDist < 0) {
tethaDist = 2 * Math.PI + tethaDist;
}
}
activate();
}
/**
* Setzt den Zielvektor und die Geschwindigkeit und startet die Bewegung sofort.
* @param pos die Zielposition
* @param speed die Geschwindigkeit
*/
public synchronized void setTargetVector(SimplePosition pos, double speed, boolean arc, boolean arcDirection, SimplePosition arcCenter) {
changeSpeed(speed);
setTargetVector(pos, arc, arcDirection, arcCenter);
}
/**
* Ändert die Geschwindigkeit während des Laufens.
* Speed wird verkleinert, wenn der Wert über dem Einheiten-Maximum liegen würde
* @param speed Die Einheitengeschwindigkeit
*/
public synchronized void changeSpeed(double speed) {
if (speed > 0 && speed <= caster2.getSpeed()) {
this.speed = speed;
}
trigger();
}
public boolean isMoving() {
return target != null;
}
/**
* Stoppt die Einheit innerhalb eines Ticks.
*/
public synchronized void stopImmediately() {
stopUnit = true;
trigger();
}
/**
* Findet einen Sektor, den beide Knoten gemeinsam haben
* @param n1 Knoten 1
* @param n2 Knoten 2
*/
private FreePolygon commonSector(Node n1, Node n2) {
for (FreePolygon poly : n1.getPolygons()) {
if (n2.getPolygons().contains(poly)) {
return poly;
}
}
return null;
}
/**
* Berechnet den Winkel zwischen zwei Vektoren
* @param vector_1
* @param vector_2
* @return
*/
public double getAngle(FloatingPointPosition vector_1, FloatingPointPosition vector_2) {
double scalar = ((vector_1.getfX() * vector_2.getfX()) + (vector_1.getfY() * vector_2.getfY()));
double vector_1_lenght = Math.sqrt((vector_1.getfX() * vector_1.getfX()) + vector_2.getfY() * vector_1.getfY());
double vector_2_lenght = Math.sqrt((vector_2.getfX() * vector_2.getfX()) + vector_2.getfY() * vector_2.getfY());
double lenght = vector_1_lenght * vector_2_lenght;
double angle = Math.acos((scalar / lenght));
return angle;
}
/**
* Untersucht die gegebene Route auf Echtzeitkollision.
* Sollte alles frei sein, wird to zurückgegeben.
* Ansonsten gibts eine neue Position, bis zu der problemlos gelaufen werden kann.
* Im schlimmsten Fall ist dies die from-Position, die frei sein MUSS!
* @param from von wo wir uns losbewegen
* @param to wohin wir laufen
* @return FloatingPointPosition bis wohin man laufen kann.
*/
private FloatingPointPosition checkAndMaxMove(FloatingPointPosition from, FloatingPointPosition to) {
// Zuallererst: Wir dürfen nicht über das Ziel hinaus laufen:
if (!arc) {
Vector oldtargetVec = new Vector(target.x() - from.x(), target.y() - from.y());
Vector newtargetVec = new Vector(target.x() - to.x(), target.y() - to.y());
if (oldtargetVec.isOpposite(newtargetVec)) {
// Achtung, zu weit!
to = target.toFPP();
}
} else {
// Arc-Bewegung begrenzen:
if (movedTetha >= tethaDist) {
to = target.toFPP();
}
}
// Zurücksetzen
lastObstacle = null;
colliding = false;
List<Moveable> possibleCollisions = moveMap.moversAroundPoint(caster2.getPrecisePosition(), caster2.getRadius() + 10, caster2.getMyPoly());
// Uns selber ignorieren
possibleCollisions.remove(caster2);
// Freies Gebiet markieren:
Vector ortho = new Vector(to.getfY() - from.getfY(), from.getfX() - to.getfX()); // 90 Grad verdreht (y, -x)
ortho.normalizeMe();
ortho.multiplyMe(caster2.getRadius());
Vector fromv = from.toVector();
Vector tov = to.toVector();
Polygon poly = new Polygon();
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
poly.addPoint((float) fromv.add(ortho.getInverted()).x(), (float) fromv.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho.getInverted()).x(), (float) tov.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho).x(), (float) tov.add(ortho).y());
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
for (Moveable t : possibleCollisions) {
float radius = (float) (t.getRadius() + MIN_DISTANCE / 2);
Circle c = new Circle((float) t.getPrecisePosition().x(), (float) t.getPrecisePosition().y(), radius); //Das getUnit ist ugly!
boolean arcCol = collidesOnArc(t, around, radius, from, to);
// Die Kollisionsbedingungen: Schnitt mit Begrenzungslinien, liegt innerhalb des Testpolygons, liegt zu nah am Ziel
// Die ersten beiden Bedingungen gelten nur für nicht-arc-Bewegungen!
// Die letzte gilt dafür nur für arc-Bewegungen
if (!arc && (poly.intersects(c)) || (!arc && poly.includes(c.getCenterX(), c.getCenterY())) || to.getDistance(t.getPrecisePosition()) < caster2.getRadius() + radius || (arc && arcCol)) {
//System.out.println("COL! with: " + t + " at " + t.getPrecisePosition() + " (dist: " + to.getDistance(t.getPrecisePosition()) + ") on route to " + target + " critical point is " + to);
// Kollision!
if (!arc) {
// Jetzt muss poly verkleinert werden.
// Dazu muss die Zielposition to auf der Strecke von from nach to so weit wie notwendig nach hinten verschoben werden.
// Notwendiger Abstand zur gefundenen Kollision t
float distanceToObstacle = (float) (this.caster2.getRadius() + radius + MIN_DISTANCE / 2);
// Vector, der vom start zum Ziel der Bewegung zeigt.
Vector dirVec = new Vector(to.getfX() - from.getfX(), to.getfY() - from.getfY());
// 90 Grad dazu
Vector origin = new Vector(-dirVec.getY(), dirVec.getX());
// Strecke vom Hinderniss in 90-Grad-Richtung
Edge edge = new Edge(t.getPrecisePosition().toNode(), t.getPrecisePosition().add(origin.toFPP()).toNode());
// Strecke zwischen start und ziel
Edge edge2 = new Edge(caster2.getPrecisePosition().toNode(), caster2.getPrecisePosition().add(dirVec.toFPP()).toNode());
// Schnittpunkt
SimplePosition p = edge.endlessIntersection(edge2);
if (p == null) {
System.out.println("ERROR: " + caster2 + " " + edge + " " + edge2 + " " + t.getPrecisePosition() + " " + origin + " " + dirVec + " " + distanceToObstacle);
}
// Abstand vom Hinderniss zur Strecke edge2
double distance = t.getPrecisePosition().getDistance(p.toFPP());
// Abstand vom Punkt auf edge2 zu freigegebenem Punkt
double b = Math.sqrt((distanceToObstacle * distanceToObstacle) - (distance * distance));
// Auf der Strecke weit genug zurück gehen:
FloatingPointPosition nextnewpos = p.toVector().add(dirVec.getInverted().normalize().multiply(b)).toFPP();
// Zurückgegangenes Stück analysieren
if (new Vector(nextnewpos.getfX() - fromv.x(), nextnewpos.getfY() - fromv.y()).isOpposite(dirVec)) {
// Ganz zurück setzen. Dann muss man nicht weiter suchen, die ganze Route ist hoffnungslos blockiert
colliding = true;
lastObstacle = t;
return from;
}
// Hier gibt es keine Kollision mehr.
// poly neu bauen:
to = nextnewpos;
tov = nextnewpos.toVector();
poly = new Polygon();
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
poly.addPoint((float) fromv.add(ortho.getInverted()).x(), (float) fromv.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho.getInverted()).x(), (float) tov.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho).x(), (float) tov.add(ortho).y());
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
} else {
// to auf dem Laufkreis nach hinten verschieben.
Vector obst = t.getPrecisePosition().toVector();
// Als erstes die Schnittpunkte der beiden Kreise bestimmmen
double moveRad = from.toFPP().getDistance(around.toFPP());
SimplePosition[] intersections = MathUtil.circleCircleIntersection(new Circle((float) obst.getX(), (float) obst.getY(), (float) (radius + caster2.getRadius())), new Circle((float) around.x(), (float) around.y(), (float) moveRad));
SimplePosition s1 = intersections[0];
- SimplePosition s2 = intersections[0];
+ SimplePosition s2 = intersections[1];
// Ausbrüten, ob s1 oder s2 der richtige ist:
SimplePosition newPosVec = null;
double fromTetha = Math.atan2(from.y() - around.y(), from.x() - around.x());
if (fromTetha < 0) {
fromTetha += 2 * Math.PI;
}
double s1tetha = Math.atan2(s1.y() - around.y(), s1.x() - around.x());
if (s1tetha < 0) {
s1tetha += 2 * Math.PI;
}
double s2tetha = Math.atan2(s2.y() - around.y(), s2.x() - around.x());
if (s2tetha < 0) {
s2tetha += 2 * Math.PI;
}
if (s1tetha < fromTetha) {
s1tetha += 2 * Math.PI;
}
if (s2tetha < fromTetha) {
s2tetha += 2 * Math.PI;
}
if (s1tetha < s2tetha) {
if (arcDirection) {
newPosVec = s1;
} else {
newPosVec = s2;
}
} else {
if (arcDirection) {
newPosVec = s2;
} else {
newPosVec = s1;
}
}
if (!newPosVec.toVector().isValid()) {
throw new RuntimeException();
}
to = newPosVec.toFPP();
tov = to.toVector();
}
colliding = true;
lastObstacle = t;
// Falls wir so weit zurück mussten, dass es gar netmehr weiter geht:
if (from.equals(to)) {
return from;
}
}
}
// Jetzt wurde alles oft genug verschoben um definitiv keine Kollision mehr zu haben.
// Bis hierhin die Route also freigeben:
return to;
}
/**
* Hiermit lässt sich herausfinden, ob dieser mover gerade wartet, weil jemand im Weg steht.
* @return
*/
boolean isWaiting() {
return wait;
}
/**
* Hiermit lässt siche herausfinden, wer momentan primär einem Weiterlaufen
* im Weg steht.
* @return Das derzeitige, primäre Hinderniss
*/
Moveable getWaitFor() {
return waitFor;
}
/**
* @return the pathManager
*/
GroupMember getPathManager() {
return pathManager;
}
/**
* @param pathManager the pathManager to set
*/
void setPathManager(GroupMember pathManager) {
this.pathManager = pathManager;
}
/**
* Findet heraus, ob das gegebenen Moveable auf dem gegebenen zu laufenden Abschnitt liegt,
* also eine Kollision darstellt.
* @param t
* @return true, wenn Kollision
*/
private boolean collidesOnArc(Moveable t, SimplePosition around, double colRadius, SimplePosition from, SimplePosition to) {
if (!arc) {
return false;
}
// Muss in +arc-Richtung erfolgen, notfalls start und Ziel tauschen
if (!arcDirection) {
SimplePosition back = from;
from = to;
to = back;
}
// Zuerst auf Nähe des gesamten Kreissegments testen
double dist = t.getPrecisePosition().getDistance(around.toFPP());
double moveRad = from.toFPP().getDistance(around.toFPP());
double minCol = moveRad - colRadius - t.getRadius();
double maxCol = moveRad + colRadius + t.getRadius();
if (dist >= minCol && dist <= maxCol) {
// Mögliche Kollision!
// Winkeltest
double fromTetha = Math.atan2(from.y() - around.y(), from.x() - around.x());
if (fromTetha < 0) {
fromTetha += 2 * Math.PI;
}
double toTetha = Math.atan2(to.y() - around.y(), to.x() - around.x());
if (toTetha < 0) {
toTetha += 2 * Math.PI;
}
double colTetha = Math.atan2(t.getPrecisePosition().y() - around.y(), t.getPrecisePosition().x() - around.x());
if (colTetha < 0) {
colTetha += 2 * Math.PI;
}
// Zusätzlichen Umlauf beachten
if (toTetha < fromTetha) {
if (colTetha < toTetha) {
colTetha += 2 * Math.PI;
}
toTetha += 2 * Math.PI;
}
if (colTetha >= fromTetha && colTetha <= toTetha) {
// Dann auf jeden Fall
return true;
}
// Sonst weitertesten: Der 6-Punkte-Test
Circle c = new Circle((float) t.getPrecisePosition().x(), (float) t.getPrecisePosition().y(), (float) t.getRadius());
Vector fromOrtho = new Vector(from.x() - around.x(), from.y() - around.y());
fromOrtho = fromOrtho.normalize().multiply(colRadius);
Vector toOrtho = new Vector(to.x() - around.x(), to.y() - around.y());
toOrtho = toOrtho.normalize().multiply(colRadius);
SimplePosition t1 = from.toVector().add(fromOrtho);
SimplePosition t2 = from.toVector();
SimplePosition t3 = from.toVector().add(fromOrtho.getInverted());
SimplePosition t4 = to.toVector().add(toOrtho);
SimplePosition t5 = to.toVector();
SimplePosition t6 = to.toVector().add(toOrtho.normalize());
if (c.contains((float) t1.x(), (float) t1.y())
|| c.contains((float) t2.x(), (float) t2.y())
|| c.contains((float) t3.x(), (float) t3.y())
|| c.contains((float) t4.x(), (float) t4.y())
|| c.contains((float) t5.x(), (float) t5.y())
|| c.contains((float) t6.x(), (float) t6.y())) {
return true;
}
}
return false;
}
}
| true | true | private FloatingPointPosition checkAndMaxMove(FloatingPointPosition from, FloatingPointPosition to) {
// Zuallererst: Wir dürfen nicht über das Ziel hinaus laufen:
if (!arc) {
Vector oldtargetVec = new Vector(target.x() - from.x(), target.y() - from.y());
Vector newtargetVec = new Vector(target.x() - to.x(), target.y() - to.y());
if (oldtargetVec.isOpposite(newtargetVec)) {
// Achtung, zu weit!
to = target.toFPP();
}
} else {
// Arc-Bewegung begrenzen:
if (movedTetha >= tethaDist) {
to = target.toFPP();
}
}
// Zurücksetzen
lastObstacle = null;
colliding = false;
List<Moveable> possibleCollisions = moveMap.moversAroundPoint(caster2.getPrecisePosition(), caster2.getRadius() + 10, caster2.getMyPoly());
// Uns selber ignorieren
possibleCollisions.remove(caster2);
// Freies Gebiet markieren:
Vector ortho = new Vector(to.getfY() - from.getfY(), from.getfX() - to.getfX()); // 90 Grad verdreht (y, -x)
ortho.normalizeMe();
ortho.multiplyMe(caster2.getRadius());
Vector fromv = from.toVector();
Vector tov = to.toVector();
Polygon poly = new Polygon();
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
poly.addPoint((float) fromv.add(ortho.getInverted()).x(), (float) fromv.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho.getInverted()).x(), (float) tov.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho).x(), (float) tov.add(ortho).y());
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
for (Moveable t : possibleCollisions) {
float radius = (float) (t.getRadius() + MIN_DISTANCE / 2);
Circle c = new Circle((float) t.getPrecisePosition().x(), (float) t.getPrecisePosition().y(), radius); //Das getUnit ist ugly!
boolean arcCol = collidesOnArc(t, around, radius, from, to);
// Die Kollisionsbedingungen: Schnitt mit Begrenzungslinien, liegt innerhalb des Testpolygons, liegt zu nah am Ziel
// Die ersten beiden Bedingungen gelten nur für nicht-arc-Bewegungen!
// Die letzte gilt dafür nur für arc-Bewegungen
if (!arc && (poly.intersects(c)) || (!arc && poly.includes(c.getCenterX(), c.getCenterY())) || to.getDistance(t.getPrecisePosition()) < caster2.getRadius() + radius || (arc && arcCol)) {
//System.out.println("COL! with: " + t + " at " + t.getPrecisePosition() + " (dist: " + to.getDistance(t.getPrecisePosition()) + ") on route to " + target + " critical point is " + to);
// Kollision!
if (!arc) {
// Jetzt muss poly verkleinert werden.
// Dazu muss die Zielposition to auf der Strecke von from nach to so weit wie notwendig nach hinten verschoben werden.
// Notwendiger Abstand zur gefundenen Kollision t
float distanceToObstacle = (float) (this.caster2.getRadius() + radius + MIN_DISTANCE / 2);
// Vector, der vom start zum Ziel der Bewegung zeigt.
Vector dirVec = new Vector(to.getfX() - from.getfX(), to.getfY() - from.getfY());
// 90 Grad dazu
Vector origin = new Vector(-dirVec.getY(), dirVec.getX());
// Strecke vom Hinderniss in 90-Grad-Richtung
Edge edge = new Edge(t.getPrecisePosition().toNode(), t.getPrecisePosition().add(origin.toFPP()).toNode());
// Strecke zwischen start und ziel
Edge edge2 = new Edge(caster2.getPrecisePosition().toNode(), caster2.getPrecisePosition().add(dirVec.toFPP()).toNode());
// Schnittpunkt
SimplePosition p = edge.endlessIntersection(edge2);
if (p == null) {
System.out.println("ERROR: " + caster2 + " " + edge + " " + edge2 + " " + t.getPrecisePosition() + " " + origin + " " + dirVec + " " + distanceToObstacle);
}
// Abstand vom Hinderniss zur Strecke edge2
double distance = t.getPrecisePosition().getDistance(p.toFPP());
// Abstand vom Punkt auf edge2 zu freigegebenem Punkt
double b = Math.sqrt((distanceToObstacle * distanceToObstacle) - (distance * distance));
// Auf der Strecke weit genug zurück gehen:
FloatingPointPosition nextnewpos = p.toVector().add(dirVec.getInverted().normalize().multiply(b)).toFPP();
// Zurückgegangenes Stück analysieren
if (new Vector(nextnewpos.getfX() - fromv.x(), nextnewpos.getfY() - fromv.y()).isOpposite(dirVec)) {
// Ganz zurück setzen. Dann muss man nicht weiter suchen, die ganze Route ist hoffnungslos blockiert
colliding = true;
lastObstacle = t;
return from;
}
// Hier gibt es keine Kollision mehr.
// poly neu bauen:
to = nextnewpos;
tov = nextnewpos.toVector();
poly = new Polygon();
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
poly.addPoint((float) fromv.add(ortho.getInverted()).x(), (float) fromv.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho.getInverted()).x(), (float) tov.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho).x(), (float) tov.add(ortho).y());
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
} else {
// to auf dem Laufkreis nach hinten verschieben.
Vector obst = t.getPrecisePosition().toVector();
// Als erstes die Schnittpunkte der beiden Kreise bestimmmen
double moveRad = from.toFPP().getDistance(around.toFPP());
SimplePosition[] intersections = MathUtil.circleCircleIntersection(new Circle((float) obst.getX(), (float) obst.getY(), (float) (radius + caster2.getRadius())), new Circle((float) around.x(), (float) around.y(), (float) moveRad));
SimplePosition s1 = intersections[0];
SimplePosition s2 = intersections[0];
// Ausbrüten, ob s1 oder s2 der richtige ist:
SimplePosition newPosVec = null;
double fromTetha = Math.atan2(from.y() - around.y(), from.x() - around.x());
if (fromTetha < 0) {
fromTetha += 2 * Math.PI;
}
double s1tetha = Math.atan2(s1.y() - around.y(), s1.x() - around.x());
if (s1tetha < 0) {
s1tetha += 2 * Math.PI;
}
double s2tetha = Math.atan2(s2.y() - around.y(), s2.x() - around.x());
if (s2tetha < 0) {
s2tetha += 2 * Math.PI;
}
if (s1tetha < fromTetha) {
s1tetha += 2 * Math.PI;
}
if (s2tetha < fromTetha) {
s2tetha += 2 * Math.PI;
}
if (s1tetha < s2tetha) {
if (arcDirection) {
newPosVec = s1;
} else {
newPosVec = s2;
}
} else {
if (arcDirection) {
newPosVec = s2;
} else {
newPosVec = s1;
}
}
if (!newPosVec.toVector().isValid()) {
throw new RuntimeException();
}
to = newPosVec.toFPP();
tov = to.toVector();
}
colliding = true;
lastObstacle = t;
// Falls wir so weit zurück mussten, dass es gar netmehr weiter geht:
if (from.equals(to)) {
return from;
}
}
}
// Jetzt wurde alles oft genug verschoben um definitiv keine Kollision mehr zu haben.
// Bis hierhin die Route also freigeben:
return to;
}
| private FloatingPointPosition checkAndMaxMove(FloatingPointPosition from, FloatingPointPosition to) {
// Zuallererst: Wir dürfen nicht über das Ziel hinaus laufen:
if (!arc) {
Vector oldtargetVec = new Vector(target.x() - from.x(), target.y() - from.y());
Vector newtargetVec = new Vector(target.x() - to.x(), target.y() - to.y());
if (oldtargetVec.isOpposite(newtargetVec)) {
// Achtung, zu weit!
to = target.toFPP();
}
} else {
// Arc-Bewegung begrenzen:
if (movedTetha >= tethaDist) {
to = target.toFPP();
}
}
// Zurücksetzen
lastObstacle = null;
colliding = false;
List<Moveable> possibleCollisions = moveMap.moversAroundPoint(caster2.getPrecisePosition(), caster2.getRadius() + 10, caster2.getMyPoly());
// Uns selber ignorieren
possibleCollisions.remove(caster2);
// Freies Gebiet markieren:
Vector ortho = new Vector(to.getfY() - from.getfY(), from.getfX() - to.getfX()); // 90 Grad verdreht (y, -x)
ortho.normalizeMe();
ortho.multiplyMe(caster2.getRadius());
Vector fromv = from.toVector();
Vector tov = to.toVector();
Polygon poly = new Polygon();
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
poly.addPoint((float) fromv.add(ortho.getInverted()).x(), (float) fromv.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho.getInverted()).x(), (float) tov.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho).x(), (float) tov.add(ortho).y());
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
for (Moveable t : possibleCollisions) {
float radius = (float) (t.getRadius() + MIN_DISTANCE / 2);
Circle c = new Circle((float) t.getPrecisePosition().x(), (float) t.getPrecisePosition().y(), radius); //Das getUnit ist ugly!
boolean arcCol = collidesOnArc(t, around, radius, from, to);
// Die Kollisionsbedingungen: Schnitt mit Begrenzungslinien, liegt innerhalb des Testpolygons, liegt zu nah am Ziel
// Die ersten beiden Bedingungen gelten nur für nicht-arc-Bewegungen!
// Die letzte gilt dafür nur für arc-Bewegungen
if (!arc && (poly.intersects(c)) || (!arc && poly.includes(c.getCenterX(), c.getCenterY())) || to.getDistance(t.getPrecisePosition()) < caster2.getRadius() + radius || (arc && arcCol)) {
//System.out.println("COL! with: " + t + " at " + t.getPrecisePosition() + " (dist: " + to.getDistance(t.getPrecisePosition()) + ") on route to " + target + " critical point is " + to);
// Kollision!
if (!arc) {
// Jetzt muss poly verkleinert werden.
// Dazu muss die Zielposition to auf der Strecke von from nach to so weit wie notwendig nach hinten verschoben werden.
// Notwendiger Abstand zur gefundenen Kollision t
float distanceToObstacle = (float) (this.caster2.getRadius() + radius + MIN_DISTANCE / 2);
// Vector, der vom start zum Ziel der Bewegung zeigt.
Vector dirVec = new Vector(to.getfX() - from.getfX(), to.getfY() - from.getfY());
// 90 Grad dazu
Vector origin = new Vector(-dirVec.getY(), dirVec.getX());
// Strecke vom Hinderniss in 90-Grad-Richtung
Edge edge = new Edge(t.getPrecisePosition().toNode(), t.getPrecisePosition().add(origin.toFPP()).toNode());
// Strecke zwischen start und ziel
Edge edge2 = new Edge(caster2.getPrecisePosition().toNode(), caster2.getPrecisePosition().add(dirVec.toFPP()).toNode());
// Schnittpunkt
SimplePosition p = edge.endlessIntersection(edge2);
if (p == null) {
System.out.println("ERROR: " + caster2 + " " + edge + " " + edge2 + " " + t.getPrecisePosition() + " " + origin + " " + dirVec + " " + distanceToObstacle);
}
// Abstand vom Hinderniss zur Strecke edge2
double distance = t.getPrecisePosition().getDistance(p.toFPP());
// Abstand vom Punkt auf edge2 zu freigegebenem Punkt
double b = Math.sqrt((distanceToObstacle * distanceToObstacle) - (distance * distance));
// Auf der Strecke weit genug zurück gehen:
FloatingPointPosition nextnewpos = p.toVector().add(dirVec.getInverted().normalize().multiply(b)).toFPP();
// Zurückgegangenes Stück analysieren
if (new Vector(nextnewpos.getfX() - fromv.x(), nextnewpos.getfY() - fromv.y()).isOpposite(dirVec)) {
// Ganz zurück setzen. Dann muss man nicht weiter suchen, die ganze Route ist hoffnungslos blockiert
colliding = true;
lastObstacle = t;
return from;
}
// Hier gibt es keine Kollision mehr.
// poly neu bauen:
to = nextnewpos;
tov = nextnewpos.toVector();
poly = new Polygon();
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
poly.addPoint((float) fromv.add(ortho.getInverted()).x(), (float) fromv.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho.getInverted()).x(), (float) tov.add(ortho.getInverted()).y());
poly.addPoint((float) tov.add(ortho).x(), (float) tov.add(ortho).y());
poly.addPoint((float) fromv.add(ortho).x(), (float) fromv.add(ortho).y());
} else {
// to auf dem Laufkreis nach hinten verschieben.
Vector obst = t.getPrecisePosition().toVector();
// Als erstes die Schnittpunkte der beiden Kreise bestimmmen
double moveRad = from.toFPP().getDistance(around.toFPP());
SimplePosition[] intersections = MathUtil.circleCircleIntersection(new Circle((float) obst.getX(), (float) obst.getY(), (float) (radius + caster2.getRadius())), new Circle((float) around.x(), (float) around.y(), (float) moveRad));
SimplePosition s1 = intersections[0];
SimplePosition s2 = intersections[1];
// Ausbrüten, ob s1 oder s2 der richtige ist:
SimplePosition newPosVec = null;
double fromTetha = Math.atan2(from.y() - around.y(), from.x() - around.x());
if (fromTetha < 0) {
fromTetha += 2 * Math.PI;
}
double s1tetha = Math.atan2(s1.y() - around.y(), s1.x() - around.x());
if (s1tetha < 0) {
s1tetha += 2 * Math.PI;
}
double s2tetha = Math.atan2(s2.y() - around.y(), s2.x() - around.x());
if (s2tetha < 0) {
s2tetha += 2 * Math.PI;
}
if (s1tetha < fromTetha) {
s1tetha += 2 * Math.PI;
}
if (s2tetha < fromTetha) {
s2tetha += 2 * Math.PI;
}
if (s1tetha < s2tetha) {
if (arcDirection) {
newPosVec = s1;
} else {
newPosVec = s2;
}
} else {
if (arcDirection) {
newPosVec = s2;
} else {
newPosVec = s1;
}
}
if (!newPosVec.toVector().isValid()) {
throw new RuntimeException();
}
to = newPosVec.toFPP();
tov = to.toVector();
}
colliding = true;
lastObstacle = t;
// Falls wir so weit zurück mussten, dass es gar netmehr weiter geht:
if (from.equals(to)) {
return from;
}
}
}
// Jetzt wurde alles oft genug verschoben um definitiv keine Kollision mehr zu haben.
// Bis hierhin die Route also freigeben:
return to;
}
|
diff --git a/bundles/pipeline-tests/src/main/java/de/matrixweb/smaller/AbstractToolTest.java b/bundles/pipeline-tests/src/main/java/de/matrixweb/smaller/AbstractToolTest.java
index 64b4906..6f19816 100644
--- a/bundles/pipeline-tests/src/main/java/de/matrixweb/smaller/AbstractToolTest.java
+++ b/bundles/pipeline-tests/src/main/java/de/matrixweb/smaller/AbstractToolTest.java
@@ -1,466 +1,468 @@
package de.matrixweb.smaller;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import org.junit.Ignore;
import org.junit.Test;
import de.matrixweb.smaller.common.SmallerException;
import de.matrixweb.smaller.common.Version;
import de.matrixweb.smaller.pipeline.Result;
import de.matrixweb.smaller.resource.Type;
import de.matrixweb.vfs.VFS;
import de.matrixweb.vfs.VFSUtils;
/**
* @author marwol
*/
public abstract class AbstractToolTest extends AbstractBaseTest {
private static final String JS_SOURCEMAP_PATTERN = "//@ sourceMappingURL[^\\n]+\n;";
private static final String CSS_SOURCEMAP_PATTERN = "/\\*# sourceMappingURL[^ ]+ \\*/";
/**
* @throws Exception
*/
@Test
public void testCoffeeScript() throws Exception {
runToolChain(Version.UNDEFINED, "coffeeScript", new ToolChainCallback() {
@Override
public void test(final VFS vfs, final Result result) throws Exception {
final String basicMin = result.get(Type.JS).getContents()
.replaceFirst(JS_SOURCEMAP_PATTERN, "");
assertOutput(
basicMin,
"(function() {\n var square;\n\n square = function(x) {\n return x * x;\n };\n\n}).call(this);\n");
}
});
}
/**
* @throws Exception
*/
@Test
public void testCoffeeScript2() throws Exception {
runToolChain(Version._1_0_0, "coffeescript2", new ToolChainCallback() {
@Override
public void test(final VFS vfs, final Result result) throws Exception {
String current = VFSUtils.readToString(vfs.find("/script.js"))
.replaceFirst(JS_SOURCEMAP_PATTERN, "");
assertOutput(
current,
"(function() {\n var square;\n\n square = function(x) {\n return x * x;\n };\n\n}).call(this);\n");
current = VFSUtils.readToString(vfs.find("/script2.js")).replaceFirst(
JS_SOURCEMAP_PATTERN, "");
assertOutput(
current,
"(function() {\n var square;\n\n square = function(x) {\n return x * x;\n };\n\n}).call(this);\n");
}
});
}
/**
* @throws Exception
*/
@Test
public void testMixedCoffeeScript() throws Exception {
runToolChain(Version.UNDEFINED, "mixedCoffeeScript",
new ToolChainCallback() {
@Override
public void test(final VFS vfs, final Result result) throws Exception {
final String basicMin = result.get(Type.JS).getContents();
assertOutput(
basicMin,
"(function(){window.square=function(a){return a*a}}).call(this);function blub(){alert(\"blub\")};");
}
});
}
/**
* @throws Exception
*/
@Test
public void testClosure() throws Exception {
runToolChain(Version.UNDEFINED, "closure", new ToolChainCallback() {
@Override
public void test(final VFS vfs, final Result result) throws Exception {
final String basicMin = result.get(Type.JS).getContents();
assertThat(
basicMin,
is("(function(){alert(\"Test1\")})()(function(){alert(\"Test 2\")})();"));
}
});
}
/**
* @throws Exception
*/
@Test
public void testUglifyJs() throws Exception {
runToolChain(Version.UNDEFINED, "uglify", new ToolChainCallback() {
@Override
public void test(final VFS vfs, final Result result) throws Exception {
assertOutput(result.get(Type.JS).getContents(),
"!function(){alert(\"Test1\")}()(function(){var t=\"Test 2\";alert(t)})();");
}
});
}
/**
* @throws Exception
*/
@Test
public void testClosureUglify() throws Exception {
runToolChain(Version.UNDEFINED, "closure-uglify", new ToolChainCallback() {
@Override
public void test(final VFS vfs, final Result result) throws Exception {
final String basicMin = result.get(Type.JS).getContents();
assertOutput(basicMin,
"!function(){alert(\"Test1\")}()(function(){alert(\"Test 2\")})();");
}
});
}
/**
* @throws Exception
*/
@Test
public void testLessJs() throws Exception {
runToolChain(Version.UNDEFINED, "lessjs", new ToolChainCallback() {
@Override
public void test(final VFS vfs, final Result result) throws Exception {
final String css = result.get(Type.CSS).getContents()
.replaceFirst(CSS_SOURCEMAP_PATTERN, "");
assertOutput(
css,
"#header {\n color: #4d926f;\n}\nh2 {\n color: #4d926f;\n}\n.background {\n background: url('some/where.png');\n}\n");
}
});
}
/**
* @throws Exception
*/
@Test
public void testLessJsIncludes() throws Exception {
runToolChain(Version.UNDEFINED, "lessjs-includes", new ToolChainCallback() {
@Override
public void test(final VFS vfs, final Result result) throws Exception {
final String css = result.get(Type.CSS).getContents()
.replaceFirst(CSS_SOURCEMAP_PATTERN, "");
assertOutput(
css,
"#header {\n color: #4d926f;\n}\nh2 {\n color: #4d926f;\n}\n.background {\n background: url('../some/where.png');\n}\n");
}
});
}
/**
* @throws Exception
*/
@Test
public void testLessRelativeResolving() throws Exception {
runToolChain(Version.UNDEFINED, "lessjs-relative-resolving",
new ToolChainCallback() {
@Override
public void test(final VFS vfs, final Result result) throws Exception {
assertOutput(result.get(Type.CSS).getContents(),
".background {\n background: url('../../some/where.png');\n}\n");
}
});
}
/**
* @throws Exception
*/
@Test
public void testLessJsVars() throws Exception {
runToolChain(Version.UNDEFINED, "lessjs-vars", new ToolChainCallback() {
@Override
public void test(final VFS vfs, final Result result) throws Exception {
assertOutput(
result.get(Type.CSS).getContents(),
".background {\n background: url(\"/public/images/back.png\") no-repeat 0 0;\n}\n");
}
});
}
/**
* @throws Exception
*/
@Test
@Ignore("Currently sass does not work as expected")
public void testSass() throws Exception {
runToolChain(Version.UNDEFINED, "sass.zip", new ToolChainCallback() {
@Override
public void test(final VFS vfs, final Result result) throws Exception {
final String css = result.get(Type.CSS).getContents();
assertThat(css, is(""));
}
});
}
/**
* @throws Exception
*/
@Test
public void testAny() throws Exception {
runToolChain(Version.UNDEFINED, "any", new ToolChainCallback() {
@Override
public void test(final VFS vfs, final Result result) throws Exception {
final String basicMin = result.get(Type.JS).getContents();
assertOutput(basicMin,
"!function(){alert(\"Test1\")}()(function(){alert(\"Test 2\")})();");
final String css = result.get(Type.CSS).getContents();
assertOutput(
css,
"#header{color:#4d926f}h2{color:#4d926f;background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIcAAACbCAYAAABI84jqAAAABmJLR0QA9gD2APbboEbJAABMi0lEQVR4XuzSQQ0AIRAEsOFy/lVusLEY4AXh12ro6O7swJd3kAM5kAPkQA7kQA7kQA7kQA7kQA74c6lq5tRi7zvgq6qyftctuamFNBIgdAIECL2KgCJSLChib1jxU8cpFuxjG2uZGRV0bDhjF7tgRQRRsYD0EmpoCYEkhBTSbnvr/2fvdy6BkUHf7yXfe98Jh3PLuefss/faa/1X3W63S6qqqkUkLPEJCeL3+/VlWN+JRPuiZcOGDb1btsxY2apVaynYurX1hk0bS/bv3+/3eDwiLvm3W8AfkES9Xqf27cXr9cq+ffukaFeRdOjQUdq2bSuhUEhvE+Z3e0pKZM+ePeJv8KM9/Ky0rFRiY+OkRYsWUl9XJy6X6DUqpb6hXlJSUiUQ8EswEOD76OhYvV5Yf98gdfW1EhsTK4FgkPcI6rG+vl5at24jycktZMfObSmVFVXdo6N943y+6JzExKTf68XLwuGQuF3oiypx67P5fD79LdrIdgo2HHG9Th07aruSpUHvd6Rt8KABv5E4mtnm0k5yu90DS0tLn9KOHVpbW/dpbW3Nxurq6mtqamoWtczIGKvEUY+OO8xmOtMlCfHxzvv/S1soDIII6MD5eV8Ji1sHNFRXV4vn6llf3/BtZmZmi2QlOr+/QfT9ieFQeLK45JvmyzmafsPMIeeI8nrTAg3+xXvL90pWq1ainGPC/urqCRs3bQTljBw0YICeElUfCAQORxpKWB4BZ9mxY7vo75QDxB6JGDHLOcM9HrwOclZGR8ccibDwPX+LtjToYEtI8nzRMeMSEpOHR0V5u3k83qSqqso1SgjjROTq2Ji4FlXVVQLeGBcXj0mQEQyHFuplrhOXTP8f4jj8xk5O"
+ "TUnN3rx50ydgq927dxdfVBRZacG2bbKzqEgmT5p0eatWWdVyhK20pFSqKyvFo7+PGEgSTXR0tGXJQvZNInOdk5mZNV4HNEMHLBgW1xYRuU9FzF6Ii0ZEYsUF2gziOiYmNma0iqAJMTExx6i4IIGGw0GKm4SEhDa7dxfPqKgovyUmNj7eH/BfXFZW5ob48Xo8OAfXf0pvMVSPT+i+WUT2/g9xcOPsk1atW18578sv//rj998nXH3ttbJ/f41U6QBXqhxesWqVtG/XrrRXbu5MnAsOc7hZrIMj5eXlsnr1anAgciOzEUvU1tRIYWGRpKamiO8AkbhcbvcLnTt1uiw2Lg6DDoKkrK+o2PdhwO9fAEKyBKUiThITA22ioqJGKEeaEB8XPyo5Obl9AzgeCFnb1lDfgPbhqSR8gHiAU65RwsxWLLJNzwu1yspyJyUlSZ2em+zzyu7de4CzLtD2XxAIBir1Ge8Rkb8enlv9/0EcBG4JiYkXaeffmL9uXe+vvvxSrpw6Var375evFy5Udh2UmtoasF8ZO+aEyS63SwFiPTu80UbCqK2tlbVr1pIovBxkpycxo6uqq7GTeAq2blFckpDZf8CAyxQHAFASBDaEhWB027Zt/RXj/JSYmOBTkJibmpo6Mis6eowSw3FKQF4QFwCkzxdFEFmjxCwuAWGBIxFTBJR7YEO7U1JTJ4JoQBQ7tu+Q+V99KUF/UFoooZ44foJyIr8+W60Sd1lSIBB6XJ+5pT7/LSBI/D5sQLTLRVH4/zZxUIykpkzNX5f/7P6a/fLdt9/KyaecIq2z28pL//qn7KuskC6dOn8anxD/1XEjR6zOysxcaIngcJvfH5Dly5ZzhsfFxTUWBXgPIiMXqNRrF+8qlvz8tcVLly7defkVV2Tn5uZKnRJXIECClZycro8rYd6mHMjnjfIl4pperwdcAdoQjhRTlaptJSclgiBIHN4or9TVKYeJSVBtpgG4h2ImqNeN8kbJvvJyJeDVMm/uXOnRs5dqZOv1s33i8Xp198jE0ybJtq0FUlNXe3PL9"
+ "PTF7fu2fbfBaFJ1nBhuIxabP3Gww45uc1kRcPH27duffeftWcpWd8vYceNkxMgR8tPiJZKRniEjhh8LlTJ1y9aCx3bs2CG7oW6iUyJmjSJ9nZEpsnTJElm2bJlMOn0SZDzEw78jSHKXtLR0Ofvsc2TXrqIuChBLMzLSs6l66h4d45P4+AQMpL4PpuF2IATs9XUBCRlV20V124drgtOR6ECPVZVVVHFjVMVNTErAeVTXPR43wXHBls2ycuUKuera38nM556TKZdeJp/M+UiUSAHAySFGjzlR6nftAnC9ze1yvwuigPh16Z8vxmsIv/kTh5X/R0L1mFlA9WDFsGGM8yQl/gsd2r5DB2nTpo2cOnGilJaWSVZmlvTonssOXvzzkiGK+KfvLd/3u7pG4gTXTEhMkLK9e+Xuu++WEceOUM2mJcRB43uTIFQVBuF4tB25MTGxJ6i4mJCbO3ocbBkVFZUUX4oh1G6zQzlLpeT17kNR5HKFqZruLi4G54HIIogNud0gDBA5+wDtowYVdoGT6Hu/VKhtJDk5EeAVIosaTW6PnnLvXX+WzKwsufm22+WOW26WabfdJqrliIJVJagknh8fHydlZXv7l5SUnt2pY4dZwCd79Vm7d8uxE6z5E8eWLVv+A2OXm7MrXllzeno6OunW8AEQKps3beKgxsfHYwAhEihjN23eJMXgKGPGbOjbO49gMHLAQVgguKeefFISzG/xvlevXmqwquA9raEtKyurQ0Vl5YsKSrtBe8C9IBLAYdDhGFy0LTOzJdXM3592GkVcz7ze8sZrr8qEk05SzjZen0FFSIsUHfR9IDheOxSiFoQdoJRsHyQcF+fRNtUAUINjAOvwPunKFadcdpn85S/3yaQzzpSLplwizz49Q8674CJ5V7lo334DaCsJBUO8nrb5LX3WfAW9KwGyyTn"
+ "/u3COMrUmHmnTmSpr1qyhdXL48OH91CI5WB8a1kcMkJGhYXYsPgd3yV+/QTWDxFC3nC6vuj1uAj9sxrLJff78+bJ02VLpoFbDZcuXybPPPSt33XUXziEgFHHx+olJieGOnTqO3qccImy0Hb2nAXgugsStW7fKou++kxYpKdJvwABaVRMT4jF7ZdZbs+RSHdCVK1fJnTrTz1SRlNuzJ89xu6GVCEQSBpOEWaGYJk45Sk1tHcVcbCw5DttTUrJHzjv/Qvnph+9l8mmnyoo1+ZwgL/9zppw++SwpV2JNSk7CBMH1yI2Wr1z1jeKcTBV/dRBl4FJouza+WRMHB/TIG4EkuMJIZcUf6R6Ljk3Qzv/TDdeDfWMQMNthiIKpXG0b2+X4kSNeUALZqx2E78z9aOIGxyLBpehgqkmdomnmSzOlW7ducuqpp6iIKsFvaLWsravZplxlnYqDXFzLEJntfALGtLRUufDc82TEqJHy5Izp/CzK61EssEx+/PFHjsMmNcStW7dW2qpZnr+jFqH3cOu13B6Kpv011aIiiyqtmsn1GeP42mNsGiBMtPfe+x/S+50tY44bSdyR3jJDRh43Sqqr9uv31cAX4GLEKslKvfosr6qa7iovryhLSWkxFUSPZ2jWxJGXl/dLYEPCRqy0yc6+Xgf6cdghrEbh8xH8QXZzNsTGRgu+X7N2nbLftMCQwYOmRVoyLdcoUX/I4sWLMePZ6Xag1S4ts2bNkpNOOllaK7HAVsLfUQ2UNdqOXNxLjyQGQecr8NyrhNleB/yGaTfJs888AxFFjNAyI121miLiIGyzP/xQr5st7dq1U3V0O68t+GeAeXVJtaSlptGPUlOzn8NbW0e8oZwA4iYkXvGoKCuT9IwM+ccLM+Weu+6U4uJdcvU118rOwp2qMT"
+ "UYIxrOFamtD0CLAlFNBidTiyve/zMuPm4ROa64mi9xpCmG+KXNcwC4ZaWlpT2ug2hYsZsDiw0iBLMwFMIAe+gI27W7WFR9/Yuy0ApgAjPTIbt5/jfffIOBIXHZ2UNDmqL9lStXyvOqBdykAw1gZ6+fkJS4HdwLr5U9y/r8fCWwJdK1a470HzgQoFQxwBls29YtW6WbWmj37CmRjRs2yO/+8EeZN2++nK7fz/38C3n91VfknPPOU4NaIf3arhDtGwCR4CZGbPmNqHRh9uP5KFpC5HxRUqLaV0JCojw5/RngMVyLv3N7MAlcbGdNbS0dkPGqkUX5fLzWNuWo9Q3+99WtkAmCBOE1V+KgTv9vNoPuVSoHg7OAG4ADMIggDIAuDDzEEs6LiYmmjWFLwTaIiprBAwc+iNmWqmIDm5Wv36o9pKKiQmC4wrGRZkLx8sabb1CcnDbxNIBMakFlpaWLFPNcr0YsWbZ0GTSSpd1zu5++bu06j3qEZ6s46lVevk+xxaUgCoqDmS++IO0Vzxw/+nhZpXjjhBOOB2ejTeasc85VwvdA3dVnJHFKog72vgoQv4eDWt9QxwHl7gYFm9cuWmyVgOqlpLQO6i98OuyDYIjeV/QbgDrVdU4iJaBqJfQwJ0KgpRLh00rkcEaSe7iaIXEcXu4RLFEMdN5XUT5XuUdHUD4eGrMXM8kYkfg+KsoH7YM4Qu0ayjVGPq3vG7YUFJjOdO"
+ "s56l7fvZsiBQOMwThMWyiusD3//POy8OuFMmHCBOnSpQsA7Weqjm5TAkxUwnhducx1cO5ltMzI27x5856MjAw422DKJkfauHETRdWNN02D2R1iSkHrdjnu+OMFBjO0BW3DIIaUdbjCHHiow9RMoCJ7Q1F07/MZ0D4DSvH8Xi/ESzm+B2BGyAAnWpQv2k4GaHCcAHvUVxQbE4M+MtglpKr1nqu1nc/o866CeGmGxEGx8W+5hlL1GzrwHePiYvFAeDh0FGdHNC2dYLcBsFA+tKqb6LiQDuSMd9/7QNauyxe1kGLUeU5aaqrigBQlMocgje1jsBJeDz2nUAlkLgiuo8748opymaXqYfv27TSWo8P+jh06ddDvRoUklLzo+0UvaZsmKSdIBhEMGzZMcIQowobjRFVpU9PSqLraNoADwjYDVRZWT3AoaBYuPksQzwi3ADgTtA4+H+jYFQ6jr+C70e+qVMXV7xOTlIsmCNiKvx7EUaz3rYP5nsc9SqgqPnBfi5/Qr/geWo+2q+K1rjldegPg6nM3P+JwH0ocGGh07kna+YMAOEXCluIx+OzoyopKslFqOzTqwJyeKt1yuta7RB5MSkxIVvP6fTorvg8bIgD6x/2MxgEucaYebtZzBioewXvMvjOVK72r54PNY/bBtJ67Y2fh6PJ9FSMqKyqG6qxuD1CphEGCOOeccwAi8R73IWFkZ2fzO+U2EBVoshURAKy0Q6g3Fp5VEoN+DC5C7ojJQK2kej80MthocC3gH3AC/q5ddrYeY8k9Kiqr6ChEX4GocA3gEvXegrOCiEBQvAYHLcpD0bxp8+Y8Fa9n9uzR/R3YU/5PC5ffXLxFLXiHIxh04Ba1bnakL0TC1qRNDPDcs8/J5598Ki/88yUjexsMUblBLGChHJC5875Cp3RSA1UBzNawPOopwCbonPs1Uuy2BQsWgCjwHgMH0"
+ "fS2Ypkb9Lr9dR+jnx+rtoa+1mM7ePBgufjii0kM2EBwuKfaXvB7236+LikthS0GA0xA6HZ5ADjxLATW/kCAGlIDsVQYWhE4CV5DC4JX2RjKQhhoiCttZyIHe7+KKqrvnCwEoHx+en/VAYcNBAMRCiswcAy4GMQZiBMbCE2frbBfn97ZGjh0iKgdOXJ4c3K8sWMx8yZqB3bUAUCHQHUDyASaJ6vcvHGj9OnXFzOM7DkSqniI1mkQI+LPyel8Wp+8vL9rKIT8sGgRwCK1jYKCgqs///xzAlNj8cTMxPXG6z3PVIJx6efoPDvjMFBqA5kIi6m1ohqzN/EPiViE3AExIRgsiCMcwdbhOcW5/F2yigzMVt0M9tBjlNdek8YsjWDjAMfqc2cquAQRB8OKF/QZQkGKIBJTMBACkYBA6LhLjEqiGuyjk7ASfUEwukiB8EAlblwHogRYpay0rM3a/PxzO3bs8CaIqll7ZV0uqnIP4wHi4mPl9Vdel7ETxpKqF323SGfvXvo/Hn7sUXANcAF0PkCp0dlD+ByDTHCY271bHMDi+vXr5euvv6Y9QiQd5+Qpwa3"
+ "SQU1Bp1pDmYqLRBPUg3NAaNgNGI6FlmRVXxtLSqLRgwGLHmhRZP2tW7dSlbMUmMKqpFQz41QcVOhgKWfUAaQ3lgRRva9Sj3Sxc1IkJ7UkPihXLgPOA5UV6inAdVDbyngPuvR1D7rg+kf7dGcsCBx2vG+Wuhneev01mT79SZky5VK55PIrYFWFaMN9MBkfVBfCm3ExxHbNyULqakwYI/TYvaWKj5kvvCgvv/SSeiI3KQglpqA8P33SJAwyRJLxH3gAwMg6QVRgucuWrxAQxaBBg975+OOP5SW9TufOnfVczs60fv36TVAx4f7uu++gvho57bUufRvgGxmgCwLi/R3N2BWpXFlCAmHR8aesGrMTbQNugSGLszhsfl9dVQ1igLoJMEqXe0pqC9pjfFHRIBiAbLQFBMfA4NhQjARAoEZzwcFlj2HiFtpOMMRRviiIKPbrrqIiGhy3qfV4zapVqmVBld9HrllcvKfD2rX547KyMj+vranFtZsd58DgQA7ehodB8MumDRvV79EJcpTsvXOXLmSnkyafAZmN8yHzadhZsy4fXlZ/Rnq6YsbKtKJduwMt01Pve+zRhzd89NHsFj179myj6udQETlBOc+pykUSYDgCARkfCY7/zktsgSYtjA5B2O/se8aQsq3hqrC69HdhoPU9xZZys3oQAAgCBEQrqzrEoIEYfw9VV8Z4V"
+ "FRUW+0CBAtCMbEfyeKvrhLek/8ZqnCxIeZoAHhUNNvcoHunLp3ZljZt26nNZYVMnHQG4lKMO4Gm+9uVUD5HXAgeprkRBy2hehivR4KmW++4nbIZ2zMznpaP1Px8rloW0XSwTjwsDFQ/L10uhUVF5du3FbymlsNuyoLHaGeHtmzeNEwHaL3OmGwd+DgFoBh8YAsSglpdbSiAHGmzxAOCMu/NZxZngGuI5X5w+oEAwH1AJAj1AwHoe7+E3QCQQYhC7Dy/lk7E/byWm2IlCmzfRqTr9eJVrNTALQ+Vluo828E/52htJ3WBOjwnLNDEbCedfKrcf+/d8tOPP8hxo08AULYaIIKVAdxHAOelp6UV4Ltmk9TkzLrQRY6892DQiMhhxeuhXswTx46V0SeMRuQTZhsfLF+5yz5F3Vs2bYhZvXL5hVVVFSfW7K9yNdTX+pRTjFcvblcFnXEYJFwHGyyHAJVWrf0PN7YLgUM2uNghEnaFxT4gWn5uzP14zd8yHUJo9cUA4z0tpNbeExMdAzxh8Qv+gUiQy8IBdBn7CYAmmUQEl7BHI+0ogperx3mdOhc1+Jnc97Irr0KIIYEpxSiBNu9BblZUtOsKAfc0GKwZWUgZ23BBkCjch9dKIHx6HdRaGXXcKOPiL6dW4I2OJlFofgpBakN9XWyvvN6xwCA2UryS8pocxvpRsP9a0AX5jA6EWgmug3aZazI1QbFOA2YkOhfiz6rXVL/x1sRwUhRYe04sLJougaNQsdVWGMyoftY3BNAPwFU0eNHUHgzRqOVwKyHAxeZclq947KkY43l1BGa2aqUYrYMgCPqBRx6R115+Gc/A+9SRuOmphsp7rmKl26363PSA1GHPHdS72AfyGS54NA6DC3QeEx"
+ "1tbQdmxriB6Gl32K8DtL+amV6WE1gCwHuwbHz2mx4WBIvrYHbl5+cjpBDEquKi2IoTbDZ4l3YWECnAMVRRuOL9/iCIARZNaClQbanRaGA0bQ8L1RkYVNB6zvnnkcuIy6Nq924OYmpaKkArsIfVxCLxjtMvYXsU2kjyNNhouEa43XLj9Sqi/8w4E82Sg+Zj0yKwW4Mg2tmppKRsYIvkpCXqnGt64nBM5bWTcEQj0WDo4RgQBZiQuRxgh5W7QQDQShhxTU3FdQi1WzzB3brmj7DZnBKIILBitAX4gSAzO7uNKLDFdTm40dFRBJGRqq+bXmRco8FqNoheAxEDZAN/IDgZmEqNec9Kjx495IILL5QX1BOc06279O7dm0HDbpcXbYDpnqmZtXXUeAAucQ/YNiyH4D9nJ7XQ7lFUVChnK0ZDjMhNf/q95CIgOX+ddMnppip7exV55eIxFlr0N/xOGampQ1QrWgInZ3MQK1ZtHKuBu2YQGS8JNs6BiPKqWbu+Hp8bwEacQtETxG8DQaiJjTPQcG3LcX6JMMERwIVARCAEyGsQAXGJ4haoujDCYSdHKNhSQDtC69atjRhB+/0cPBGKLs7OVL0WZrnm09C0vXbtWvnD734n99x3n/zx+j/JU088IV27ddO9q0w8/XRoJFBvCS0pXmN8ZqLUApvwnjR2+fFdNO/DwJ4wQ3sc+uAf+4GxHpdcdoUa4zrJ0zOeVG4VJ2efe54Fo3TYVanWkhAfpziulfiDwdEazjgD/d8cxAoGJVbZ8yi8hlwF28XDAZmTWEQcvwoJioOKmYo3kYYqa4uI5BgYULBkAwrDkaozItfJrUaMGCFdVN3r1KkzrKYkhEYbLa5Kj1ABqXImJSVTFdXNhA7g2gSfdGz9c+ZMef7ZZxit/tHHn5AIFsyfr5rXDDlb/TFn6d5WfTQijDpnTGxdfR2uQWDqdhGUEzOF6kNUXcPBMMWRDqASiR8xHcYcbhCqlSs4uNm3DHoeoo7Bbrk9"
+ "QEyYAIx0s1bfNnpfTC6EHGgw9hk6KZK1vyqaQ2oCxEYfZc+xJmjXGpcAwszAM2ueD+t2W92fbBziCEBKcUclBgvcBmCRYsD4ZRiIU1xcDO5gBx3XpWGpT58+cuGFF0FkNCYEtMvgCbbB2kOQl0Lg6HIf1t5hRGC0jBs3jmbwxx5+WJYbnPKyBvqcqTaGDu3aysuvva7+ixFwnFnAi8h0XIcD7PV4ibkIUOsaRAxHwqyG1gH8EBcfr3ucaPY9+4Y/dXZoRlCHgV+gSSEUAOIKfQiHHiYC71FQsBVcGgQH8TdCraVzmkGwTwNY7zBYFONi48l+6ZTyN8BAxQHSuEcMjzAoxnAJj5EtA/r3Y6kAX5RHxUEaHh5EwtlmOQ0dV2oPefudt2XJkiUgGgwyHU+TJ08GYZjcVccYhs0Shj1iQ7vACfaWlcEzbGM7DTClpgDxwntkqsi4+957pFS5yJjjj5PV+eulm3KPd95/T0YcM1wee+ghOU8xQVJiIjQcDjIjsw5wU1pLdxYWIuBYz0k2vhOPbF6xie/bKoEhNDAlJRnqKL9vBEBIZPhDHg0m3vbt2wBuEQgNP4zxTYWNh9uF/oV9JE8NinOa2s5hAle8nTUIVo+IySgHa+UAW5UtLi4G8hYdCHGDGYU4DXooBw3sL6O1449VVA5wBxxg4j84+/1+OroQlKMhfd3QgZYD0N7x1FNPITTQpAVYIuAxkiNY1RHXxX1hqgcnoghptNnzEFnPzp+u6uToE"
+ "8bICGXtNkXib4o3lq1aKZdePEUCJlQP7B4DyNuZWZ+uBF9auhdAFp5fxS3rEFTEvBWUZoA2VFdbj8lgCEsid5vzQ/FXpqIkBYFOwQAy5/AbOP/YP+RawaC1BA8Jh5telSXFakPy0NnQ62mPSAhBC8DAGuKIU9aawtmJDe2GTIZnFCIDD2nObZQL6tLvYsgVPlDr6hfqhTXqIDqNwPPTTz/FaxAJOomvrRbgmNXFUVl5D6ZFQmNhO0WIEyyXsRsICJZHOuxmf/KJ9FROMkENeQu+Wcg2vfH6G3LbLbfI+BPHQGMBpwQ45rUs5opVQm+VmQknIn0qySpKUlLS4LsB7sGgQkyQw3q8BJlsiaFztJN9VFmxT4F1axVLyjXdHmoyxhKqvyeRgbj0SA7UDRHvTc050MHROsP7aoPY6WtWr6EnU8PnTcieE46v56IjyFka/AFgEqurH0oYznuy5id1psK6aUIEqaZu2rSJ2shpGrHliJHIa4ixVzAQiPLdF00OY0LzGiw8Opy/xRq6MOPJ9r9WJx/iR6+47HIAYXUFnCtvv/uufLVgvvz4w4/aliwQZKR/hO2Ev6NtW0ajIT/Y5MyE0F+4vk3ThH3FclvsmAgEmdUqlrQSAGwnvC/zat1M3sZktA3GtRCXCrDbVq8d1xzM521EwsirgIOKNouHHnhA3nn7bcwu5nAw8trtGMwiZ6ad5REfO+8josqHDz8Werwi952wqoKFMnDnH//4h4wZMwYEaH4TyXViEUqnBLuaOS75a2GwKtFZVyRbCwqQqkhx5xBGOFIMmdckEMx8uvAXqLHrRc2P+Uw5CbYBAweojeMFyenahSUVsEWopEY1D5NT1FFtDkYSpPUmR7ogwAFB1BRFfu3DLjm8NrELg5MMIWCjm9/J67HiOF7vldPUxIGGphsRT1Px2HFj5VhVK++562654/bbTT5ptDPgPDoD4fRU5IAc5Ell/MQjjzwsTz/9jFx11V"
+ "Uybdo0uU9tDTfffDNiRQ0OidQ4KO7AaVBugaLDakslivqRc9JOQwaydTaDm1mMcvgaGC6rMvL5hh87XO6/7y/SoVNHzvKiomI594LzZcoll0oRnXqO6DIc0blSoz0yuYqDHGIANvusUCdBQnyserI7M60SlQhs1h/7NDaW0XKlJSUIooK5PzJNFH3SrhkYwSQNKB+xB9AEHnvkUXgSVc17TZ7TWY1ZiuhveF+NBZIs1ZkljZvgco6OkYudNmzY0MgTrW0kcrabzmZKpWzSCPL+A/pTFJnNnG9jQRsH5hJ3WAKLJBrLAfgcN91yMwNxiotL8CxUi7GZqj4QG0hqIlfyxcQaTSpgb+HYMfiabeHHviifEm8hYk/JpZK03YgasxFiIQJfakL0s6S0oOqPFoKzoI/gsrAJ7ilNThw//vh9FjQNdDI6p7faHd6e9ZZ8q+wXxHLLtJvlz3ffpRbLHiojaxENRflPs2+AVtRGA2xkrrNZ2c0Z0fhzC04dLyRZLllyamoLEAYBmxPMY49hByCHfyk/2QJV3g9thcHLWHjpb0G7kI4AdRtpDDhbTAUiGgQzMlqSyFnMBfd3rq0EwSGgzUYDWZSggjTm"
+ "gQx2MbOf3mJej22JcD6m63XBFWFFnT9vLisDxCUk2PyW5KYWK8jhaGEsmwSbuaqOnnHGZPmvq69Rg9GrMuyYYwCcqJbuLCqkNRBF0zRXBKwUct+IBdehosVJnMYAkAu99OJM+dvjj8utKlJuuWkako0waGDNnNmNE7idmiDC3dFmDksMh21D5Gu3G4QaALGCnaPtzIorVmIEFwHQhdaSrUnjnTt3oVGquLgIEydSwCA/BTMdsRrgcBhQ1hrpqBbemro6OOzwTIe6DpxJxD7dtm0r2sD0Sq09hmsClILY4pucOLKyWicw5jFMczbkLqO2l2kswjcLv5EbbrxBhqo4QLQXEHaHDu1hD2BsZUulfPzWIYRD40RsdcDXXnlVLle5jlNHjBzJ5KJ16uvo06e3PD19utUsnIEPheGQslfCbn01IDS01RLf0YpRm5oJgMxErPjERFQQIP7JUNsLraAsN8lyT1RZLaejKg6AW1xMoqirqYVtB6Z3RKxDq4PmAjF9KMHappo2gBBRJehtzfCLi41jLVerusfDuNSkxEF2WBplXAJ8cKv6XXv11fKIWhDhjMKOQYHpGyzerX8a74jPbMDv4WazjahSzecdufKKK+VBNWNfcvllMnDQIBk3frx8+PEcufD8C+Ta666DdhRZZQiBv8QqjnMwDJsDZjdEDmYsQCuIFCz6aIgD3lz8HiZ95tR2YNY90jv3KZfcb4K"
+ "XYSqH+Ry5K0nAQWgPzObggPRCZ6nq2zmnKwYZxjUGQYVMLItDCNwpWsSx/pITbVyfT4vy8BEjZfWqlbY2CEAp1HZPMyCO8rABmDQjr9cGwyDz8iuvyMWXTJElixdT7obFyRMNhYPoKMpsS+kikeyeu42sllsVAF485WItbNLXynLu2B569BFJTkjQ+hb/snYNfAdPLGYl1F6wf6rZZTrTly9fzkEo2VOCtiHQCKGMBuxJY0Jt3Ca2n7ijqgoeWTwrRUA4TKyD57GxG3Te7S7ezVm/fds2ZMfDZ0RjltYLwUwnkVVXV8HYh/7ADq5kCdaKFQQMwaJq8RL9LDbXJiurFfxFdEn4IaJNY5uaOGDCrsMsMcYfIG2qiueperdyxUpY/SJZt9FUhEDq8OUDQgeFHq7SSOtNyrqhdWBD7GbERpY8+vjRSHcAKLSgkYSV3a4tHWble8tR/wuBPsQBffr2kV55eSgLIStWrICsRuf+EgexfhfuPI+R4tKYuPnnmO9dOrNTwNEgXkCwcJSBEJl/U1dbQ/HmctN7S8IOmrgXPce4/kNIcmL1ouw2rYDRIC5BKMq1crWPl6thbqGq5h3onPO66cWG38nfxMTBQa42g06bwaXK9jfrYKJjYM1DDqrfD1UuiLgNlHcE+4NzjsfGLDuSl9o65i5TqsFukVoHtuSUFHCiyLxdsGmmP3TJyUHBFSXYnajeh5A/mMShaiJghl7d/Pz1ANNUF53NajCNBj9M0z8i5ZFLwxltrbaOKuKCaRv2GajxTMJiJcF9lbB44lyDeYyY4LMQQAOwQ+OBEw+fkdAzW2ZovyVqHzBfFpF1EM+0+J4y8XTm7haqW5+aG9vMONKGZmDnCJWFKRPBXktxpCdzgNa8uOCCCzBomBWgfNbeUGmM2QG/CryfGCwbsdXIJyLcemiBtY46K374/gcjNrwAe+QwluUuW7qUnIXmeod4AOwQewkLq7XOgsgMUTKugzO5eNduAsu83nkMzzuUAO3ODe2FXwcTgxgiKwv5LUkI9LHcj3iJM1zvx+IxmIletwXLEjZg+VDA7IUPhs7J8n3lajbvyL7YUrCdRBUXy7gWzBZoQngGAHOkgJgQRObR4Jnzm5pzAFCW6SBDqwArA7dgtPQ"
+ "dd96hZQta62csnsKEHlb/K92rwDAe4XMAawCrVtXEFnkkYSUpGyXgfO9dFRErOMCRM/yF55+ndHpFjW7YEO0OAtXTDIHUgDWbIKIGgmDnPozSUvd3CyGOMXGXjsiOtORKpLqNQaDrv7USHgAuCIWDHj6YlNyUPTyiX8A5gTHQjsOGODLy3dhq2rfLBubS6+8GMEfEviVcBgnNm/uFvPvWW8yhbZ3dBmGDIET0M9TZcBMTBwHgBu3AGgyy1+uDcwlaAFRX6Nqc6Tb4Jj0tVTSnU+UiWSo6FL4YG4MRCQB5tIHF12vdsN9r3c6LFMd8PHuOuAxYXTB/gXyvKZaz53xsNSQ1l6+yZmYnyIfJzRYvHMQVTEQYwJwLtgZ2ieOAg4oeKWYcMAgtZ/u2rfCOUo0lYbnJ/Sx1ATdAfQeXIWdZvXKlAueXAJLJ5Q4Fv/y9BEjM8JEEiJdCxrsc4nNwJ9F3V656oar3MLIhKAnlKo3rH6KzvqnFCoJ7ClWtUgJvwNNCdgOp0/JJnBEMctY4NUsDwtnvjkY/wK1tMtel0UCIKdiyh7PsielPySJNpL7vnnvgg0DtDGSvQe6rl/QyWmRr1Pgzdux44384SMtopH1wjzSy4YaoOIwOZrstnnGcb15TnjIEQsQsJYF2zukCtRKDCN8N2kbTNk3ZFZU0+P28YAmJ+pM5s+X6G29Uu88xsnPHDkOkLD/htNGsIAGRiGt5rT8lGFYswkh+0BA4CmwjEGXs1zhfHH5nQgv90MDWNzlxVFTQU9gAsQGRokRibAdMCDZZ81RhI2akU8ObIokPZKOxwMxsVJabYO9mre+14UDpSVnw1XzppcASxIHgIIQUQqW8eMoUVADGZxRHzuAecrQxrNY5ZjUn2BLI9fx+agkgbAyQiXar0SOBNYQgsBICdmBKR1QZOAHZe6z+frWGLXymhDxg0CAQHp18PXv1lDdnvakD2oafhRwD3UFEizfkFPDMMrt/P1RgtsVjcoFL91J06ud1CDuA4c0Y2GIBhBG0Xaoa0rYmJg6KlQZ1Qi3"
+ "XBx6XmZmhHUtucVDMJjbHZ+LMFkRi075gw/lIRCFzpChCGiFF1afqIj9Ny1c/8dST0q9/fxAhVdEPdTZGbiYzzt7XEAIGPkqP+J41SoH2IdL0Pdk0wB1AMrUoW4TN+PKsd5XGr4SEVFTsoRgpUfe/mJhUJDp/+MEHVJeLCotYkdnih+HHHktOge1nDXMcN2ECBz8csv0UafmM9CdBA3NRLJGLeL2M/LKLAzAA28vieyBcEzhUi4vs0GcINX3ZpwPJSJs0WmncgfC7oO1c+x0JoTH3IOFQqgPJ288tgTizCd7Pq6+9juzY2Zx64iASa57mb5xit7aQPc7FzLcYxtybLBhtxLnoYHBA4gl+bjgL2s+cWMz2MINyaETDxsgtM5pQQffrjsj0oepPOvPss4lHEJG1bs1aJj8dM2SIfK3FZi5ULof7mZxfy9XYE3xvnXpuNw2L1fRNNcCLjOcx1YQCBkOFDZfD+yi0ERN2JZ69OSQ1oXN/0hl7LajXZLRxh6ptiuBzRjucxA6+8GG4OUE/ZlDwmjsAJsSPU7nQCaLR3W+vxwGMivaBDSMoGBqFMUcz4srGOpgCdb7IIBuog8hMg5scA2o5CtrN+9aGHYulrRNKQtMdhj8sHoRI9A2a+/uBBiCvUONUdnZbaDQofUlV82ItRnvdNVeDaCCS6F538BCJ1go/iB22G30KrGGYrnE5OJgIBA+iJCci0XNSLsE5zSXLfpFNz3Nc4VxSCywesw0mbATWYtCtIQkyFOwSg2bAa8ionfUgBjPLsTPdj6ZnZ/ZHek6pvRD/lG0txSwCjgD2AavFjvuhU23KgikRDVc+MQ7SBXjt2po6Hi1YdfAROj8St3DHK4hHaAesi963Xz95YeYLsnb1aoYvbNOUga1qQ5kw4SRZl78OLabTjVbQ0MHXEksowkBjm7fD1zzHOddqgPjenEvPuK2dthhqdRMTh01W8mzShm3XRrfTo2KBNkDOiJxCdjlAFSyDJmeFouagROkdO7ZZe4e1MtpCKbgOOgthdrAPMH3B4+HssfYRXAseUgTdMGEoJSUTOSHoRKB6YgswHcf7a1+7IzlRIyttJE"
+ "cThzA4OI0G1AwcrK65PXJVc4gmJ0pQR9/8+fNYx6O7AmXUVweRA1yD69nHde7lqFdOm9jHtg1WjMECaiYaUykwARgCEWpoKFcN8keIpOaQDmkdTgv09cUIoH37rVksGT31v64iQCI6ZwnrWuM0a9Adct1iA58OJss24L3djaEIBEWtBk4q7MhdbRzaBycXzOUAb7AaMjOscbCyHWDnyJ3YgTRJ7sfRPsQoZ939eBty2HokkUC8UFx07NyJwHPHziIliG0yatRxCGWA1ZL1TNfnrwdng0GMKnFkW6xocZEbMHsQ76ythvexIo+aS0kJ8o2hqQFMw67yrds44JpDgLFJPg59BsCEbYmWjV6o9bumP/UUWDjc56bISAJUT3gR6eaOio5G0AuCYyAyIHZswjRYpp31wA7W02oK0O21EWCROSzwkRjDW7TtbGv0MgvtHRoNJoJwft4T2CIyYTvy+mgfnsVWKTIVARytTP8Q54n4Fhk4YCBtIU/PmM4kr4GDBiMYCPXKaOOY/9U8lMgG9oAIcESVOP4ZAOZqk4yuHlv0h8mnCXJyxWg/UCtzexBYBJwFmwdWevgUfYOJ1xyIwxagnaPUHYQ6eOLYE+UN1enbaaNf0VoSXgMIYfuwg15bX0egRY2DVXECxmVtBw3Hg7gTtQ4bIeUMNkUHgB8caUwLBJF6PJZ47HUOfW2PLpPVjkx6DFZEPXUQIwAxk6i3bClg0PKmjRttwBABddgGFwVYmwSlEpCZxmi3s885F1oJcdXWbQUMFejVO49cVBliY+7DawXNcqScCOXlCCVEGwCUQcAwhJEzmOW96PBUbRHnoKDLB+iPZsA5+GC2E6t"
+ "UPfsMXGDF8uVquLoZtb+UpY5iLktGRhrOc2auMW84qQGHil1nMEkciMgGK2UNURvPYZOpsEGksSZX5T6KKEdNxD2c143EC7gByjqhABtfW3uJXZXh55+Xwq5BD2uOenmrlPgKFGQCZFNzCDlYACpzjmbm7ddBbJvdFtdFuADuxtyWEzX/9tXX35TzNQmqRWoqwbrjj6HJ3VQMYp9ChKHgDHJaAJqRg8PvQAAmM89wME7QRQq8d5mswGZTTdDmW8xU8HnyyOOOk4cffFAunXKJsrxslEOiTLRJwE7tTtoprBrWKEaykcobCiIc39bpMgVd/ah3gdoX+pqZ+YjvwIBwZmI7NGf2kNcgNHhnUS+M1s3Bao+orWFcCjADraGdu+TAlkH1vFv3blKkhIr3+hRGpQ1bHIDEZsh+qrPvvTMLJa84oMccMxw5rgww2qt70GgXITMb6LjDkQQSBqHifHIr7Sq6/sGZ7Zq2Xk8UQhLhSQZRwUL6kpuJYqFmVRjfArYPVOZXaGckY/0QGJMAluaryft8Xd3oLw8+oAHHw0xMQxDqJWaDcx0HvjeORgdBAK+gY+EFNWc6QUawRiIM0aY5ihx0vcMRRqRqi"
+ "hkMWwXEByPEjJ8IeSMs61jJiPOgeU4P2DcGD2AauAjXgDud3GGlBhD97e9PIPga1lSo1LgWdiWKMohEEDI1OarSIS4sSALiznaR2PAbEAW0NkwkiBa0Adckl3rnzbeQCqKifLxfOejrEfaNZiFWsFtcEFKZOPNAtHk9ZiPSAGl/GKkrEuX17s1O1s3EeMRZV7oVJca6ymjyyGsb1hkGtoC/BS5rFGfBykxIsEbEFTgJZi5iMu3aa404x+EJAy8hjoA7UPQF10BJyH79+lN1rmKbQ9ahZzCB41QMUcWEuu1n209Vv88FWhaiY6dOuDaIGbMbrB9gFqmiwFhIKcA9cY5j02GuLCPcJWDAqMvloVuC3zvr/SsR/6Rm+e3gzGjzm+rSr2m2xBEM0iP5d8wkeAxBFHNmz4bVESFtNpHJnsu4A93QSXCbA1DpkfYJpB+auAxih0ikzvPSM9JY0+vO2+9AFDdAGghKvbPfAg/gHBARZ5j19UQasA4VLy7MShArCBqz0SQ4B+lTEQER2Gh4AFFWPibnw0WMhgXxSQ6iZTKRcolrIH4Vz2VCBqPgksd73AtYxrrhrVhhWKDLxYBoTBZjAQXJ0OtLDejbhV/Lj98v0rKTY2TQkKGYjA8HjIptrte81luh6zg2druWePpIVx2YiAX1TjrlFM7EW6ZNY+eccurJGHjjWPIzA31nYRGSolkKySVMzkYHgtUjVgKsF4R"
+ "h7RWmBmgUc2AfeOB+TUWcAuMX9ztuvVUSlSjeeOtNmXrF5Roo9Hvp27ePEuBuzrZDxWHj11RpAWjBeZBzws9IEMQVBINYrAcTgaF/bieOlO2kCEEFnqQEekrxFdRMqKb6AAgZhP0H6iYMVwZcU2yAo5C4GLVWXcPJYMuGkcgN5yos3Kl4qAChj1jV+ltXOLwG3zfnJTVsWP00rbU5EXIZMQ2wXgLcwd+B800JKKuuMSpsj34HcYTvUI4R+GL9+o2yXdlmxw4ddMCCJvKbKF6wzftynnwx90v54ou58rqWQ/jjn/4kPiXEBx96iJ7LL+fORUAxxA8xiVm89xfxR5iOK+IJbfM2xGlCO7L2Dw6e38/FDDnALss96XuhWo1ZzHviEzjprGvBKRQjUsmlNZjjCk7Bvoih7ycOk4be11CQvzO/YbwJI9YX//A923jsyOOwbo3+zneDKbnQrJbUgJp1uBWn0UEfKuudWF5WBh8Dqf2vjz5KTtKBg13n/MIsUmMNNw1+slrK23XqAk9NSYWhDAMGpxk76jG9FsTGTdNulH59+8rtt9+pa78t5ADcpYsQ/9fUqTTPT1EP6DHqMgcrxsBFYJDDiRnrqIeNgkCwVas2qF8OrYi4wmPM/yg/aQYPz2ZVctb6ytTIrColdNg3ALrxLGY3MS5uWnptKADdCbAOe7y00ew3IQe4PryvdukPcimPG+IECxEi/RKuim81mWoEnq3Rppzz0qbFHHxoZ6dMFBcH/FokBiPQBdZCBMH07NULhd1J7ZFEGTLplOhkzA5cx1g1KYpsfEbkDNXFeqjzX6zAb4pW1znzrMmSl9eLkdvvv/cerJFQnaFGYiYasWR/H7KvbTvs/cCVoNIylyWrVWsEMJEwaNQ269VC3OGtCd2zmAvPzHP3lJYwaMiWcrLfW+Dp5yKEmYgDAQdCf5BoyvaiKhITwExQMnGMCUCidZYc54QTx/E5i4sLEeg0FfdojgsAYkAPRzCwYexUWfq4PvQNYMWoj4GgFzwgQuqcmSrgGrBVgIgI1Kxjjiwei/UYB5OxhvI47ZabsUQHxBXTCwb27SfvffghTPAgQP2sL3w8XJT4HLVS4nfgVrh2owo+kR5R"
+ "s2xoEICUEV52ZUfr9OKpYt9bEBnidyHghXgmKkFE0kZhjWw83ww40i1M+SjjZ2J0mRG5BM+ojQ5VFfVNCIKrqrhKJgiKsavfKCA9ZeJpryveWYf2NkfiAOv7JTwyTdnhFXv2VCTDowouEMG+bSwFxchuJQysBIlcj7ABt2CvAKfQdgw3MYlCyRo087XcqiAXEd29euXJNQo8URsM6vMnc+bQMtt/wABqK59paag+KnqgRmKgnO0gPwvAITASB48sPrCfA+YQAo4OYfBo/Tb8npFxOqDJao9RB6E3Xb+zhEOuyiPVHuFnONhlz2kUg8bhN9wTVlGIMRi+MAlxHr776IP31c+UHdIKx9fAqnuErUkjwX6RdtR+cJ5Wy/tEO8+sdUZvK3enlmgJjFcAcSjiZmuOgkBsTi1Zua0uyEKzBQWwI2DlImKLs845m2x8546dzC4DGIYV8uWX/qWJVpfg2iAMcA874IfdfVi+cx/LYWPgGnEI3c1g871T3huzH9yJ/REXC2diDjACNCsQsFHD/fgNOWcNlk01K2abJdSpIXH9WOIwxt6iPjy/03dQg7EeLtXlMyafOVVDBCpMkbhmyjmOULVOv/7Up84g9UOcriAVkdomiIVGKrOeKj2McHljJlMLwGYCdDBbzIDyilBLGVB8/OjRkMGMPJ/54ouyWe0dd959F2qOQYVEOSg4ybQjJ8u7mozdpWsOZhwJhKIhJOZoiYP+FPhw4AqHrYarLOnwO0nuBIocaBiprNuAhBkXmwzACNUbCwBAHDDV8rVX/iUZmVlY21aKi4pklKZv9ujVCxPBgE6GBKL6E"
+ "DglOKkNdjL4mO57bfd+BhSN7tLla73niwf8K813RWpQ/ZGcL5j15yrL3h3rjUpmKoKxcXi9UA3djCpnxbyqChPtRcAYsdryQZVVDOdxweMLVsw2JCv4nHbrzcAvNCzNnPmi9FIwuvinH+XRhx9RL+l2zEqs9oT2kI0bVGmsnLRiA+hRs9mBskuJrC4MEQMitj4Q3p+VE6Pgx6CtAi3kNSsrq8EheU52dqb845kZ8vLL/4p0DBDsDh42lB7mIDUYuhKg0iIwCtczJTyp7pNQgiFyJmhwDdpHpx8BhDYXO4fnSOQjHp+vXh9ugg7aIrBLfXrMV7O+G3BEDLQEyFbjca1z0iOd4iuRG4lp5MhRsKyicC2sovCa8rxTTz1VlmqK5IhRI+W0SZMwAFCFCTBLSstohHJ7wtAsrBOL97NiEkuQQQxCXGGpDJzDIBtj4rZpDSFTt105nQk7DBn3P79jHm0rjV3pltONWfUpOuu/mveleH0+VjR21Nsgdgw8svkMSA1wEgXNOSYbD8FMp6ko3uekkDpbs7NzbN5ccBSaTfBGvd+jqsmwA8WAOZNYDB+EDkwm8moNu3axg8R1iGcVMwqONswymJfB5u3n0DQA5mhIYmyD05HwmPJ9GPdUVdsGMnPAeT9oSl4QBrLWkQfDOmBh6xgzajeO1ixiNREOJKO0gvY1sBM4FdRVtveaq66UbuqQm3Lp5bKrsIgcweb/eA1+qzfttYavALASwwpaPKDFgG8H4Rx5o52jaYljXf4RE6tsJ9oBeksf+2wMBAdEmKEFkAkDEOQt4jIwU5wAXw4YQWxE8S5ez0a34/fWHmJd/hBLtlQkrm38Mj4QFIgAv7EJz9avYrPdEB6AdALeN693X3iDTa6ty2ot1qiFI37HYySRWBXTg5TQsIAo1Rd0q1ZbHMk12nbv2oVzTRwIRYptHwYGNg8QPUQwLLxfaL+Ms1pb8ycOco4tRxX7ETpgq/heQd1QVW1RBwvAzJQsiENBWnSQWUmpxrrkMZg2S65RUBA714gK5pFACEXmsDAlUe+HoGNc2xa5"
+ "Rcdb9biREzFkV4HE2ikIIwSQZQJ4VRWvdTC34B42R0dl5WvYQCgy4gh077/vXl0i43JkwxH0OqtY2kQmWmKtQw4EA+Jfo/3RKyLY+CiIowkxx9GvCMRBHakGopUa+9B948YNcvLJpzAOsnxvKcAatBE44bhyM2UrOQwHz2oO3JxKOwEUcKV9gZtELuZXD6wBPMICsVwvPyInRpy4kIPtGEGqlhoS0J1VeTZu3ASOxsJsNdRSHIIIRxCJDXUkPnG4CbgeuY+wllcSfD/2O0toIFYQEhrO2FB/HZc536nBS8fYojQRW7MHpL+mwegov/bHEJWxS7SuVs7naqRCQvJxquLBugifBrQLBBQj4wvslYNpyyA4m10WyxIRCcWKnZDJj0HYPhbpBSiFKIkM7Qv/u93ksoQbwky7zAqFsBgfQWNcfCIwgjWHO3vYHIORnwFshpGjg5RItA/R84xUcwApfSh8zfbBN8WIOSlOT88YpKKt8tcSRtOHCR79hpIBlb379h3YOjv7BzV3537+2WcMOB6ttglssHQiRK+TonyAy4PROY72JY1UUFM5UylmTEqlmMFDgFBNTZ0U797NIOSGen8kx7Diyby2ycwO0EQ2P4rAosAbPKkQLdby6XANZ3c+s+mKQarcuiyqhiAOo8OwxBEpTgyozwf8Q/e+0vn29JYthyogLz4CYTRfbWXV6rVHSyA8n1bBYBBYQUVq9HzN8xj63jtvawG4x6Ch0FBFjUE7sVPHjuA27HDDPyLuaUooiJP1RRuGyf+wy5EzWhxGNX9Qau2acmGHgACQcbTeV5rEjRGKebIG+KLYCzgVzicR8DwHiNrXDlfA53C+cVE/ihS/NXLZQaekpDcaebEQe/nqNBymXGTfEQijeWOO3NweGgC7HQMJreDoiESA4OvrVE4PU+/i7P79+5/y8ezZCCdkLS8Mb5W6wLeqzIeXVc+zKUqWyqyKaddbMSopsYmtC2IHmANCjQY5JxhIEgGJC3kfAMoMMWR6AAaPE4dma2tbMeLLY0RTBBAl8DTvDQgNcGBBnDwfeAW11/E5wxz9"
+ "JuwvaFRjGM+ifVELVZWfoH1Zg+v+qgxEtwfqfJOLFSbunHTyydKnt7rjt+9E1tXREgk6HLPy1F59+jy2ds3aGz768AMZPHiI5KmzLC01TWoNF4F7m7PciT42EVJhqKJWtUWdDBAJzfEuAz4DJq+EflFnoT9cB2mWqOpjlj4Xa8fA0XAjJioDv0B8GZc9fx9BDJGYg4NufUGIarNLqUILYhSZxT3+ADMA9XsW839en3GqwXJH3Y+Mfjf2lO8XfSdnnH5K08Zz/OEP18mJY0bLQw89jLcgEgLAozHvukykd8eOnW7UtIDzO3Xu0vDG66+ry/0tOp7i9IHpUbULAxoZjj3Ao10WPAgPLhfpe0jDB19Rs/WH6sHEIj7fqf9l06aNEgqEGJtJddGkBmCZDd2AJ2DSRltMARgWu6XBrrqqEoCSM99HbGBEBtuiu5MIDk7GvNkAYzC45poxfcfpjM6ANZVE53ZyfgF0r9ZnnPorF1W2izMzs/8V9eU8/NADzSLjjQnCt956i4wcMVweePAhNrJ791wQydE8KGYWor3f0JUQc8efdNKCDevzOaMLi7gEFrmADU5mrgsTisG+QSQ8YqBMtb80qserVqyE7wa+F2gYKKKL1AHMeLQPrBw4AMV2dd9Ldu+liHJzqaxtBQXIUQEIhXiBtRSEYtaWqWdbuOP+ZoFko3IDW5j1VDwkqHXr1iAOAyIO2grWjgGHW6bt6K199g9TWuHXEAa5qsbtyozpT6iTcVaTayuNN6qft992q0ZivStPPDkdhcwQ6o9yzpiRkO1HAqoYBHg4t+iaLcdrBZ8/6UA/qg/vAeHoaxAe2DuKrrHDbQ1QW36geHcxk5IGDRkML60ehxC/JCXxPKrKuwoLdZAWqu0jhwvdlJeHGSy8efMmzG7jQg+A5dOLnJTcAhZTXJ/H4qJC5viK0Lpq4Q9D/dw2osyUlQCR4f3qVStgL+ESXmVIaiorhaHvASXc263Wgu1XEgYTtJ984u/y0YfvN2FqwpE3OsKGHzNUxc3xco+60DGoffvkQTQcqRPsEuWY5Tj3b9qxXUXkHchRriTN8Lg9IAawbMw+mwBtZy09qYU7dsL"
+ "aCO6B+6NGKgYbiUTwbSCuFQnN2tbFIDg6/NIzMoUD7fEwsLh16zaot4U2wVtLbYMlpLxelHsAeAXBGM2Hwc+4l119Cbm9WCQA68LCFK+E2FXy9L56+mdaH7VvZlar2/Gshrv+WlHCdj75979awmjWxGE3lpy+T83FEDePPvY4BhCLAh+NgQ0dCfv8WSrDJyoWWBWvgwtCgdiARxaDoIY0AmH6XkzSNQZjhxLIli2b2Y6uKuaW/vyzemt/pkm6j4YVdlar6f333qsDSMyBmAoQCSyztrA+wWoDzewhU6pbaEbHFjY13OvrbeGXWuvTgejS+y2RD959m4lHgwYPRQ7tZhWKF7VMz5igomQFCO7XbRZ8xmLRY1UKnpLZH33YBEaw375RrEy76UaNbXhaZuhSXOPHjVVZXy+F6njap3L+yHYSF/bZOnNna4zoZUoE1+ug9BQJIzgHrB+cBoMOfEE80qdff3AVJjGvWL5M5s+bx+SpEerm//Tjj+U1LYGQv3YtiBWaDrkS/RrWJxO5cLLYpC1nOVP1kMLmQY2jpqEGnAW4hiD0888+YRBSHy1sx/LWLbM2q3f274ozZoTU/El7iIlc/w0cA1xRMcaTKsbfaWIL6W/fWEJ6wvhxcsIJJ2pS8TCZoonWvXv3xszGqtQOIRwej9gKvjOVo8zUmXw27DwKRE9QTgH5jVnO6yDqHQ49JHE3mDwSlGU89/wLUXlH5f9qiVdC6d9/gOR06waVFxZbaisSkWYQNioqbCLUjkzcBwralwT84BRWHQbotFoXlhWnyT0xIeF7JdwXtF2aYF79m4jBPCMnQpSPNc0"
+ "UY/xN3n+XhPHfnzjsNm/eXO7/1Gq+V145VSZNmgzgSpBZWFhEuX64zeB4Y52UWarCztIz+/tDwQtFZLKCyXZg+QDGuAbUWoQG9tUZzDKNlRUoooIkKt3bQ2OAK58gmDVETEpAlDr9avRzhBuCg9hqO04EuYscgnmsDO8jOGWsSGx87O68Vr3fVy/zq0pQ39UECGx/DWFYhx09wmjBou++VbV7N7nl2rVrZO4XnzdT38pv31ha4M9/vpMLBp951lkyWZf/6q1YYOOG9f+RSscOD4eXaicuVWvmDYoNxikRnKJY5EQdqK4uDnYYRIdOtiZzAEUYnqiK2vXzCxSbILc1J6cr7Q/RMbEQUeQEju2B8aPC+BOkTogHEdRSEwgWqJo7Vy8/R1XauVWVFXXM83VqJHJw/9PNhhGQKFi7dLF88vFshDw2geOtaTfW83rm6Rla5P45mT7jGbnooou4Dsp/GEBrPbZhjfn4TPHAZ5p1jk97qiVzlIgMUO1lgIqEPi2UELhUBa2aBJbQLqB2wo5Cz23RzkIWcWmvNdqHDDsGEVwgCGMCJyiF1rVa7SNLQ37/Mk30XhAKBZYzz8bJgfm1G4AtxAeIlkQxZ85HzKZvis0rzWcj0Ltq6hUq/8vkmmt/h5qeEAUYmKNx6lnD0xrlFmt0tGCCRzxnO8UjXTWZuZ36YdpjV1DbUm0RiRoSENd/wEDfoMFDXMo9wggDUU2gRoFqldopSsUlW5Xwtiv3QMXEDSp6CpyVoN2KR/zy2zdqZ0gVJZB+4m9/lZ9++uF/tXO1R4rjQJS7uv+jjeB0EYw2gvFGgDcCmwiACDARABFgIjBEAESwngjWGZw3gjtN1Zvqri6NDq0/4Lb0"
+ "qrqYoa3utvTcaiQBKR9pVzYi4veHjCoikiMikiMikiMikiMikiMi4o8b1g3ODsXVSmHFWNkI3cFKaSW3ksn30d5l88ukL0RoK9+sfPqPldjOmeOrlcZKAjlZKaCrraytGOgaIgBeqU0pbLbUxvroExErK8pKPui0gkFc4vUNjdBfrOygM5LBIM/WYfMVtmaw3QMiBCmmw5KDCFJ6HG5xjbGSsIyhoHMhA3F6RASIUWI8UitqjIL0wJxrB3mO0M9ZattBJwDioE1/iED/71jfpmNsvNUQA4IUQr/G+yn0xlNLzBm731A5GN6+t4evF0c8S39RjHYCmMoaqXfYP2HaBBCnB4ipZgMz91x7hR/XQ+LvEzcSEXtOfR0IVKxeEchxROH7xI0KeitEHgENvXbZhiycN056SYYN8yntGit/Q793kNCImKnad8eS0vVki7WR962YrUpcXyC2M8Ud1CcSe+6f3bf+ibEPXuc4gr36g3S1E4WqC3PYaYSiFDWMxIXZPDmIMwM5GmfGo4zSOvQXHrP4BLXhJOBPubDVIHs+yQzI4n0V1xf4CJ+AICqoT9yFaOmINR265pC1ReZMxYTMcwO7SX/YwG856RGCZCbg4XkN8kKxayurjoVozeNmpMyGJofMDukHU0PjKVxT6C89VuYJ5vkh0dyW0mUGDC/2Oxei7kxvIIOSQ6bpuSPANQbfdbOrHrPGAgOCBbXeYaC4eMiRQFJIKOQUrIIHkeLQIMhZyDuysfZWdpzp4u/yXY9gFV/3gL4rNhAUdt0hbCkQr6Ws5CXHFG06I9gODfwRsa65sPjTUc6QIpCNKIKQNSyo4NTQbyntdQdbsf2GTwCf4a8rpuho2gvyZ6WCE+vOK6JfPdP1CvEZK/WgmUMWpu6sQNkDgaXQd4Vc51AgSGcg5i+QbeB0tezw5FOb8Hosp/FwQy5QDkkOOfgJsshB6Ev2sfeM/5tJv9iiMw2mgXuiZlOeCa8ZMIihkItc/oI3HYkcVJiCAFtPdtEIsH9QQZpD7gmFAahDBxiK9U8WoqcbiNtQfIOTgxjp2UNZy4WmG+fv3FP8vWEqSDhjT23uaZdB4dUHxJkIYmwcxNDM7jOfQkCkim011A"
+ "F9kgQU5ZqNzwr+On9vxf+NM1oa/uyZnyuQSKZM/z4Cbef791YI54C9FWQbv94Tpw8nZFH/3grd4xV90wb0CZu6/AemPNde7dgXncnxSyIi/CRYRMT9yRERyRERyaEmj4AIdY+fYFh4HP9pRctKuYPdpueV1PSDar0YabA21D+Dnhvdw8eFLalvx8ocBUT+f+i4wjnFDRWQ50m/OFp54jGPmO1a9M/QKEEKTsqXsaaV47AdSBioM384OvPXBU6yjUWO5sal3AqixNRR0C6uFwYKjesX4lxkymyZQB8y1pb5ydH+LFYiDdnFsjNdmzNbBV4VdBAnUofNBPeZsDhSbxxkawPRMqtLn/ChRi5IERixNWdBNni9giAuZIJADXt/iZSZIFUWWJavgnxQ2z3FS36QTWasvWLEXLKNvSOub9ku6jNeK7EyaxyknDKbcysp2hrotsyfproFbbD9zvpjCWnF6vELI9ac98+ovwkmjv69MnZmLMAnzxL7Ae2NmApOaHNhg1OQzyAfV9Y2536ga0QtkooNrU9sGtxhII+wtXQQ7otj/yUT0+aOHdRp2f3WIFkKf/K+lbTFySGJAtIriB6PHH7owHMRtc8WOvPYxQdQol3j9edv/x0ZDHaIBAE2W0+a/8EGtHZMUzr0zAfkYRbBavGUqo62Mm6ro49VqD/HcYQ9y5g1CKJFG2lzKvTXiRvP8FE7vtaoyB/Z8hDjCQ9QMxg54GgKydmhVoMbMExv8GSt2Jwpn64F2syFLmF2EkrBKNxYQXiDjxR2XlihVnE/0Gn2xaGCpfqK+ePYoc2FEWbLri9E/+SINaFT86gxCBn0C9irZRwQmpLIlwLhE+HzDYb505xU996VVQiugXRFQh03iA8J45zyqJNL+T6Rxn/yS1xzRg3RMGLIOJRjPcPAjkI7AdGW+qnF2A9AjogFHYXsBWdklsv/d8s+QqEYbSF9wLBMpB/9Z58i/Cu6fw1gd+ZQ/PI/bx0Rz3NERHJERHJERPwLZ401JHjcCs0AAAAASUVORK5CYII=)}");
}
});
}
/**
* @throws Exception
*/
@Test
public void testCssEmbed() throws Exception {
runToolChain(Version.UNDEFINED, "cssembed", new ToolChainCallback() {
@Override
public void test(final VFS vfs, final Result result) throws Exception {
final String css = result.get(Type.CSS).getContents();
assertOutput(
css,
".background {\n background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAABaElEQVR42u3aQRKCMAwAQB7n/7+EVx1HbZsEStlcldAsUJrq9hDNsSGABQsWLFiwEMCCBQsWLFgIYMGCBQsWLASwYMGCBQsWAliwYMGCBQtBCGt/j1UrHygTFixYsGDBgnUE1v4lKnK2Zw5h7f0RLGmMLDjCSJlVWOnuYyP8zDwdVkpVKTlnx4o8Dr1YLV8uwUqZ4IP3S1ba1wPnfRsWvZUqVjMnYw1ffFiZBy6OlTvu1bBKZ7rc1f90WJGILx3ujpXSD94Iq/0ssLpPtOYEX7RR03WTro8V2TW7NVbvImOuOWtyr6u2O6fsr8O6LNY8T+JxWEd6/SisGqvlFFvpZsvAenrg0+HBl2DFO97g5S1qthP24NsTVbQ+uQlTurT/WLnNxIS/rQ2UuUVyJXbX6Y16YpvZgXVK41Z3/SLhD7iwYMGCBUvAggULFixYAhYsWLBgwRKwYMGCBQuWgAULFixYsAQsWDXxBFVy4xyOC7MdAAAAAElFTkSuQmCC);\n}\n.svg {\n background: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB2aWV3Qm94PSIwIDAgMTk1IDgyIj4KICA8dGl0bGU+U1ZHIGxvZ28gY29tYmluZWQgd2l0aCB0aGUgVzNDIGxvZ28sIHNldCBob3Jpem9udGFsbHk8L3RpdGxlPgogIDxkZXNjPlRoZSBsb2dvIGNvbWJpbmVzIHRocmVlIGVudGl0aWVzIGRpc3BsYXllZCBob3Jpem9udGFsbHk6IHRoZSBXM0MgbG9nbyB3aXRoIHRoZSB0ZXh0ICdXM0MnOyB0aGUgZHJhd2luZyBvZiBhIGZsb3dlciBvciBzdGFyIHNoYXBlIHdpdGggZWlnaHQgYXJtczsgYW5kIHRoZSB0ZXh0ICdTVkcnLiBUaGVzZSB0aHJlZSBlbnRpdGllcyBhcmUgc2V0IGhvcml6b250YWxseS48L2Rlc2M+CiAgCiAgPG1ldGFkYXRhPgogICAgPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIiB4bWxuczpyZGZzPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwLzAxL3JkZi1zY2hlbWEjIiB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiB4bWxuczp4aHRtbD0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94aHRtbC92b2NhYiMiIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyI+CiAgICAgIDxjYzpXb3JrIHJkZjphYm91dD0iIj4KICAgICAgICA8ZGM6dGl0bGU+U1ZHIGxvZ28gY29tYmluZWQgd"
+ "2l0aCB0aGUgVzNDIGxvZ288L2RjOnRpdGxlPgogICAgICAgIDxkYzpmb3JtYXQ+aW1hZ2Uvc3ZnK3htbDwvZGM6Zm9ybWF0PgogICAgICAgIDxyZGZzOnNlZUFsc28gcmRmOnJlc291cmNlPSJodHRwOi8vd3d3LnczLm9yZy8yMDA3LzEwL3N3LWxvZ29zLmh0bWwiLz4KICAgICAgICA8ZGM6ZGF0ZT4yMDA3LTExLTAxPC9kYzpkYXRlPgogICAgICAgIDx4aHRtbDpsaWNlbnNlIHJkZjpyZXNvdXJjZT0iaHR0cDovL3d3dy53My5vcmcvQ29uc29ydGl1bS9MZWdhbC8yMDAyL2NvcHlyaWdodC1kb2N1bWVudHMtMjAwMjEyMzEiLz4KICAgICAgICA8Y2M6bW9yZVBlcm1pc3Npb25zIHJkZjpyZXNvdXJjZT0iaHR0cDovL3d3dy53My5vcmcvMjAwNy8xMC9zdy1sb2dvcy5odG1sI0xvZ29XaXRoVzNDIi8+CiAgICAgICAgPGNjOmF0dHJpYnV0aW9uVVJMIHJkZjpyZW91cmNlPSJodHRwOi8vd3d3LnczLm9yZy8yMDAxL3N3LyIvPgogICAgICAgIDxkYzpkZXNjcmlwdGlvbj5UaGUgbG9nbyBjb21iaW5lcyB0aHJlZSBlbnRpdGllcyBkaXNwbGF5ZWQgaG9yaXpvbnRhbGx5OiB0aGUgVzNDIGxvZ28gd2l0aCB0aGUgdGV4dCAnVzNDJzsgdGhlIGRyYXdpbmcgb2YgYSBmbG93ZXIgb3Igc3RhciBzaGFwZSB3aXRoIGVpZ2h0IGFybXM7IGFuZCB0aGUgdGV4dCAnU1ZHJy4gVGhlc2UgdGhyZWUgZW50aXRpZXMgYXJlIHNldCBob3Jpem9udGFsbHkuCgkJCTwvZGM6ZGVzY3JpcHRpb24+CiAgICAgIDwvY2M6V29yaz4KICAgIDwvcmRmOlJERj4KICA8L21ldGFkYXRhPgogIAogIDx0ZXh0IHg9IjAiIHk9Ijc1IiBmb250LXNpemU9IjgzIiBmaWxsLW9wYWNpdHk9IjAiIGZvbnQtZmFtaWx5PSJUcmVidWNoZXQiIGxldHRlci1zcGFjaW5nPSItMTIiPlczQzwvdGV4dD4KICA8dGV4dCB4PSIxODAiIHk9Ijc1IiBm"
+ "b250LXNpemU9IjgzIiBmaWxsLW9wYWNpdHk9IjAiIGZvbnQtZmFtaWx5PSJUcmVidWNoZXQiIGZvbnQtd2VpZ2h0PSJib2xkIj5TVkc8L3RleHQ+CiAgPGRlZnM+CiAgICA8ZyBpZD0iU1ZHIiBmaWxsPSIjMDA1QTlDIj4KICAgICAgPHBhdGggaWQ9IlMiIGQ9Ik0gNS40ODIsMzEuMzE5IEMyLjE2MywyOC4wMDEgMC4xMDksMjMuNDE5IDAuMTA5LDE4LjM1OCBDMC4xMDksOC4yMzIgOC4zMjIsMC4wMjQgMTguNDQzLDAuMDI0IEMyOC41NjksMC4wMjQgMzYuNzgyLDguMjMyIDM2Ljc4MiwxOC4zNTggTDI2LjA0MiwxOC4zNTggQzI2LjA0MiwxNC4xNjQgMjIuNjM4LDEwLjc2NSAxOC40NDMsMTAuNzY1IEMxNC4yNDksMTAuNzY1IDEwLjg1MCwxNC4xNjQgMTAuODUwLDE4LjM1OCBDMTAuODUwLDIwLjQ1MyAxMS43MDEsMjIuMzUxIDEzLjA3MCwyMy43MjEgTDEzLjA3NSwyMy43MjEgQzE0LjQ1MCwyNS4xMDEgMTUuNTk1LDI1LjUwMCAxOC40NDMsMjUuOTUyIEwxOC40NDMsMjUuOTUyIEMyMy41MDksMjYuNDc5IDI4LjA5MSwyOC4wMDYgMzEuNDA5LDMxLjMyNCBMMzEuNDA5LDMxLjMyNCBDMzQuNzI4LDM0LjY0MyAzNi43ODIsMzkuMjI1IDM2Ljc4Miw0NC4yODYgQzM2Ljc4Miw1NC40MTIgMjguNTY5LDYyLjYyNSAxOC40NDMsNjIuNjI1IEM4LjMyMiw2Mi42MjUgMC4xMDksNTQuNDEyIDAuMTA5LDQ0LjI4NiBMMTAuODUwLDQ0LjI4NiBDMTAuODUwLDQ4LjQ4MCAxNC4yNDksNTEuODg0IDE4LjQ0Myw1MS44ODQgQzIyLjYzOCw1MS44ODQgMjYuMDQyLDQ4LjQ4MCAyNi4wNDIsNDQuMjg2IEMyNi4wNDIsNDIuMTkxIDI1LjE5MSw0MC4yOTggMjMuODIxLDM4LjkyMyBMMjMuODE2LDM4LjkyMyBDMjIuNDQxLDM3LjU0OCAyMC40NjgsMzcuMDc0IDE4LjQ0MywzNi42OTcgTDE4LjQ0MywzNi42OTIgQzEzLjUzMywzNS45MzkgOC44MDAsMzQuNjM4IDUuNDgyLDMxLjMxOSBMNS40ODIsMzEuMzE5IEw1LjQ4MiwzMS4zMTkgWiIvPgogICAgICA8cGF0aCBpZD0iViIgZD0iTSA3My40NTIsMC4wMjQgTDYwLjQ4Miw2Mi42MjUgTDQ5Ljc0Miw2Mi42MjUgTDM2Ljc4MiwwLjAyNCBMNDcuNTIyLDAuMDI0IEw1NS4xMjIsMzYuNjg3IEw2Mi43MTIsMC4wMjQgTDczLjQ1MiwwLjAyNCBaIi8+CiAgICAgIDxwYXRoIGlkPSJHIiBkPSJNIDkxLjc5MiwyNS45NTIgTDExMC4xMjYsMjUuOTUyIEwxMTAuMTI2LDQ0LjI4NiBMMTEwLjEzMSw0NC4yODYgQzExMC4xMzEsNTQuNDEzIDEwMS45MTgsNjIuNjI2IDkxLjc5Miw2Mi42MjYgQzgxLjY2NSw2Mi42MjYgNzMuNDU4LDU0LjQxMyA3My40NTgsNDQuMjg2IEw3My40NTgsNDQuMjg2IEw3My40NTgsMTguMzU5IEw3My40NTMsMTguMzU5IEM3My40NTMsOC4"
+ "yMzMgODEuNjY1LDAuMDI1IDkxLjc5MiwwLjAyNSBDMTAxLjkxMywwLjAyNSAxMTAuMTI2LDguMjMzIDExMC4xMjYsMTguMzU5IEw5OS4zODUsMTguMzU5IEM5OS4zODUsMTQuMTY5IDk1Ljk4MSwxMC43NjUgOTEuNzkyLDEwLjc2NSBDODcuNTk3LDEwLjc2NSA4NC4xOTgsMTQuMTY5IDg0LjE5OCwxOC4zNTkgTDg0LjE5OCw0NC4yODYgTDg0LjE5OCw0NC4yODYgQzg0LjE5OCw0OC40ODEgODcuNTk3LDUxLjg4MCA5MS43OTIsNTEuODgwIEM5NS45ODEsNTEuODgwIDk5LjM4MCw0OC40ODEgOTkuMzg1LDQ0LjI5MSBMOTkuMzg1LDQ0LjI4NiBMOTkuMzg1LDM2LjY5OCBMOTEuNzkyLDM2LjY5OCBMOTEuNzkyLDI1Ljk1MiBMOTEuNzkyLDI1Ljk1MiBaIi8+CiAgICA8L2c+CiAgPC9kZWZzPgogIDxnIHNoYXBlLXJlbmRlcmluZz0iZ2VvbWV0cmljUHJlY2lzaW9uIiB0ZXh0LXJlbmRlcmluZz0iZ2VvbWV0cmljUHJlY2lzaW9uIiBpbWFnZS1yZW5kZXJpbmc9Im9wdGltaXplUXVhbGl0eSI+CiAgICA8Zz4KICAgICAgPGcgaWQ9ImxvZ28iIHRyYW5zZm9ybT0ic2NhbGUoMC4yNCkgdHJhbnNsYXRlKDAsIDM1KSI+CiAgICAgICAgPGcgc3Ryb2tlLXdpZHRoPSIzOC4wMDg2IiBzdHJva2U9IiMwMDAiPgogICAgICAgICAgPGcgaWQ9InN2Z3N0YXIiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDE1MCwgMTUwKSI+CiAgICAgICAgICAgIDxwYXRoIGlkPSJzdmdiYXIiIGZpbGw9IiNFREE5MjEiIGQ9Ik0tODQuMTQ4NywtMTUuODUxMyBhMjIuNDE3MSwyMi40MTcxIDAgMSAwIDAsMzEuNzAyNiBoMTY4LjI5NzQgYTIyLjQxNzEsMjIuNDE3MSAwIDEgMCAwLC0zMS43MDI2IFoiLz4KICAgICAgICAgICAgPHVzZSB4bGluazpocmVmPSIjc3ZnYmFyIiB0cmFuc2Zvcm09InJvdGF0ZSg0NSkiLz4KICAgICAgICAgICAgPHVzZSB4bGluazpocmVmPSIjc3ZnYmFyIiB0cmFuc2Zvcm09InJvdGF0ZSg5MCkiLz4KICAgICAgICAgICAgPHVzZSB4bGluazpocmVmPSIjc3ZnYmFyIiB0cmFuc2Zvcm09InJvdGF0ZSgxMzUpIi8+CiAgICAgICAgICA8L2c+CiAgICAgICAgPC9nPgogICAgICAgIDx1c2UgeGxpbms6aHJlZj0iI3N2Z3N0YXIiLz4KICAgICAgPC9nPgogICAgICA8ZyBpZD0iU1ZHLWxhYmVsIj4KICAgICAgICA8dXNlIHhsaW5rOmhyZWY9IiNTVkciIHRyYW5zZm9ybT0ic2NhbGUoMS4wOCkgdHJhbnNsYXRlKDY1LDEwKSIvPgogICAgICA8L2c+CiAgICA8L2c+CiAgPC9nPgo8L3N2Zz4K);\n}");
}
});
}
/**
* @throws Exception
*/
@Test
@Ignore("Should be moved to the server tests")
public void testOutputOnly() throws Exception {
runToolChain(Version.UNDEFINED, "out-only", new ToolChainCallback() {
@Override
public void test(final VFS vfs, final Result result) throws Exception {
// assertThat(directory.list().length, is(2));
// assertThat(new File(directory, "basic-min.js").exists(), is(true));
// assertThat(new File(directory, "style.css").exists(), is(true));
}
});
}
/**
* @throws Exception
*/
@Test
public void testClosureError() throws Exception {
try {
runToolChain(Version.UNDEFINED, "closure-error", null);
} catch (final SmallerException e) {
assertThat(
e.getMessage(),
is("Closure Failed: JSC_PARSE_ERROR. Parse error. missing ( before function parameters. at source.js line 1 : 10"));
}
}
/**
* @throws Exception
*/
@Test
public void testUnicodeEscape() throws Exception {
runToolChain(Version.UNDEFINED, "unicode-escape", new ToolChainCallback() {
@Override
public void test(final VFS vfs, final Result result) throws Exception {
final String basicMin = result.get(Type.JS).getContents();
assertOutput(
basicMin,
"var stringEscapes={\"\\\\\":\"\\\\\",\"'\":\"'\",\"\\n\":\"n\",\"\\r\":\"r\",\"\t\":\"t\",\"\\u2028\":\"u2028\",\"\\u2029\":\"u2029\"};");
}
});
}
/**
* @throws Exception
*/
@Test
public void testRelativeResolving() throws Exception {
runToolChain(Version.UNDEFINED, "relative-resolving",
new ToolChainCallback() {
@Override
public void test(final VFS vfs, final Result result) throws Exception {
- final String basic = result.get(Type.JS).getContents();
+ final String basic = result.get(Type.JS).getContents()
+ .replaceAll("\r\n", "\n");
assertOutput(basic, "// test1.js\n\n// test2.js\n");
}
});
}
/**
* @throws Exception
*/
@Test
public void testTypeScript() throws Exception {
runToolChain(Version.UNDEFINED, "typescript", new ToolChainCallback() {
@Override
public void test(final VFS vfs, final Result result) throws Exception {
assertOutput(
result.get(Type.JS).getContents(),
"var Greeter = (function () {\n function Greeter(message) {\n this.greeting = message;\n }\n Greeter.prototype.greet = function () {\n return \"Hello, \" + this.greeting;\n };\n return Greeter;\n})();\nvar greeter = new Greeter(\"world\");\nvar button = document.createElement('button');\nbutton.innerText = \"Say Hello\";\nbutton.onclick = function () {\n alert(greeter.greet());\n};\ndocument.body.appendChild(button);\n");
}
});
}
/**
* @throws Exception
*/
@Test
@Ignore("Currently the result is not assertable")
public void testTypeScriptCompiler() throws Exception {
runToolChain(Version.UNDEFINED, "typescript-compiler",
new ToolChainCallback() {
@Override
public void test(final VFS vfs, final Result result) throws Exception {
assertOutput(result.get(Type.JS).getContents(), "wada");
}
});
}
/**
* @throws Exception
*/
@Test
@Ignore
public void testJpegTran() throws Exception {
runToolChain(Version.UNDEFINED, "jpegtran", new ToolChainCallback() {
@Override
public void test(final VFS vfs, final Result result) throws Exception {
assertOutput("yada", "wada");
}
});
}
/**
* @throws Exception
*/
@Test
public void testYcssmin() throws Exception {
runToolChain(Version.UNDEFINED, "ycssmin", new ToolChainCallback() {
@Override
public void test(final VFS vfs, final Result result) throws Exception {
assertOutput(result.get(Type.CSS).getContents(), "h1{color:0000FF}");
}
});
}
/**
* @throws Exception
*/
@Test
public void testJsHint() throws Exception {
try {
runToolChain(Version.UNDEFINED, "jshint", new ToolChainCallback() {
@Override
public void test(final VFS vfs, final Result result) throws Exception {
}
});
fail("Expected to have jshint errors");
} catch (final SmallerException e) {
}
}
/**
* @throws Exception
*/
@Test
public void testBrowserify() throws Exception {
runToolChain(Version._1_0_0, "browserify", new ToolChainCallback() {
@Override
public void test(final VFS vfs, final Result result) throws Exception {
final String current = result.get(Type.JS).getContents()
- .replaceFirst(JS_SOURCEMAP_PATTERN, "");
+ .replaceAll("\r\n", "\n").replaceFirst(JS_SOURCEMAP_PATTERN, "");
final String expected = ";(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require==\"function\"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error(\"Cannot find module '\"+o+\"'\")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require==\"function\"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){\nvar m = require('./module');\nm.test();\n\n},{\"./module\":2}],2:[function(require,module,exports){\nmodule.exports = {test:function() {}};\n\n},{}]},{},[1])\n;";
assertOutput(current, expected);
}
});
}
/**
* @throws Exception
*/
@Test
public void testCoffeeScritBrowserify() throws Exception {
runToolChain(Version._1_0_0, "coffeescript-browserify",
new ToolChainCallback() {
@Override
public void test(final VFS vfs, final Result result) throws Exception {
- final String expected = ";(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require==\"function\"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error(\"Cannot find module '\"+o+\"'\")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require==\"function\"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){\n(function() {\n var m;\n\n m = require('./module');\n\n m.test();\n\n}).call(this);\n\n},{\"./module\":2}],2:[function(require,module,exports){\n(function() {\n var func;\n\n func = function(x) {\n return x * 2;\n };\n\n module.exports = {\n test: func\n };\n\n}).call(this);\n\n},{}]},{},[1])\n;";
final String current = result.get(Type.JS).getContents()
+ .replaceAll("\r\n", "\n")
.replaceFirst(JS_SOURCEMAP_PATTERN, "");
+ final String expected = ";(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require==\"function\"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error(\"Cannot find module '\"+o+\"'\")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require==\"function\"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){\n(function() {\n var m;\n\n m = require('./module');\n\n m.test();\n\n}).call(this);\n\n},{\"./module\":2}],2:[function(require,module,exports){\n(function() {\n var func;\n\n func = function(x) {\n return x * 2;\n };\n\n module.exports = {\n test: func\n };\n\n}).call(this);\n\n},{}]},{},[1])\n;";
assertOutput(current, expected);
}
});
}
/**
* @throws Exception
*/
@Test
public void testSvgo() throws Exception {
runToolChain(Version._1_0_0, "svgo", new ToolChainCallback() {
@Override
public void test(final VFS vfs, final Result result) throws Exception {
final String expected = "<svg width=\"10\" height=\"20\">test</svg>";
assertOutput(VFSUtils.readToString(vfs.find("/test.svg")), expected);
}
});
}
/**
* @throws Exception
*/
@Test
public void testSweetjs() throws Exception {
runToolChain(Version._1_0_0, "sweetjs", new ToolChainCallback() {
@Override
public void test(final VFS vfs, final Result result) throws Exception {
final String expected = "function add$112(a$113, b$114) {\n return a$113 + b$114;\n}";
assertOutput(VFSUtils.readToString(vfs.find("/browser.js")), expected);
}
});
}
}
| false | false | null | null |
diff --git a/src/org/biojava/stats/svm/SparseVector.java b/src/org/biojava/stats/svm/SparseVector.java
index 867f2586c..9126d1e5a 100755
--- a/src/org/biojava/stats/svm/SparseVector.java
+++ b/src/org/biojava/stats/svm/SparseVector.java
@@ -1,320 +1,324 @@
/*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
*/
package org.biojava.stats.svm;
import java.util.*;
import java.io.Serializable;
/**
* An implementation of a sparse vector.
* <P>
* Memory is only allocated for dimensions that have non-zero values.
*
* @author Thomas Down
* @author Matthew Pocock
*/
public class SparseVector implements Serializable {
int size;
int[] keys;
double[] values;
public SparseVector() {
this(1);
}
public SparseVector(int capacity) {
keys = new int[capacity];
values = new double[capacity];
Arrays.fill(keys, 0, capacity, Integer.MAX_VALUE);
size = 0;
}
/**
* The number of used dimensions.
* <P>
* This is the total number of non-zero dimensions. It is not equal to the
* number of the highest indexed dimension.
*
* @return the number of non-zero dimensions
*/
public int size() {
return size;
}
/**
* Set the value at a particular dimension.
* <P>
* This silently handles the case when previously there was no value at dim.
* It does not contract the sparse array if you set a value to zero.
*
* @param dim the dimension to alter
* @param value the new value
*/
public void put(int dim, double value) {
// find index of key nearest dim
int indx = Arrays.binarySearch(keys, dim);
if(indx >= 0) { // found entry for dim
values[indx] = value;
} else { // need to create entry for dim
indx = -(indx + 1);
if ((size + 1) >= keys.length) { // growing arrays
int[] nKeys = new int[keys.length * 2];
Arrays.fill(nKeys, size, nKeys.length, Integer.MAX_VALUE);
System.arraycopy(keys, 0, nKeys, 0, indx);
System.arraycopy(keys, indx, nKeys, indx+1, size-indx);
keys = nKeys;
double[] nValues = new double[values.length * 2];
Arrays.fill(nValues, size, nValues.length, Double.NaN);
System.arraycopy(values, 0, nValues, 0, indx);
System.arraycopy(values, indx, nValues, indx+1, size-indx);
values = nValues;
} else {
try {
System.arraycopy(keys, indx, keys, indx+1, size-indx);
System.arraycopy(values, indx, values, indx+1, size-indx);
} catch (ArrayIndexOutOfBoundsException ae) {
// paranoya check - they were out to get me once
// - they may try it again
System.out.println("dim = " + dim);
System.out.println("value = " + value);
System.out.println("keys.length = " + keys.length);
System.out.println("size = " + size);
System.out.println("indx = " + indx);
System.out.println("indx+1 = " + (indx+1));
System.out.println("size-indx = " + (size-indx));
System.out.println("size+1 = " + (size+1));
throw ae;
}
}
keys[indx] = dim;
values[indx] = value;
++size;
}
}
/**
* Retrieve the value at dimension dim.
*
* @param dim the dimension to retrieve a value for
* @return the value at that dimension
*/
public double get(int dim) {
int pos = Arrays.binarySearch(keys, dim);
if (pos >= 0) {
return values[pos];
}
return 0.0;
}
/**
* Retrieve the dimension at a specific index.
* <P>
* E.g., if the sparse vector had dimensions 5, 11, 12, 155 set to non-zero
* values then <code>sv.getDimAtIndex(2)</code> would return 12.
*
* @param indx the index
* @return the dimension stoored at that index
* @throws ArrayIndexOutOfBoundsException if index >= size.
*/
public int getDimAtIndex(int indx) {
if(indx >= size) {
throw new ArrayIndexOutOfBoundsException(
"Attempted to read item " + indx + " of an array with " + size + "elements"
);
}
return keys[indx];
}
/**
* Retrieve the value at a specific index.
* <P>
* E.g., if the sparse vector contained the data 5->0.1, 11->100, 12->8.5, 155->-10
* then <code>sv.geValueAtIndex(2)</code> would return 8.5.
*
* @param indx the index
* @return the value stoored at that index
* @throws ArrayIndexOutOfBoundsException if index >= size.
*/
public double getValueAtIndex(int indx) {
if(indx >= size) {
throw new ArrayIndexOutOfBoundsException(
"Attempted to read item " + indx + " of an array with " + size + "elements"
);
}
return values[indx];
}
public int maxIndex() {
return keys[size - 1];
}
public static SparseVector normalLengthVector(SparseVector v, double length) {
SparseVector n = new SparseVector(v.size);
double oldLength = 0;
for (int i = 0; i < v.size; ++i) {
oldLength += v.values[i] * v.values[i];
}
oldLength = Math.sqrt(oldLength);
for (int i = 0; i < v.size; ++i) {
n.put(v.keys[i], v.values[i] * length / oldLength);
}
return n;
}
- public static final SVMKernel kernel = new SVMKernel() {
+ public static final SVMKernel kernel = new SparseVectorKernel();
+
+
+
+ private static class SparseVectorKernel implements SVMKernel, Serializable {
public double evaluate(Object o1, Object o2) {
SparseVector a = (SparseVector) o1;
SparseVector b = (SparseVector) o2;
int ai=0, bi=0;
double total = 0.0;
while (ai < a.size && bi < b.size) {
if (a.keys[ai] > b.keys[bi]) {
++bi;
} else if (a.keys[ai] < b.keys[bi]) {
++ai;
} else {
total += a.values[ai++] * b.values[bi++];
}
}
return total;
}
public String toString() {
return "SparseVector kernel K(x, y) = sum_i ( x_i * y_i ).";
}
};
/**
* A version of the standard dot-product kernel that scales each column
* independantly.
*
* @author Matthew Pocock
*/
public static class NormalizingKernel implements SVMKernel, Serializable {
/**
* The sparse vector that performes the normalization.
*/
private SparseVector s;
/**
* Retrive the current normalizing vector.
*
* @return the normalizing vector
*/
public SparseVector getNormalizingVector() {
return s;
}
/**
* Set the normalizing vector.
*
* @param the new normalizing vector
*/
public void setNormalizingVector(SparseVector nv) {
s = nv;
}
/**
* Evaluate the kernel function between two SparseVectors.
* <P>
* This function is equivalent to:
* <br>
* <code>k(a, b) = sum_i ( a_i * b_i * nv_i )</code>
* <br>
* where nv_i is the value of the normalizing vector at index i. This can
* be thought of as scaling each vector at index i by
* <code>sqrt(nv_i)</code>.
*/
public double evaluate(Object o1, Object o2) {
SparseVector a = (SparseVector) o1;
SparseVector b = (SparseVector) o2;
int ai=0, bi=0, si=0;
double total = 0.0;
while (ai < a.size && bi < b.size && si < s.size) {
if ( (a.keys[ai] < b.keys[bi]) || (a.keys[ai] < s.keys[si])) {
++ai;
} else if ((b.keys[bi] < a.keys[ai]) || (b.keys[bi] < s.keys[si])) {
++bi;
} else if ((s.keys[si] < a.keys[ai]) || (s.keys[si] < b.keys[bi])) {
++si;
} else if( (a.keys[ai] == s.keys[si]) && (b.keys[bi] == s.keys[si]) ) {
total += a.values[ai++] * b.values[bi++] * a.keys[ai-1]; //s.values[si++];
} else {
System.out.println("ai = " + ai);
System.out.println("bi = " + bi);
System.out.println("si = " + si);
System.exit(1);
}
}
return total;
}
/**
* Generate a normalizing kernel with the normalizing vector s.
*
* @param s the SparseVector to normalize by
*/
public NormalizingKernel(SparseVector s) {
this.s = s;
}
/**
* Generate a normalizing kernel defined by the SparseVectors in vectors.
* <P>
* It will set up a normalizing vector that has weight that will scale
* each element so that the average score is 1.
*/
public NormalizingKernel(List vectors) {
this.s = new SparseVector();
for(Iterator i = vectors.iterator(); i.hasNext(); ) {
SparseVector v = (SparseVector) i.next();
for(int j = 0; j < v.size(); j++) {
s.put(v.keys[j], s.get(v.keys[j]) + v.values[j]);
}
}
for(int j = 0; j < s.size(); j++) {
s.values[j] = (double) vectors.size() / s.values[j];
s.values[j] *= s.values[j];
}
}
public String toString() {
return "SparseVector.NormalizingKernel K(x, y | s) = " +
"sum_i ( x_i * y_i * s_i ).";
}
}
}
diff --git a/src/org/biojava/stats/svm/tools/ClassifierExample.java b/src/org/biojava/stats/svm/tools/ClassifierExample.java
index b0d584426..f50f13d32 100755
--- a/src/org/biojava/stats/svm/tools/ClassifierExample.java
+++ b/src/org/biojava/stats/svm/tools/ClassifierExample.java
@@ -1,376 +1,376 @@
/*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
*/
package org.biojava.stats.svm.tools;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
import javax.swing.*;
import org.biojava.stats.svm.*;
/**
* A simple toy example that allows you to put points on a canvas, and find a
* polynomeal hyperplane to seperate them.
*/
public class ClassifierExample {
/**
* Entry point for the application. The arguments are ignored.
*/
public static void main(String args[]) {
JFrame f = new JFrame();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
f.getContentPane().setLayout(new BorderLayout());
final PointClassifier pc = new PointClassifier();
f.getContentPane().add(BorderLayout.CENTER, pc);
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
ButtonGroup bGroup = new ButtonGroup();
final JRadioButton rbPos = new JRadioButton("postive");
bGroup.add(rbPos);
final JRadioButton rbNeg = new JRadioButton("negative");
bGroup.add(rbNeg);
ActionListener addTypeAction = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JRadioButton rb = (JRadioButton) ae.getSource();
pc.setAddPos(rbPos.isSelected());
}
};
rbPos.addActionListener(addTypeAction);
panel.add(rbPos);
rbNeg.addActionListener(addTypeAction);
panel.add(rbNeg);
ActionListener classifyAction = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
pc.classify();
}
};
JButton classifyB = new JButton("classify");
classifyB.addActionListener(classifyAction);
panel.add(classifyB);
ActionListener clearAction = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
pc.clear();
}
};
JButton clearB = new JButton("clear");
clearB.addActionListener(clearAction);
panel.add(clearB);
rbPos.setSelected(pc.getAddPos());
rbNeg.setSelected(!pc.getAddPos());
JComboBox kernelBox = new JComboBox();
kernelBox.addItem("polynomeal");
kernelBox.addItem("rbf");
kernelBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {
Object o = e.getItem();
if(o.equals("polynomeal")) {
pc.setKernel(pc.polyKernel);
} else if(o.equals("rbf")) {
pc.setKernel(pc.rbfKernel);
}
}
}
});
panel.add(kernelBox);
f.getContentPane().add(BorderLayout.NORTH, panel);
f.setSize(400, 300);
f.setVisible(true);
}
/**
* An extention of JComponent that contains the points & encapsulates the
* classifier.
*/
public static class PointClassifier extends JComponent {
// public kernels
public static SVMKernel polyKernel;
public static SVMKernel rbfKernel;
public static SMOTrainer trainer;
static {
trainer = new SMOTrainer();
trainer.setC(1.0E+7);
trainer.setEpsilon(1.0E-9);
SVMKernel k = new SVMKernel() {
public double evaluate(Object a, Object b) {
Point2D pa = (Point2D) a;
Point2D pb = (Point2D) b;
double dot = pa.getX() * pb.getX() + pa.getY() * pb.getY();
return dot;
}
};
PolynomialKernel pk = new PolynomialKernel();
pk.setNestedKernel(k);
pk.setOrder(2.0);
pk.setConstant(1.0);
pk.setMultiplier(0.0000001);
RadialBaseKernel rb = new RadialBaseKernel();
rb.setNestedKernel(k);
rb.setWidth(10000.0);
polyKernel = pk;
rbfKernel = rb;
}
// private variables that should only be diddled by internal methods
private SVMTarget target;
private SVMClassifierModel model;
{
target = new SimpleSVMTarget();
model = null;
}
// private variables containing state that may be diddled by beany methods
private boolean addPos;
private Shape posShape;
private Shape negShape;
private Paint svPaint;
private Paint plainPaint;
private Paint posPaint;
private Paint negPaint;
private SVMKernel kernel;
/**
* Set the kernel used for classification.
*
* @param kernel the SVMKernel to use
*/
public void setKernel(SVMKernel kernel) {
firePropertyChange("kernel", this.kernel, kernel);
this.kernel = kernel;
}
/**
* Retrieve the currently used kernel
*
* @return the current value of the kernel.
*/
public SVMKernel getKernel() {
return this.kernel;
}
/**
* Set a flag so that newly added points will be in the positive class or
* negative class, depending on wether addPos is true or false respectively.
*
* @param addPos boolean to flag which class to add new points to0
*/
public void setAddPos(boolean addPos) {
firePropertyChange("addPos", this.addPos, addPos);
this.addPos = addPos;
}
/**
* Retrieve the current value of addPos.
*
* @return true if new points will be added to the positive examples and
* false if they will be added to the negative examples.
*/
public boolean getAddPos() {
return addPos;
}
/**
* Set the Shape to represent the positive points.
* <P>
* The shape should be positioned so that 0, 0 is the center or focus.
*
* @param posShape the Shape to use
*/
public void setPosShape(Shape posShape) {
firePropertyChange("posShape", this.posShape, posShape);
this.posShape = posShape;
}
/**
* Retrieve the shape used to represent positive points.
*
* @return the current positive Shape
*/
public Shape getPosShape() {
return posShape;
}
/**
* Set the Shape to represent the negative points.
* <P>
* The shape should be positioned so that 0, 0 is the center or focus.
*
* @param posShape the Shape to use
*/
public void setNegShape(Shape negShape) {
firePropertyChange("negShape", this.negShape, negShape);
this.negShape = negShape;
}
/**
* Retrieve the shape used to represent negative points.
*
* @return the current negative Shape
*/
public Shape getNegShape() {
return negShape;
}
/**
* Remove all points from the canvas, and discard any model.
*/
public void clear() {
target.clear();
model = null;
repaint();
}
/**
* Learn a model from the current points.
* <P>
* This may take some time for complicated models.
*/
public void classify() {
new Thread() {
public void run() {
Cursor c = getCursor();
setCursor(new Cursor(Cursor.WAIT_CURSOR));
System.out.println("Training");
model = trainer.trainModel(target, kernel, null);
System.out.println("Threshold = " + model.getThreshold());
- for(Iterator i = target.items().iterator(); i.hasNext(); ) {
+ for(Iterator i = model.items().iterator(); i.hasNext(); ) {
Object item = i.next();
System.out.println(item + "\t" +
target.getTarget(item) + "\t" +
model.getAlpha(item) + "\t" +
model.classify(item)
);
}
PointClassifier.this.model = model;
setCursor(c);
repaint();
}
}.start();
}
/**
* Make a new PointClassifier.
* <P>
* Hooks up the mouse listener & cursor.
* Chooses default colors & Shapes.
*/
public PointClassifier() {
setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
addPos = true;
setPosShape(new Rectangle2D.Double(-2.0, -2.0, 5.0, 5.0));
setNegShape(new Ellipse2D.Double(-2.0, -2.0, 5.0, 5.0));
setKernel(polyKernel);
plainPaint = Color.black;
svPaint = Color.green;
posPaint = Color.red;
negPaint = Color.blue;
addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent me) {
Point p = me.getPoint();
if(getAddPos()) {
target.addItemTarget(p, +1.0);
} else {
target.addItemTarget(p, -1.0);
}
model = null;
repaint();
}
});
}
/**
* Renders this component to display the points, and if present, the
* support vector machine.
*/
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
AffineTransform at = new AffineTransform();
int i = 0;
Rectangle r = g2.getClipBounds();
int step = 3;
if(model != null) {
Rectangle rr = new Rectangle(r.x, r.y, step, step);
Point p = new Point(r.x, r.y);
for(int x = r.x; x < r.x + r.width; x+=step) {
p.x = x;
rr.x = x;
for(int y = r.y; y < r.y + r.height; y+=step) {
p.y = y;
rr.y = y;
double s = model.classify(p);
if(s <= -1.0) {
g2.setPaint(negPaint);
} else if(s >= +1.0) {
g2.setPaint(posPaint);
} else {
g2.setPaint(Color.white);
}
g2.fill(rr);
}
}
}
Set supportVectors = Collections.EMPTY_SET;
if(model != null) {
supportVectors = model.items();
}
for(Iterator it = target.items().iterator(); it.hasNext(); i++) {
Point2D p = (Point2D) it.next();
at.setToTranslation(p.getX(), p.getY());
Shape glyph;
if(target.getTarget(p) > 0) {
glyph = getPosShape();
} else {
glyph = getNegShape();
}
Shape s = at.createTransformedShape(glyph);
if(supportVectors.contains(p)) {
g2.setPaint(svPaint);
} else {
g2.setPaint(plainPaint);
}
g2.draw(s);
}
}
}
}
| false | false | null | null |
diff --git a/src/game/GameAppEventual.java b/src/game/GameAppEventual.java
index acf2e69..654db0d 100644
--- a/src/game/GameAppEventual.java
+++ b/src/game/GameAppEventual.java
@@ -1,329 +1,330 @@
package game;
import java.util.Collection;
import java.util.Vector;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector3f;
import rice.p2p.commonapi.Application;
import rice.p2p.commonapi.CancellableTask;
import rice.p2p.commonapi.Endpoint;
import rice.p2p.commonapi.Id;
import rice.p2p.commonapi.Message;
import rice.p2p.commonapi.Node;
import rice.p2p.commonapi.NodeHandle;
import rice.p2p.commonapi.RouteMessage;
import rice.p2p.scribe.Scribe;
import rice.p2p.scribe.ScribeContent;
import rice.p2p.scribe.ScribeImpl;
import rice.p2p.scribe.Topic;
import rice.pastry.commonapi.PastryIdFactory;
import rice.p2p.scribe.ScribeMultiClient;
import java.util.Map;
public class GameAppEventual implements ScribeMultiClient, Application {
CancellableTask messageToSelfTask;
/**
* The Endpoint represents the underlieing node. By making calls on the
* Endpoint, it assures that the message will be delivered to a MyApp on whichever
* node the message is intended for.
*/
protected Endpoint endpoint;
protected Node node;
Scribe myScribe;
Topic myTopic;
GameModel game;
Vector<Topic> sendToTopics;
//Vector3f lastPosition;
PlayerDataScribeMsg allPlayerData;
public GameAppEventual(Node node, GameModel game)
{
// We are only going to use one instance of this application on each PastryNode
this.endpoint = node.buildEndpoint(this, "myinstance");
// the rest of the initialization code could go here
this.node = node;
// now we can receive messages
this.endpoint.register();
// Schedule a msg to be sent to self if we are not the bootstrap
if (game != null){
messageToSelfTask = this.endpoint.scheduleMessage(new MessageToSelf(), 100, 40);
sendToTopics = new Vector<Topic>();
allPlayerData = new PlayerDataScribeMsg(this.endpoint.getLocalNodeHandle());
}
// Lets set up scribe
myScribe = new ScribeImpl(node,"myScribeInstance");
this.game = game;
}
public Node getNode(){
return node;
}
/**
* Subscribes to myTopic.
*/
public void subscribe(Topic top) {
myScribe.subscribe(top, this);
// scribeTopics.add(top);
}
/**
* Unsubscribes to myTopic.
*/
public void unsubscribe(Topic top) {
//myScribe.addChild(myTopic, endpoint.getLocalNodeHandle());
myScribe.unsubscribe(top, this);
}
/**
* Called to route a message to a specific id, not using Scribe
*/
public void routeMyMsg(Id id) {
// System.out.println(this+" sending to "+id);
// Message msg = new MyMsg(endpoint.getId(), id);
//endpoint.route(id, msg, null);
}
/**
* Called to directly send a message to the nh, not using Scribe
*/
public void routeMyMsgDirect(NodeHandle nh) {
// System.out.println(this+" sending direct to "+nh);
// Message msg = new MyMsg(endpoint.getId(), nh.getId());
//endpoint.route(null, msg, nh);
}
public void sendMulticast(String s){
// not using this At the moment, using more specific multicasts
}
public void sendMoveEventMulticast()
{
/* ScribeMoveMsg myMessage = new ScribeMoveMsg(
endpoint.getLocalNodeHandle(),
position.x,position.y,position.z,
rotation.getW(), rotation.getX(), rotation.getY(), rotation.getZ());
*/
//Make my player data item
PlayerData myPlayer = new PlayerData();
myPlayer.position = game.getPlayerPosition();
myPlayer.rotation = game.getPlayerRotation();
myPlayer.setTime();
allPlayerData.updatePlayerData(endpoint.getLocalNodeHandle(), myPlayer);
for(int i = 0; i<sendToTopics.size(); i++){
myScribe.publish(sendToTopics.get(i), allPlayerData);
}
//System.out.println("Move Msg Sent!!");
}
public void sendChatMessage(String message){
ChatScribeMsg chatMsg = new ChatScribeMsg(endpoint.getLocalNodeHandle(),message);
for(int i = 0; i<sendToTopics.size(); i++){
myScribe.publish(sendToTopics.get(i), chatMsg);
}
}
public void sendRegionMulticast(boolean joined, Region newReg, Region oldReg)
{
RegionChangeScribeMsg message = new RegionChangeScribeMsg(endpoint.getLocalNodeHandle(),joined);
if (joined){
//If it is when we first joined the game, everyone must know
if (oldReg.x==-1 && oldReg.y==-1){
for(int i = 0; i<sendToTopics.size(); i++){
myScribe.publish(sendToTopics.get(i), message);
}
}else{
int diffX = newReg.x-oldReg.x;
int diffY = newReg.y-oldReg.y;
System.out.print("Telling these people I joined:");
for (int i=-1; i<2; i++){
Topic t;
if (diffX==0){
t = new Topic(new PastryIdFactory(node.getEnvironment()), "Region x:"+(newReg.x+i)+" y:"+(newReg.y+diffY));
System.out.print("x:"+(newReg.x+i)+" y:"+ (newReg.y+diffY)+" / ");
}else{
t = new Topic(new PastryIdFactory(node.getEnvironment()), "Region x:"+(newReg.x+diffX)+" y:"+(newReg.y+i));
System.out.print("x:"+(newReg.x+diffX)+" y:"+ (newReg.y+i)+" / ");
}
myScribe.publish(t, message);
}
}
}else{
// We are leaving a region, tell
int diffX = newReg.x-oldReg.x;
int diffY = newReg.y-oldReg.y;
for (int i=-1; i<2; i++){
Topic t;
if (diffX==0){
t = new Topic(new PastryIdFactory(node.getEnvironment()), "Region x:"+(oldReg.x+i)+" y:"+(oldReg.y-diffY));
}else{
t = new Topic(new PastryIdFactory(node.getEnvironment()), "Region x:"+(oldReg.x-diffX)+" y:"+(oldReg.y+i));
}
myScribe.publish(t, message);
}
}
}
/**
* Called when we receive a message directly.
*/
public void deliver(Id id, Message message) {
if (message instanceof MessageToSelf){
if (game != null){
if (game.regionChanged){
game.regionChanged=false;
Region newRegion = GameModel.getPlayersRegion(game.getPlayerPosition());
if (myTopic != null){
myScribe.unsubscribe(myTopic, this);
// We are leaving a region in this case, we need to tell everyone that we are leaving!
// DO NOT NEED TO DO THIS IN EVENTUAL, WE DO NOT REMOVE PLAYERS
//sendRegionMulticast(false,newRegion,game.region);
}
// Set the new region
Region oldRegion = game.region;
game.region = newRegion;
// This function removes everyone in old regions, because we will be re-adding them
//game.removePlayersByRegion(oldRegion,newRegion);
System.out.println("Region is x:"+game.region.x+" y:"+game.region.y);
myTopic = new Topic(new PastryIdFactory(node.getEnvironment()), "Region x:"+game.region.x+" y:"+game.region.y);
this.subscribe(myTopic);
sendToTopics = getSendToTopics(game.region);
// We need to tell everyone in our new region that we are there!
sendRegionMulticast(true, game.region,oldRegion);
sendMoveEventMulticast();
}
if (game.positionChanged){
game.positionChanged=false;
sendMoveEventMulticast();
}
}
}
}
/**
* This is Called when we receive a message from a scribe topic
*/
public void deliver(Topic topic, ScribeContent content) {
if (game != null && content instanceof PlayerDataScribeMsg)
{
PlayerDataScribeMsg message = (PlayerDataScribeMsg)content;
// Msg not from self
if (message.from != endpoint.getLocalNodeHandle()){
System.out.println("Move Rcvd: "+content);
// Lets get the players that are new and or have changed position
Vector<NodeHandle> changedPlayers = allPlayerData.dealWithNewPlayerDataSet(message);
for (int i=0; i<changedPlayers.size(); i++){
PlayerData data = allPlayerData.nodeToPlayerData.get(changedPlayers.get(i));
game.updatePlayer(changedPlayers.get(i), data.position, data.rotation);
}
}
}
else if (game != null && content instanceof RegionChangeScribeMsg)
{
RegionChangeScribeMsg message = (RegionChangeScribeMsg)content;
if (message.from != endpoint.getLocalNodeHandle()){
System.out.println("RegionChange Rcvd: "+content);
if (message.joinedRegion){
System.out.println("Tell them where I AM!");
sendMoveEventMulticast();
}else{
//Someone has left our region. Fuck them, remove em
// WE DO NOT REMOVE PLAYERS THAT LEAVE OUR REGION!
//game.removePlayer(message.from);
}
}
}
else if (game!=null && content instanceof ChatScribeMsg)
{
//Chat Msg, we need to call game's methods to get it drawn
game.receiveChatMessage(((ChatScribeMsg)content).chatter);
}
}
/**
* Called when you hear about a new neighbor.
* Don't worry about this method for now.
*/
public void update(NodeHandle handle, boolean joined) {
System.out.println("UPDATE MESSAGE!");
if (game == null){
if(joined){
System.out.println("Somone joined the ring");
// System.out.println("Sending out the Subscrbe!");
// TopicMsg tm = new TopicMsg();
// tm.addTopicName(myTopic);
// endpoint.route(null, tm, handle);
}else{
System.out.println("Someone exited the ring");
}
}else{
// This is all game nodes, NOT bootstrap
if (joined){
System.out.println("Someone joined the ring");
// Someone joined, everyone send out you position incase he is in your group!
//sendMoveEventMulticast(game.getPlayerPosition(), game.getPlayerRotation());
}else{
System.out.println("Someone exited the ring");
//Someone left, we need to remove their player from our map!
game.removePlayer(handle);
+ allPlayerData.playerLeftGame(handle);
}
}
}
/**
* Called when a message travels along your path.
* Don't worry about this method for now.
*/
public boolean forward(RouteMessage message) {
return true;
}
public String toString() {
return "MyApp "+endpoint.getId();
}
public void childAdded(Topic topic, NodeHandle child) {
// System.out.println("MyScribeClient.childAdded("+topic+","+child+")");
}
public void childRemoved(Topic topic, NodeHandle child) {
// System.out.println("MyScribeClient.childRemoved("+topic+","+child+")");
}
public void subscribeFailed(Topic topic) {
// System.out.println("MyScribeClient.childFailed("+topic+")");
}
public void subscribeFailed(Collection<Topic> topic) {
// System.out.println("MyScribeClient.childFailed("+topic+")");
}
public void subscribeSuccess(Collection<Topic> topic) {
// System.out.println("MyScribeClient.childFailed("+topic+")");
}
public boolean anycast(Topic topic, ScribeContent content) {
return true;
}
public Vector<Topic> getSendToTopics(Region r){
Vector<Topic> top = new Vector<Topic>();
//Get rid of messages past boundaries
for (int x = -1; x<2; x++){
for(int y=-1; y<2; y++){
Topic addTop = new Topic(new PastryIdFactory(node.getEnvironment()), "Region x:"+(game.region.x+x)+" y:"+(game.region.y+y));
top.add(addTop);
}
}
return top;
}
}
diff --git a/src/game/PlayerDataScribeMsg.java b/src/game/PlayerDataScribeMsg.java
index 85a7a45..0808e79 100644
--- a/src/game/PlayerDataScribeMsg.java
+++ b/src/game/PlayerDataScribeMsg.java
@@ -1,74 +1,81 @@
package game;
import rice.p2p.commonapi.NodeHandle;
import rice.p2p.scribe.ScribeContent;
import java.util.Map;
import java.util.HashMap;
import java.util.Vector;
import java.util.Iterator;
public class PlayerDataScribeMsg implements ScribeContent {
//Who sent the message?
NodeHandle from;
// Map that holds the player Data Structures
Map<NodeHandle,PlayerData> nodeToPlayerData;
/**
* Simple constructor. Typically, you would also like some
* interesting payload for your application.
*
* @param from Who sent the message.
* @param seq the sequence number of this content.
*/
public PlayerDataScribeMsg(NodeHandle from) {
nodeToPlayerData = new HashMap();
this.from = from;
}
// This function will handle the input of player data based on our mapping
// 1. If not in map, add him, this is the first we know about him
// 2. otherwise we need to see if this data more recent then what we have
// We return true if a change occurs, false otherwise
// This may be used to determine whether we foudn anything new out.
public boolean updatePlayerData(NodeHandle handle, PlayerData data){
if (!nodeToPlayerData.containsKey(handle)){
nodeToPlayerData.put(handle,data);
return true;
}
PlayerData ourData = nodeToPlayerData.get(handle);
if (data.timestamp.after(ourData.timestamp)){
//The data we receieved is more recent then what we have stored
nodeToPlayerData.remove(handle);
nodeToPlayerData.put(handle,data);
return true;
}
return false;
}
public Vector<NodeHandle> dealWithNewPlayerDataSet(PlayerDataScribeMsg set){
Vector<NodeHandle> retVector = new Vector();
//Go through each playerData in set
Iterator it = set.nodeToPlayerData.entrySet().iterator();
while (it.hasNext()){
Map.Entry<NodeHandle,PlayerData> pairs = (Map.Entry)it.next();
NodeHandle nh = pairs.getKey();
PlayerData data = pairs.getValue();
//Now we will compare it to our self
if (this.updatePlayerData(nh, data)){
//If we are here, that means theres was after ours, so its changed
retVector.add(nh);
}
}
return retVector;
}
+
+ public void playerLeftGame(NodeHandle nh){
+ if(nodeToPlayerData.containsKey(nh)){
+ nodeToPlayerData.remove(nh);
+ }
+ }
+
/**
* Ye ol' toString()
*/
public String toString() {
return "PlayerDataScribe";
}
}
| false | false | null | null |
diff --git a/trunk/org/xbill/DNS/TSIG.java b/trunk/org/xbill/DNS/TSIG.java
index 94d1676..6a7926a 100644
--- a/trunk/org/xbill/DNS/TSIG.java
+++ b/trunk/org/xbill/DNS/TSIG.java
@@ -1,234 +1,237 @@
// Copyright (c) 1999 Brian Wellington ([email protected])
// Portions Copyright (c) 1999 Network Associates, Inc.
package org.xbill.DNS;
import java.io.*;
import java.net.*;
import java.util.*;
import org.xbill.DNS.utils.*;
/**
* Transaction signature handling. This class generates and verifies
* TSIG records on messages, which provide transaction security,
* @see TSIGRecord
*
* @author Brian Wellington
*/
public class TSIG {
/**
* The domain name representing the HMAC-MD5 algorithm (the only supported
* algorithm)
*/
public static final String HMAC = "HMAC-MD5.SIG-ALG.REG.INT";
private Name name;
private byte [] key;
private hmacSigner axfrSigner = null;
/**
* Creates a new TSIG object, which can be used to sign or verify a message.
* @param name The name of the shared key
* @param key The shared key's data
*/
public
TSIG(String name, byte [] key) {
this.name = new Name(name);
this.key = key;
}
/**
* Generates a TSIG record for a message and adds it to the message
* @param m The message
* @param old If this message is a response, the TSIG from the request
*/
public void
apply(Message m, TSIGRecord old) throws IOException {
Date timeSigned = new Date();
short fudge = 300;
hmacSigner h = new hmacSigner(key);
Name alg = new Name(HMAC);
try {
if (old != null) {
DataByteOutputStream dbs = new DataByteOutputStream();
dbs.writeShort((short)old.getSignature().length);
h.addData(dbs.toByteArray());
h.addData(old.getSignature());
}
/* Digest the message */
h.addData(m.toWire());
DataByteOutputStream out = new DataByteOutputStream();
name.toWireCanonical(out);
out.writeShort(DClass.ANY); /* class */
out.writeInt(0); /* ttl */
alg.toWireCanonical(out);
long time = timeSigned.getTime() / 1000;
short timeHigh = (short) (time >> 32);
int timeLow = (int) (time);
out.writeShort(timeHigh);
out.writeInt(timeLow);
out.writeShort(fudge);
out.writeShort(0); /* No error */
out.writeShort(0); /* No other data */
h.addData(out.toByteArray());
}
catch (IOException e) {
return;
}
Record r = new TSIGRecord(name, DClass.ANY, 0, alg, timeSigned, fudge,
h.sign(), m.getHeader().getID(),
Rcode.NOERROR, null);
m.addRecord(r, Section.ADDITIONAL);
}
/**
* Verifies a TSIG record on an incoming message. Since this is only called
* in the context where a TSIG is expected to be present, it is an error
* if one is not present.
* @param m The message
* @param b The message in unparsed form. This is necessary since TSIG
* signs the message in wire format, and we can't recreate the exact wire
* format (with the same name compression).
* @param old If this message is a response, the TSIG from the request
*/
public boolean
verify(Message m, byte [] b, TSIGRecord old) {
TSIGRecord tsig = m.getTSIG();
hmacSigner h = new hmacSigner(key);
if (tsig == null)
return false;
/*System.out.println("found TSIG");*/
try {
if (old != null && tsig.getError() == Rcode.NOERROR) {
DataByteOutputStream dbs = new DataByteOutputStream();
dbs.writeShort((short)old.getSignature().length);
h.addData(dbs.toByteArray());
h.addData(old.getSignature());
/*System.out.println("digested query TSIG");*/
}
m.getHeader().decCount(Section.ADDITIONAL);
byte [] header = m.getHeader().toWire();
m.getHeader().incCount(Section.ADDITIONAL);
h.addData(header);
int len = b.length - header.length;
len -= tsig.wireLength;
h.addData(b, header.length, len);
/*System.out.println("digested message");*/
DataByteOutputStream out = new DataByteOutputStream();
tsig.getName().toWireCanonical(out);
out.writeShort(tsig.dclass);
out.writeInt(tsig.ttl);
tsig.getAlg().toWireCanonical(out);
long time = tsig.getTimeSigned().getTime() / 1000;
short timeHigh = (short) (time >> 32);
int timeLow = (int) (time);
out.writeShort(timeHigh);
out.writeInt(timeLow);
out.writeShort(tsig.getFudge());
out.writeShort(tsig.getError());
if (tsig.getOther() != null) {
out.writeShort(tsig.getOther().length);
out.write(tsig.getOther());
}
else
out.writeShort(0);
h.addData(out.toByteArray());
/*System.out.println("digested variables");*/
}
catch (IOException e) {
return false;
}
if (axfrSigner != null) {
DataByteOutputStream dbs = new DataByteOutputStream();
dbs.writeShort((short)tsig.getSignature().length);
axfrSigner.addData(dbs.toByteArray());
axfrSigner.addData(tsig.getSignature());
}
if (h.verify(tsig.getSignature()))
return true;
else
return false;
}
/** Prepares the TSIG object to verify an AXFR */
public void
verifyAXFRStart() {
axfrSigner = new hmacSigner(key);
}
/**
* Verifies a TSIG record on an incoming message that is part of an AXFR.
* TSIG records must be present on the first and last messages, and
* at least every 100 records in between (the last rule is not enforced).
* @param m The message
* @param b The message in unparsed form
* @param old The TSIG from the AXFR request
* @param required True if this message is required to include a TSIG.
* @param first True if this message is the first message of the AXFR
*/
public boolean
verifyAXFR(Message m, byte [] b, TSIGRecord old,
boolean required, boolean first)
{
TSIGRecord tsig = m.getTSIG();
hmacSigner h = axfrSigner;
if (first)
return verify(m, b, old);
try {
if (tsig != null)
m.getHeader().decCount(Section.ADDITIONAL);
byte [] header = m.getHeader().toWire();
if (tsig != null)
m.getHeader().incCount(Section.ADDITIONAL);
h.addData(header);
int len = b.length - header.length;
if (tsig != null)
len -= tsig.wireLength;
h.addData(b, header.length, len);
if (tsig == null) {
if (required)
return false;
else
return true;
}
DataByteOutputStream out = new DataByteOutputStream();
long time = tsig.getTimeSigned().getTime() / 1000;
short timeHigh = (short) (time >> 32);
int timeLow = (int) (time);
out.writeShort(timeHigh);
out.writeInt(timeLow);
out.writeShort(tsig.getFudge());
h.addData(out.toByteArray());
}
catch (IOException e) {
return false;
}
if (h.verify(tsig.getSignature()) == false) {
return false;
}
h.clear();
+ DataByteOutputStream dbs = new DataByteOutputStream();
+ dbs.writeShort((short)old.getSignature().length);
+ h.addData(dbs.toByteArray());
h.addData(tsig.getSignature());
return true;
}
}
| true | false | null | null |
diff --git a/core/engine/Vector2D.java b/core/engine/Vector2D.java
index 78247b9..006f915 100644
--- a/core/engine/Vector2D.java
+++ b/core/engine/Vector2D.java
@@ -1,30 +1,33 @@
package core.engine;
public class Vector2D {
public double x;
public double y;
public Vector2D(double x, double y){
this.x = x;
this.y = y;
}
public static Vector2D transform(Vector2D point, double trans[][]){
Vector2D result = new Vector2D(0,0);
result.x = trans[0][0]*point.x + trans[0][1]*point.y;
result.y = trans[1][0]*point.x + trans[1][1]*point.y;
return result;
}
public static double[][] rotationMatrix(double angle){
double [][] result = new double [2][2];
result [0][0] = Math.cos(angle);
result [0][1] = -Math.sin(angle);
result [1][0] = Math.sin(angle);
result [1][1] = Math.cos(angle);
return result;
}
public static Vector2D add(Vector2D v1, Vector2D v2){
return new Vector2D (v1.x+v2.x, v1.y+v2.y);
}
public static Vector2D dot(Vector2D v1, Vector2D v2){
return new Vector2D (v1.x*v2.x, v1.y*v2.y);
}
+ public static Vector2D times(Vector2D v, double t){
+ return new Vector2D (v.x*t, v.y*t);
+ }
}
diff --git a/graphics/GUI.java b/graphics/GUI.java
index 8727c6a..ad247d1 100644
--- a/graphics/GUI.java
+++ b/graphics/GUI.java
@@ -1,7 +1,10 @@
package graphics;
public class GUI{
public GUI(){
}
+ public void update(){
+
+ }
};
diff --git a/graphics/Renderer.java b/graphics/Renderer.java
index a53a85a..1222526 100644
--- a/graphics/Renderer.java
+++ b/graphics/Renderer.java
@@ -1,183 +1,187 @@
package graphics;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferStrategy;
import core.engine.Land;
import core.engine.Input;
import core.entities.GameEntity;
@SuppressWarnings("serial")
public class Renderer extends Canvas{
private JFrame frame;
private BufferStrategy buffer;
private Graphics g;
private Graphics2D g2D;
+
+ private GUI ui;
public final int width;
public final int height;
//constructor
public Renderer(Input inp){
width = 800;
height = 600;
frame = new JFrame("OOTanks");
+ ui = new GUI();
//get content of the frame, determine size
JPanel panel = (JPanel) frame.getContentPane();
panel.setPreferredSize(new Dimension(width,height));
panel.setLayout(null);
//set up canvas and boundaries, add panel to 'this' canvas
setBounds(0,0,width,height);
panel.add(this);
//we will paint manually, so
setIgnoreRepaint(true);
frame.setIgnoreRepaint(true);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//creating buffering strategy
createBufferStrategy(2);
buffer = getBufferStrategy();
//handle input init. Sadly, we need to you this out of our canvas
setKeyListener(inp);
}
//function to draw tank at (x,y) and rotate it by an angle in degrees
/**
* Draws a tank
* @param x X centre coordinate of the tank
* @param y Y centre coordinate of the tank
* @param angle
*/
public void drawTank(int x,int y,double angle, int id){
int w = 60;
int h = 30;
g2D.translate(x,y);
g2D.rotate(angle);
g2D.setColor(Color.darkGray);
g2D.drawRect(-w/2, -h/2, w, h);
g2D.fillRect(-w/2, -h/2, w, h);
g2D.setColor(Color.BLUE);
g2D.fillArc(-20,-10,20,20,0,360);
g2D.setColor(Color.RED);
g2D.drawRect(-w/2+30, -h/2+12, 21, 6);
g2D.fillRect(-w/2+30, -h/2+12, 21, 6);
g2D.rotate(-angle);
g2D.translate(-x,-y);
}
/**
* Draws a projectile
* @param x X centre coordinate of the Projectile
* @param y Y centre coordinate of the Projectile
* @param angle Angle of the Projectile
*/
public void drawShell(int x, int y, double angle, int id){
int d = 8;
g2D.translate(x,y);
g2D.rotate(angle);
g2D.setColor(Color.BLACK);
g2D.fillArc(-d/2, -d/2, d, d, 0, 360);
g2D.rotate(-angle);
g2D.translate(-x,-y);
}
/**
* Initialises the renderer, loads resources.
*/
public void init(){
//load resources here
}
/**
* Renders the game each frame
* @param map map that the objects will be taken from
*/
public void draw(double x, double y, double width, double height, double angle, int id){
if (id < 10)
drawTank((int)x,(int)y,angle,id);
else if (id < 20)
drawShell((int)x,(int)y,angle,id);
}
public void update(Land map){
//reset the graphics
g = null;
g2D = null;
// get ready to draw
g = buffer.getDrawGraphics();
//creating a java 2D graphic object
g2D = (Graphics2D) g;
//fill background to green (Green for no reason)
g2D.setColor(new Color(0,150,0));
g2D.fillRect(0,0,width,height);
//drawing will be done here
for (GameEntity e : map.gameEntities){
draw(e.getX(),e.getY(),e.getWidth(),e.getHeight(),e.getAngle(), e.getId());
}
// Garbage {
/* graphic.setColor(Color.blue);
int thickness = 4;
//not the most wise thing to do
for (int i = 0; i <= thickness; i++)
graphic.draw3DRect(600 - i, 510 - i, 80 + 2 * i, 30 + 2 * i, true); //use tabbing, especially when not using {}
//same as above
for (int i = 0; i < thickness; i++)
graphic.draw3DRect(600 - i, 550 - i, 80 + 2 * i, 30 + 2 * i, false); //use tabbing, especially when not using {}
int height = 200;
int width = 120;
graphic.setColor(Color.red);
graphic.drawRect(10, 10, height, width);
graphic.setColor(Color.gray);
graphic.fillRect(10, 10, height, width);
graphic.setColor(Color.red);
graphic.drawOval(250, 250, height, width);
graphic.setColor(Color.getYellow);
graphic.fillOval(250, 250, height, width);
*/
// }
//end of drawing
-
+
+ ui.update();
//syncs everything to smooth java frames
Toolkit.getDefaultToolkit().sync();
if(!buffer.contentsLost()){
buffer.show();
} else {
System.out.println("Data Lost in buffer");
}
}
/**
* Releases used resources
*/
public void release(){
}
/**
* Function for input handler and to sync Canvas
* @param inp input handler
*/
public void setKeyListener(Input inp) {
addKeyListener(inp);
requestFocus();
}
};
| false | false | null | null |
diff --git a/src/org/i4qwee/chgk/trainer/controller/brain/ScoreManagerSingleton.java b/src/org/i4qwee/chgk/trainer/controller/brain/ScoreManagerSingleton.java
index 726dfb4..40da9d2 100644
--- a/src/org/i4qwee/chgk/trainer/controller/brain/ScoreManagerSingleton.java
+++ b/src/org/i4qwee/chgk/trainer/controller/brain/ScoreManagerSingleton.java
@@ -1,92 +1,92 @@
package org.i4qwee.chgk.trainer.controller.brain;
import org.i4qwee.chgk.trainer.controller.brain.manager.*;
import org.i4qwee.chgk.trainer.model.enums.AnswerState;
import org.i4qwee.chgk.trainer.model.enums.GameState;
import java.util.Observable;
/**
* User: 4qwee
* Date: 30.10.11
* Time: 20:36
*/
public class ScoreManagerSingleton extends Observable
{
private static ScoreManagerSingleton ourInstance = new ScoreManagerSingleton();
private final ScoreManager scoreManager = ScoreManager.getInstance();
private final PriceManager priceManager = PriceManager.getInstance();
private final RoundManager roundManager = RoundManager.getInstance();
private final AnswerSideManager answerSideManager = AnswerSideManager.getInstance();
private final AnswerStateManager answerStateManager = AnswerStateManager.getInstance();
private final GameStateManager gameStateManager = GameStateManager.getInstance();
public static ScoreManagerSingleton getInstance()
{
return ourInstance;
}
private ScoreManagerSingleton()
{
}
public void setFalseStart()
{
answerStateManager.setAnswerState(AnswerState.ONE_ANSWERED);
gameStateManager.setGameState(GameState.RUNNING);
}
public void answer(boolean isCorrect)
{
if (isCorrect)
{
switch (answerSideManager.getAnswerSide())
{
case LEFT:
scoreManager.increaseLeftScore(priceManager.getPrice());
break;
case RIGHT:
scoreManager.increaseRightScore(priceManager.getPrice());
break;
}
priceManager.setPrice(1);
answerStateManager.setAnswerState(AnswerState.NOBODY_ANSWERED);
gameStateManager.setGameState(GameState.FINISHED);
setChanged();
notifyObservers();
}
else
{
switch (answerStateManager.getAnswerState())
{
case NOBODY_ANSWERED:
answerStateManager.setAnswerState(AnswerState.ONE_ANSWERED);
gameStateManager.setGameState(GameState.RUNNING);
break;
case ONE_ANSWERED:
noOneAnswered();
break;
}
}
}
public void noOneAnswered()
{
answerStateManager.setAnswerState(AnswerState.NOBODY_ANSWERED);
- gameStateManager.setGameState(GameState.FINISHED);
priceManager.setPrice(priceManager.getPrice() + 1);
+ gameStateManager.setGameState(GameState.FINISHED);
}
public void newGame()
{
gameStateManager.setGameState(GameState.INIT);
roundManager.setRound(1);
scoreManager.setLeftScore(0);
scoreManager.setRightScore(0);
priceManager.setPrice(1);
}
}
| false | false | null | null |
diff --git a/web/src/main/java/org/openmrs/web/filter/initialization/InitializationFilter.java b/web/src/main/java/org/openmrs/web/filter/initialization/InitializationFilter.java
index 952a6f2f..f6d6013e 100644
--- a/web/src/main/java/org/openmrs/web/filter/initialization/InitializationFilter.java
+++ b/web/src/main/java/org/openmrs/web/filter/initialization/InitializationFilter.java
@@ -1,1594 +1,1592 @@
/**
* 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.filter.initialization;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
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.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.zip.ZipInputStream;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import liquibase.changelog.ChangeSet;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Appender;
import org.apache.log4j.Logger;
import org.apache.xerces.impl.dv.util.Base64;
import org.openmrs.ImplementationId;
import org.openmrs.api.PasswordException;
import org.openmrs.api.context.Context;
import org.openmrs.module.MandatoryModuleException;
import org.openmrs.module.OpenmrsCoreModuleException;
import org.openmrs.module.web.WebModuleUtil;
import org.openmrs.scheduler.SchedulerUtil;
import org.openmrs.util.DatabaseUpdateException;
import org.openmrs.util.DatabaseUpdater;
import org.openmrs.util.DatabaseUpdater.ChangeSetExecutorCallback;
import org.openmrs.util.DatabaseUtil;
import org.openmrs.util.InputRequiredException;
import org.openmrs.util.MemoryAppender;
import org.openmrs.util.OpenmrsConstants;
import org.openmrs.util.OpenmrsUtil;
import org.openmrs.util.PrivilegeConstants;
import org.openmrs.util.Security;
import org.openmrs.web.Listener;
import org.openmrs.web.WebConstants;
import org.openmrs.web.filter.StartupFilter;
import org.openmrs.web.filter.util.CustomResourseLoader;
import org.openmrs.web.filter.util.ErrorMessageConstants;
import org.openmrs.web.filter.util.FilterUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.context.ContextLoader;
/**
* This is the first filter that is processed. It is only active when starting OpenMRS for the very
* first time. It will redirect all requests to the {@link WebConstants#SETUP_PAGE_URL} if the
* {@link Listener} wasn't able to find any runtime properties
*/
public class InitializationFilter extends StartupFilter {
private static final Log log = LogFactory.getLog(InitializationFilter.class);
private static final String LIQUIBASE_SCHEMA_DATA = "liquibase-schema-only.xml";
private static final String LIQUIBASE_CORE_DATA = "liquibase-core-data.xml";
private static final String LIQUIBASE_DEMO_DATA = "liquibase-demo-data.xml";
/**
* The very first page of wizard, that asks user for select his preferred language
*/
private final String CHOOSE_LANG = "chooselang.vm";
/**
* The second page of the wizard that asks for simple or advanced installation.
*/
private final String INSTALL_METHOD = "installmethod.vm";
/**
* The simple installation setup page.
*/
private final String SIMPLE_SETUP = "simplesetup.vm";
/**
* The first page of the advanced installation of the wizard that asks for a current or past
* database
*/
private final String DATABASE_SETUP = "databasesetup.vm";
/**
* The page from where the user specifies the url to a production system
*/
private final String TESTING_PRODUCTION_URL_SETUP = "productionurl.vm";
/**
* The velocity macro page to redirect to if an error occurs or on initial startup
*/
private final String DEFAULT_PAGE = CHOOSE_LANG;
/**
* This page asks whether database tables/demo data should be inserted and what the
* username/password that will be put into the runtime properties is
*/
private final String DATABASE_TABLES_AND_USER = "databasetablesanduser.vm";
/**
* This page lets the user define the admin user
*/
private static final String ADMIN_USER_SETUP = "adminusersetup.vm";
/**
* This page lets the user pick an implementation id
*/
private static final String IMPLEMENTATION_ID_SETUP = "implementationidsetup.vm";
/**
* This page asks for settings that will be put into the runtime properties files
*/
private final String OTHER_RUNTIME_PROPS = "otherruntimeproperties.vm";
/**
* A page that tells the user that everything is collected and will now be processed
*/
private static final String WIZARD_COMPLETE = "wizardcomplete.vm";
/**
* A page that lists off what is happening while it is going on. This page has ajax that callst
* he {@value #PROGRESS_VM_AJAXREQUEST} page
*/
private static final String PROGRESS_VM = "progress.vm";
/**
* This url is called by javascript to get the status of the install
*/
private static final String PROGRESS_VM_AJAXREQUEST = "progress.vm.ajaxRequest";
public static final String RELEASE_TESTING_MODULE_PATH = "/module/testing/";
/**
* The model object that holds all the properties that the rendered templates use. All
* attributes on this object are made available to all templates via reflection in the
* {@link #renderTemplate(String, Map, httpResponse)} method.
*/
private InitializationWizardModel wizardModel = null;
private InitializationCompletion initJob;
/**
* Variable set to true as soon as the installation begins and set to false when the process
* ends This thread should only be accesses through the synchronized method.
*/
private static boolean isInstallationStarted = false;
// the actual driver loaded by the DatabaseUpdater class
private String loadedDriverString;
/**
* Variable set at the end of the wizard when spring is being restarted
*/
private static boolean initializationComplete = false;
/**
* The login page when the testing install option is selected
*/
public static final String TESTING_AUTHENTICATION_SETUP = "authentication.vm";
synchronized protected void setInitializationComplete(boolean initializationComplete) {
InitializationFilter.initializationComplete = initializationComplete;
}
/**
* Called by {@link #doFilter(ServletRequest, ServletResponse, FilterChain)} on GET requests
*
* @param httpRequest
* @param httpResponse
*/
@Override
protected void doGet(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException,
ServletException {
String page = httpRequest.getParameter("page");
Map<String, Object> referenceMap = new HashMap<String, Object>();
// we need to save current user language in references map since it will be used when template
// will be rendered
if (httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE) != null) {
referenceMap
.put(FilterUtil.LOCALE_ATTRIBUTE, httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
}
if (page == null) {
checkLocaleAttributesForFirstTime(httpRequest);
referenceMap
.put(FilterUtil.LOCALE_ATTRIBUTE, httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
httpResponse.setContentType("text/html");
renderTemplate(DEFAULT_PAGE, referenceMap, httpResponse);
} else if (INSTALL_METHOD.equals(page)) {
// get props and render the second page
File runtimeProperties = getRuntimePropertiesFile();
if (!runtimeProperties.exists()) {
try {
runtimeProperties.createNewFile();
// reset the error objects in case of refresh
wizardModel.canCreate = true;
wizardModel.cannotCreateErrorMessage = "";
}
catch (IOException io) {
wizardModel.canCreate = false;
wizardModel.cannotCreateErrorMessage = io.getMessage();
}
// check this before deleting the file again
wizardModel.canWrite = runtimeProperties.canWrite();
// delete the file again after testing the create/write
// so that if the user stops the webapp before finishing
// this wizard, they can still get back into it
runtimeProperties.delete();
} else {
wizardModel.canWrite = runtimeProperties.canWrite();
wizardModel.databaseConnection = Context.getRuntimeProperties().getProperty("connection.url",
wizardModel.databaseConnection);
wizardModel.currentDatabaseUsername = Context.getRuntimeProperties().getProperty("connection.username",
wizardModel.currentDatabaseUsername);
wizardModel.currentDatabasePassword = Context.getRuntimeProperties().getProperty("connection.password",
wizardModel.currentDatabasePassword);
}
wizardModel.runtimePropertiesPath = runtimeProperties.getAbsolutePath();
// do step one of the wizard
httpResponse.setContentType("text/html");
// if any body has already started installation
if (isInstallationStarted()) {
renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
} else {
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
}
} else if (PROGRESS_VM_AJAXREQUEST.equals(page)) {
httpResponse.setContentType("text/json");
httpResponse.setHeader("Cache-Control", "no-cache");
Map<String, Object> result = new HashMap<String, Object>();
if (initJob != null) {
result.put("hasErrors", initJob.hasErrors());
if (initJob.hasErrors()) {
result.put("errorPage", initJob.getErrorPage());
errors.putAll(initJob.getErrors());
}
result.put("initializationComplete", isInitializationComplete());
result.put("message", initJob.getMessage());
result.put("actionCounter", initJob.getStepsComplete());
if (!isInitializationComplete()) {
result.put("executingTask", initJob.getExecutingTask());
result.put("executedTasks", initJob.getExecutedTasks());
result.put("completedPercentage", initJob.getCompletedPercentage());
}
Appender appender = Logger.getRootLogger().getAppender("MEMORY_APPENDER");
if (appender instanceof MemoryAppender) {
MemoryAppender memoryAppender = (MemoryAppender) appender;
List<String> logLines = memoryAppender.getLogLines();
// truncate the list to the last 5 so we don't overwhelm jquery
if (logLines.size() > 5)
logLines = logLines.subList(logLines.size() - 5, logLines.size());
result.put("logLines", logLines);
} else {
result.put("logLines", new ArrayList<String>());
}
}
httpResponse.getWriter().write(toJSONString(result, true));
}
}
/**
* Called by {@link #doFilter(ServletRequest, ServletResponse, FilterChain)} on POST requests
*
* @param httpRequest
* @param httpResponse
*/
@Override
protected void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException,
ServletException {
String page = httpRequest.getParameter("page");
Map<String, Object> referenceMap = new HashMap<String, Object>();
// we need to save current user language in references map since it will be used when template
// will be rendered
if (httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE) != null) {
referenceMap
.put(FilterUtil.LOCALE_ATTRIBUTE, httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
}
// if any body has already started installation
if (isInstallationStarted()) {
httpResponse.setContentType("text/html");
renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
return;
}
// if any body has already started installation
if (isInstallationStarted()) {
httpResponse.setContentType("text/html");
renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
return;
}
if (DEFAULT_PAGE.equals(page)) {
// get props and render the first page
File runtimeProperties = getRuntimePropertiesFile();
if (!runtimeProperties.exists()) {
try {
runtimeProperties.createNewFile();
// reset the error objects in case of refresh
wizardModel.canCreate = true;
wizardModel.cannotCreateErrorMessage = "";
}
catch (IOException io) {
wizardModel.canCreate = false;
wizardModel.cannotCreateErrorMessage = io.getMessage();
}
// check this before deleting the file again
wizardModel.canWrite = runtimeProperties.canWrite();
// delete the file again after testing the create/write
// so that if the user stops the webapp before finishing
// this wizard, they can still get back into it
runtimeProperties.delete();
} else {
wizardModel.canWrite = runtimeProperties.canWrite();
}
wizardModel.runtimePropertiesPath = runtimeProperties.getAbsolutePath();
checkLocaleAttributes(httpRequest);
referenceMap
.put(FilterUtil.LOCALE_ATTRIBUTE, httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
log.info("Locale stored in session is " + httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
httpResponse.setContentType("text/html");
// otherwise do step one of the wizard
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
} else if (INSTALL_METHOD.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
referenceMap.put(FilterUtil.REMEMBER_ATTRIBUTE,
httpRequest.getSession().getAttribute(FilterUtil.REMEMBER_ATTRIBUTE) != null);
referenceMap.put(FilterUtil.LOCALE_ATTRIBUTE,
httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
renderTemplate(CHOOSE_LANG, referenceMap, httpResponse);
return;
}
wizardModel.installMethod = httpRequest.getParameter("install_method");
if (InitializationWizardModel.INSTALL_METHOD_SIMPLE.equals(wizardModel.installMethod)) {
page = SIMPLE_SETUP;
} else if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
page = TESTING_PRODUCTION_URL_SETUP;
wizardModel.databaseName = InitializationWizardModel.DEFAULT_TEST_DATABASE_NAME;
} else {
page = DATABASE_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
} // simple method
else if (SIMPLE_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
return;
}
wizardModel.databaseConnection = Context.getRuntimeProperties().getProperty("connection.url",
wizardModel.databaseConnection);
wizardModel.createDatabaseUsername = Context.getRuntimeProperties().getProperty("connection.username",
wizardModel.createDatabaseUsername);
wizardModel.createUserUsername = wizardModel.createDatabaseUsername;
wizardModel.databaseRootPassword = httpRequest.getParameter("database_root_password");
checkForEmptyValue(wizardModel.databaseRootPassword, errors, ErrorMessageConstants.ERROR_DB_PSDW_REQ);
wizardModel.hasCurrentOpenmrsDatabase = false;
wizardModel.createTables = true;
// default wizardModel.databaseName is openmrs
// default wizardModel.createDatabaseUsername is root
wizardModel.createDatabasePassword = wizardModel.databaseRootPassword;
wizardModel.addDemoData = "yes".equals(httpRequest.getParameter("add_demo_data"));
wizardModel.hasCurrentDatabaseUser = false;
wizardModel.createDatabaseUser = true;
// default wizardModel.createUserUsername is root
wizardModel.createUserPassword = wizardModel.databaseRootPassword;
wizardModel.moduleWebAdmin = true;
wizardModel.autoUpdateDatabase = false;
wizardModel.adminUserPassword = InitializationWizardModel.ADMIN_DEFAULT_PASSWORD;
try {
loadedDriverString = DatabaseUtil.loadDatabaseDriver(wizardModel.databaseConnection,
wizardModel.databaseDriver);
}
catch (ClassNotFoundException e) {
errors.put(ErrorMessageConstants.ERROR_DB_DRIVER_CLASS_REQ, null);
renderTemplate(page, referenceMap, httpResponse);
return;
}
if (errors.isEmpty()) {
page = WIZARD_COMPLETE;
}
renderTemplate(page, referenceMap, httpResponse);
} // step one
else if (DATABASE_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
page = TESTING_AUTHENTICATION_SETUP;
} else {
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
}
return;
}
wizardModel.databaseConnection = httpRequest.getParameter("database_connection");
checkForEmptyValue(wizardModel.databaseConnection, errors, ErrorMessageConstants.ERROR_DB_CONN_REQ);
wizardModel.databaseDriver = httpRequest.getParameter("database_driver");
checkForEmptyValue(wizardModel.databaseConnection, errors, ErrorMessageConstants.ERROR_DB_DRIVER_REQ);
loadedDriverString = loadDriver(wizardModel.databaseConnection, wizardModel.databaseDriver);
if (!StringUtils.hasText(loadedDriverString)) {
errors.put(ErrorMessageConstants.ERROR_DB_DRIVER_CLASS_REQ, null);
renderTemplate(page, referenceMap, httpResponse);
return;
}
//TODO make each bit of page logic a (unit testable) method
// asked the user for their desired database name
if ("yes".equals(httpRequest.getParameter("current_openmrs_database"))) {
wizardModel.databaseName = httpRequest.getParameter("openmrs_current_database_name");
checkForEmptyValue(wizardModel.databaseName, errors, ErrorMessageConstants.ERROR_DB_CURR_NAME_REQ);
wizardModel.hasCurrentOpenmrsDatabase = true;
// TODO check to see if this is an active database
} else {
// mark this wizard as a "to create database" (done at the end)
wizardModel.hasCurrentOpenmrsDatabase = false;
wizardModel.createTables = true;
wizardModel.databaseName = httpRequest.getParameter("openmrs_new_database_name");
checkForEmptyValue(wizardModel.databaseName, errors, ErrorMessageConstants.ERROR_DB_NEW_NAME_REQ);
// TODO create database now to check if its possible?
wizardModel.createDatabaseUsername = httpRequest.getParameter("create_database_username");
checkForEmptyValue(wizardModel.createDatabaseUsername, errors, ErrorMessageConstants.ERROR_DB_USER_NAME_REQ);
wizardModel.createDatabasePassword = httpRequest.getParameter("create_database_password");
checkForEmptyValue(wizardModel.createDatabasePassword, errors, ErrorMessageConstants.ERROR_DB_USER_PSWD_REQ);
}
if (errors.isEmpty()) {
page = DATABASE_TABLES_AND_USER;
}
renderTemplate(page, referenceMap, httpResponse);
} // step two
else if (DATABASE_TABLES_AND_USER.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(DATABASE_SETUP, referenceMap, httpResponse);
return;
}
if (wizardModel.hasCurrentOpenmrsDatabase) {
wizardModel.createTables = "yes".equals(httpRequest.getParameter("create_tables"));
}
wizardModel.addDemoData = "yes".equals(httpRequest.getParameter("add_demo_data"));
if ("yes".equals(httpRequest.getParameter("current_database_user"))) {
wizardModel.currentDatabaseUsername = httpRequest.getParameter("current_database_username");
checkForEmptyValue(wizardModel.currentDatabaseUsername, errors,
ErrorMessageConstants.ERROR_DB_CUR_USER_NAME_REQ);
wizardModel.currentDatabasePassword = httpRequest.getParameter("current_database_password");
checkForEmptyValue(wizardModel.currentDatabasePassword, errors,
ErrorMessageConstants.ERROR_DB_CUR_USER_PSWD_REQ);
wizardModel.hasCurrentDatabaseUser = true;
wizardModel.createDatabaseUser = false;
} else {
wizardModel.hasCurrentDatabaseUser = false;
wizardModel.createDatabaseUser = true;
// asked for the root mysql username/password
wizardModel.createUserUsername = httpRequest.getParameter("create_user_username");
checkForEmptyValue(wizardModel.createUserUsername, errors, ErrorMessageConstants.ERROR_DB_USER_NAME_REQ);
wizardModel.createUserPassword = httpRequest.getParameter("create_user_password");
checkForEmptyValue(wizardModel.createUserPassword, errors, ErrorMessageConstants.ERROR_DB_USER_PSWD_REQ);
}
if (errors.isEmpty()) { // go to next page
page = InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod) ? WIZARD_COMPLETE
: OTHER_RUNTIME_PROPS;
}
renderTemplate(page, referenceMap, httpResponse);
} // step three
else if (OTHER_RUNTIME_PROPS.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(DATABASE_TABLES_AND_USER, referenceMap, httpResponse);
return;
}
wizardModel.moduleWebAdmin = "yes".equals(httpRequest.getParameter("module_web_admin"));
wizardModel.autoUpdateDatabase = "yes".equals(httpRequest.getParameter("auto_update_database"));
if (wizardModel.createTables) { // go to next page if they are creating tables
page = ADMIN_USER_SETUP;
} else { // skip a page
page = IMPLEMENTATION_ID_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
} // optional step four
else if (ADMIN_USER_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(OTHER_RUNTIME_PROPS, referenceMap, httpResponse);
return;
}
wizardModel.adminUserPassword = httpRequest.getParameter("new_admin_password");
String adminUserConfirm = httpRequest.getParameter("new_admin_password_confirm");
// throw back to admin user if passwords don't match
if (!wizardModel.adminUserPassword.equals(adminUserConfirm)) {
errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSWDS_MATCH, null);
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
return;
}
// throw back if the user didn't put in a password
if (wizardModel.adminUserPassword.equals("")) {
errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSDW_EMPTY, null);
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
return;
}
try {
OpenmrsUtil.validatePassword("admin", wizardModel.adminUserPassword, "admin");
}
catch (PasswordException p) {
errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSDW_WEAK, null);
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
return;
}
if (errors.isEmpty()) { // go to next page
page = IMPLEMENTATION_ID_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
} // optional step five
else if (IMPLEMENTATION_ID_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
if (wizardModel.createTables)
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
else
renderTemplate(OTHER_RUNTIME_PROPS, referenceMap, httpResponse);
return;
}
wizardModel.implementationIdName = httpRequest.getParameter("implementation_name");
wizardModel.implementationId = httpRequest.getParameter("implementation_id");
wizardModel.implementationIdPassPhrase = httpRequest.getParameter("pass_phrase");
wizardModel.implementationIdDescription = httpRequest.getParameter("description");
// throw back if the user-specified ID is invalid (contains ^ or |).
if (wizardModel.implementationId.indexOf('^') != -1 || wizardModel.implementationId.indexOf('|') != -1) {
errors.put(ErrorMessageConstants.ERROR_DB_IMPL_ID_REQ, null);
renderTemplate(IMPLEMENTATION_ID_SETUP, referenceMap, httpResponse);
return;
}
if (errors.isEmpty()) { // go to next page
page = WIZARD_COMPLETE;
}
renderTemplate(page, referenceMap, httpResponse);
} else if (WIZARD_COMPLETE.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
if (InitializationWizardModel.INSTALL_METHOD_SIMPLE.equals(wizardModel.installMethod)) {
page = SIMPLE_SETUP;
} else {
page = IMPLEMENTATION_ID_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
return;
}
wizardModel.tasksToExecute = new ArrayList<WizardTask>();
if (!wizardModel.hasCurrentOpenmrsDatabase)
wizardModel.tasksToExecute.add(WizardTask.CREATE_SCHEMA);
if (wizardModel.createDatabaseUser)
wizardModel.tasksToExecute.add(WizardTask.CREATE_DB_USER);
if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
wizardModel.importTestData = true;
- wizardModel.createTables = true;
+ wizardModel.createTables = false;
wizardModel.addDemoData = false;
- wizardModel.tasksToExecute.add(WizardTask.CREATE_TABLES);
- wizardModel.tasksToExecute.add(WizardTask.ADD_CORE_DATA);
wizardModel.tasksToExecute.add(WizardTask.IMPORT_TEST_DATA);
} else {
if (wizardModel.createTables) {
wizardModel.tasksToExecute.add(WizardTask.CREATE_TABLES);
wizardModel.tasksToExecute.add(WizardTask.ADD_CORE_DATA);
}
if (wizardModel.addDemoData)
wizardModel.tasksToExecute.add(WizardTask.ADD_DEMO_DATA);
}
wizardModel.tasksToExecute.add(WizardTask.UPDATE_TO_LATEST);
if (httpRequest.getSession().getAttribute(FilterUtil.REMEMBER_ATTRIBUTE) != null) {
wizardModel.localeToSave = String
.valueOf(httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
}
referenceMap.put("tasksToExecute", wizardModel.tasksToExecute);
//if no one has run any installation
if (!isInstallationStarted()) {
initJob = new InitializationCompletion();
setInstallationStarted(true);
initJob.start();
}
referenceMap.put("isInstallationStarted", isInstallationStarted());
renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
} else if (TESTING_PRODUCTION_URL_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
return;
}
wizardModel.productionUrl = httpRequest.getParameter("productionUrl");
checkForEmptyValue(wizardModel.productionUrl, errors, "install.testing.production.url.required");
if (errors.isEmpty()) {
//Check if the production system is running
if (TestInstallUtil.testConnection(wizardModel.productionUrl)) {
//Check if the test module is installed by connecting to its setting page
if (TestInstallUtil.testConnection(wizardModel.productionUrl.concat(RELEASE_TESTING_MODULE_PATH
+ "settings.htm"))) {
page = TESTING_AUTHENTICATION_SETUP;
} else {
errors.put("install.testing.noTestingModule", null);
}
} else {
errors.put("install.testing.invalidProductionUrl", new Object[] { wizardModel.productionUrl });
}
}
renderTemplate(page, referenceMap, httpResponse);
return;
} else if (TESTING_AUTHENTICATION_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(TESTING_PRODUCTION_URL_SETUP, referenceMap, httpResponse);
return;
}
//Authenticate to production server
wizardModel.productionUsername = httpRequest.getParameter("username");
wizardModel.productionPassword = httpRequest.getParameter("password");
checkForEmptyValue(wizardModel.productionUsername, errors, "install.testing.username.required");
checkForEmptyValue(wizardModel.productionPassword, errors, "install.testing.password.required");
if (errors.isEmpty())
page = DATABASE_SETUP;
renderTemplate(page, referenceMap, httpResponse);
return;
}
}
/**
* This method should be called after the user has left wizard's first page (i.e. choose
* language). It checks if user has changed any of locale related parameters and makes
* appropriate corrections with filter's model or/and with locale attribute inside user's
* session.
*
* @param httpRequest the http request object
*/
private void checkLocaleAttributes(HttpServletRequest httpRequest) {
String localeParameter = httpRequest.getParameter(FilterUtil.LOCALE_ATTRIBUTE);
Boolean rememberLocale = false;
// we need to check if user wants that system will remember his selection of language
if (httpRequest.getParameter(FilterUtil.REMEMBER_ATTRIBUTE) != null)
rememberLocale = true;
if (localeParameter != null) {
String storedLocale = null;
if (httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE) != null) {
storedLocale = httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE).toString();
}
// if user has changed locale parameter to new one
// or chooses it parameter at first page loading
if ((storedLocale == null) || (storedLocale != null && !storedLocale.equals(localeParameter))) {
log.info("Stored locale parameter to session " + localeParameter);
httpRequest.getSession().setAttribute(FilterUtil.LOCALE_ATTRIBUTE, localeParameter);
}
if (rememberLocale) {
httpRequest.getSession().setAttribute(FilterUtil.LOCALE_ATTRIBUTE, localeParameter);
httpRequest.getSession().setAttribute(FilterUtil.REMEMBER_ATTRIBUTE, true);
} else {
// we need to reset it if it was set before
httpRequest.getSession().setAttribute(FilterUtil.REMEMBER_ATTRIBUTE, null);
}
}
}
/**
* It sets locale parameter for current session when user is making first GET http request to
* application. It retrieves user locale from request object and checks if this locale is
* supported by application. If not, it uses {@link Locale#ENGLISH} by default
*
* @param httpRequest the http request object
*/
public void checkLocaleAttributesForFirstTime(HttpServletRequest httpRequest) {
Locale locale = httpRequest.getLocale();
if (CustomResourseLoader.getInstance(httpRequest).getAvailablelocales().contains(locale)) {
httpRequest.getSession().setAttribute(FilterUtil.LOCALE_ATTRIBUTE, locale.toString());
} else {
httpRequest.getSession().setAttribute(FilterUtil.LOCALE_ATTRIBUTE, Locale.ENGLISH.toString());
}
}
/**
* Verify the database connection works.
*
* @param connectionUsername
* @param connectionPassword
* @param databaseConnectionFinalUrl
* @return true/false whether it was verified or not
*/
private boolean verifyConnection(String connectionUsername, String connectionPassword, String databaseConnectionFinalUrl) {
try {
// verify connection
//Set Database Driver using driver String
Class.forName(loadedDriverString).newInstance();
DriverManager.getConnection(databaseConnectionFinalUrl, connectionUsername, connectionPassword);
return true;
}
catch (Exception e) {
errors.put("User account " + connectionUsername + " does not work. " + e.getMessage()
+ " See the error log for more details", null); // TODO internationalize this
log.warn("Error while checking the connection user account", e);
return false;
}
}
/**
* Convenience method to load the runtime properties file.
*
* @return the runtime properties file.
*/
private File getRuntimePropertiesFile() {
File file = null;
String pathName = OpenmrsUtil.getRuntimePropertiesFilePathName(WebConstants.WEBAPP_NAME);
if (pathName != null) {
file = new File(pathName);
} else
file = new File(OpenmrsUtil.getApplicationDataDirectory(), WebConstants.WEBAPP_NAME + "-runtime.properties");
log.debug("Using file: " + file.getAbsolutePath());
return file;
}
/**
* @see org.openmrs.web.filter.StartupFilter#getTemplatePrefix()
*/
@Override
protected String getTemplatePrefix() {
return "org/openmrs/web/filter/initialization/";
}
/**
* @see org.openmrs.web.filter.StartupFilter#getModel()
*/
@Override
protected Object getModel() {
return wizardModel;
}
/**
* @see org.openmrs.web.filter.StartupFilter#skipFilter()
*/
@Override
public boolean skipFilter(HttpServletRequest httpRequest) {
// If progress.vm makes an ajax request even immediately after initialization has completed
// let the request pass in order to let progress.vm load the start page of OpenMRS
// (otherwise progress.vm is displayed "forever")
return !PROGRESS_VM_AJAXREQUEST.equals(httpRequest.getParameter("page")) && !initializationRequired();
}
/**
* Public method that returns true if database+runtime properties initialization is required
*
* @return true if this initialization wizard needs to run
*/
public static boolean initializationRequired() {
return !isInitializationComplete();
}
/**
* @param isInstallationStarted the value to set
*/
protected static synchronized void setInstallationStarted(boolean isInstallationStarted) {
InitializationFilter.isInstallationStarted = isInstallationStarted;
}
/**
* @return true if installation has been started
*/
protected static boolean isInstallationStarted() {
return isInstallationStarted;
}
/**
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
@Override
public void init(FilterConfig filterConfig) throws ServletException {
super.init(filterConfig);
wizardModel = new InitializationWizardModel();
//set whether need to do initialization work
if (isDatabaseEmpty(OpenmrsUtil.getRuntimeProperties(WebConstants.WEBAPP_NAME))) {
//if runtime-properties file doesn't exist, have to do initialization work
setInitializationComplete(false);
} else {
//if database is not empty, then let UpdaterFilter to judge whether need database update
setInitializationComplete(true);
}
}
private void importTestDataSet(InputStream in, String connectionUrl, String connectionUsername, String connectionPassword)
throws IOException {
File tempFile = null;
FileOutputStream fileOut = null;
try {
ZipInputStream zipIn = new ZipInputStream(in);
zipIn.getNextEntry();
tempFile = File.createTempFile("testDataSet", "dump");
fileOut = new FileOutputStream(tempFile);
IOUtils.copy(zipIn, fileOut);
fileOut.close();
zipIn.close();
URI uri = URI.create(connectionUrl.substring(5));
String host = uri.getHost();
int port = uri.getPort();
TestInstallUtil.addTestData(host, port, wizardModel.databaseName, connectionUsername, connectionPassword,
tempFile.getAbsolutePath());
}
finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(fileOut);
if (tempFile != null) {
tempFile.delete();
}
}
}
/**
* @param silent if this statement fails do not display stack trace or record an error in the
* wizard object.
* @param user username to connect with
* @param pw password to connect with
* @param sql String containing sql and question marks
* @param args the strings to fill into the question marks in the given sql
* @return result of executeUpdate or -1 for error
*/
private int executeStatement(boolean silent, String user, String pw, String sql, String... args) {
Connection connection = null;
try {
String replacedSql = sql;
// TODO how to get the driver for the other dbs...
if (wizardModel.databaseConnection.contains("mysql")) {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} else {
replacedSql = replacedSql.replaceAll("`", "\"");
}
String tempDatabaseConnection = "";
if (sql.contains("create database")) {
tempDatabaseConnection = wizardModel.databaseConnection.replace("@DBNAME@", ""); // make this dbname agnostic so we can create the db
} else {
tempDatabaseConnection = wizardModel.databaseConnection.replace("@DBNAME@", wizardModel.databaseName);
}
connection = DriverManager.getConnection(tempDatabaseConnection, user, pw);
for (String arg : args) {
arg = arg.replace(";", "^"); // to prevent any sql injection
replacedSql = replacedSql.replaceFirst("\\?", arg);
}
// run the sql statement
Statement statement = connection.createStatement();
return statement.executeUpdate(replacedSql);
}
catch (SQLException sqlex) {
if (!silent) {
// log and add error
log.warn("error executing sql: " + sql, sqlex);
errors.put("Error executing sql: " + sql + " - " + sqlex.getMessage(), null);
}
}
catch (InstantiationException e) {
log.error("Error generated", e);
}
catch (IllegalAccessException e) {
log.error("Error generated", e);
}
catch (ClassNotFoundException e) {
log.error("Error generated", e);
}
finally {
try {
if (connection != null) {
connection.close();
}
}
catch (Throwable t) {
log.warn("Error while closing connection", t);
}
}
return -1;
}
/**
* Convenience variable to know if this wizard has completed successfully and that this wizard
* does not need to be executed again
*
* @return true if this has been run already
*/
synchronized private static boolean isInitializationComplete() {
return initializationComplete;
}
/**
* Check if the given value is null or a zero-length String
*
* @param value the string to check
* @param errors the list of errors to append the errorMessage to if value is empty
* @param errorMessageCode the string with code of error message translation to append if value
* is empty
* @return true if the value is non-empty
*/
private boolean checkForEmptyValue(String value, Map<String, Object[]> errors, String errorMessageCode) {
if (value != null && !value.equals("")) {
return true;
}
errors.put(errorMessageCode, null);
return false;
}
/**
* Separate thread that will run through all tasks to complete the initialization. The database
* is created, user's created, etc here
*/
private class InitializationCompletion {
private Thread thread;
private int steps = 0;
private String message = "";
private Map<String, Object[]> errors = new HashMap<String, Object[]>();
private String errorPage = null;
private boolean erroneous = false;
private int completedPercentage = 0;
private WizardTask executingTask;
private List<WizardTask> executedTasks = new ArrayList<WizardTask>();
synchronized public void reportError(String error, String errorPage, Object... params) {
errors.put(error, params);
this.errorPage = errorPage;
erroneous = true;
}
synchronized public boolean hasErrors() {
return erroneous;
}
synchronized public String getErrorPage() {
return errorPage;
}
synchronized public Map<String, Object[]> getErrors() {
return errors;
}
/**
* Start the completion stage. This fires up the thread to do all the work.
*/
public void start() {
setStepsComplete(0);
setInitializationComplete(false);
thread.start();
}
public void waitForCompletion() {
try {
thread.join();
}
catch (InterruptedException e) {
log.error("Error generated", e);
}
}
synchronized protected void setStepsComplete(int steps) {
this.steps = steps;
}
synchronized protected int getStepsComplete() {
return steps;
}
synchronized public String getMessage() {
return message;
}
synchronized public void setMessage(String message) {
this.message = message;
setStepsComplete(getStepsComplete() + 1);
}
/**
* @return the executingTask
*/
synchronized protected WizardTask getExecutingTask() {
return executingTask;
}
/**
* @return the completedPercentage
*/
protected synchronized int getCompletedPercentage() {
return completedPercentage;
}
/**
* @param completedPercentage the completedPercentage to set
*/
protected synchronized void setCompletedPercentage(int completedPercentage) {
this.completedPercentage = completedPercentage;
}
/**
* Adds a task that has been completed to the list of executed tasks
*
* @param task
*/
synchronized protected void addExecutedTask(WizardTask task) {
this.executedTasks.add(task);
}
/**
* @param executingTask the executingTask to set
*/
synchronized protected void setExecutingTask(WizardTask executingTask) {
this.executingTask = executingTask;
}
/**
* @return the executedTasks
*/
synchronized protected List<WizardTask> getExecutedTasks() {
return this.executedTasks;
}
/**
* This class does all the work of creating the desired database, user, updates, etc
*/
public InitializationCompletion() {
Runnable r = new Runnable() {
/**
* TODO split this up into multiple testable methods
*
* @see java.lang.Runnable#run()
*/
public void run() {
try {
String connectionUsername;
String connectionPassword;
if (!wizardModel.hasCurrentOpenmrsDatabase) {
setMessage("Create database");
setExecutingTask(WizardTask.CREATE_SCHEMA);
// connect via jdbc and create a database
String sql = "create database if not exists `?` default character set utf8";
int result = executeStatement(false, wizardModel.createDatabaseUsername,
wizardModel.createDatabasePassword, sql, wizardModel.databaseName);
// throw the user back to the main screen if this error occurs
if (result < 0) {
reportError(ErrorMessageConstants.ERROR_DB_CREATE_NEW, DEFAULT_PAGE);
return;
} else {
wizardModel.workLog.add("Created database " + wizardModel.databaseName);
}
addExecutedTask(WizardTask.CREATE_SCHEMA);
}
if (wizardModel.createDatabaseUser) {
setMessage("Create database user");
setExecutingTask(WizardTask.CREATE_DB_USER);
connectionUsername = wizardModel.databaseName + "_user";
if (connectionUsername.length() > 16)
connectionUsername = wizardModel.databaseName.substring(0, 11) + "_user"; // trim off enough to leave space for _user at the end
connectionPassword = "";
// generate random password from this subset of alphabet
// intentionally left out these characters: ufsb$() to prevent certain words forming randomly
String chars = "acdeghijklmnopqrtvwxyzACDEGHIJKLMNOPQRTVWXYZ0123456789.|~@#^&";
Random r = new Random();
for (int x = 0; x < 12; x++) {
connectionPassword += chars.charAt(r.nextInt(chars.length()));
}
// connect via jdbc with root user and create an openmrs user
String sql = "drop user '?'@'localhost'";
executeStatement(true, wizardModel.createUserUsername, wizardModel.createUserPassword, sql,
connectionUsername);
sql = "create user '?'@'localhost' identified by '?'";
if (-1 != executeStatement(false, wizardModel.createUserUsername,
wizardModel.createUserPassword, sql, connectionUsername, connectionPassword)) {
wizardModel.workLog.add("Created user " + connectionUsername);
} else {
// if error occurs stop
reportError(ErrorMessageConstants.ERROR_DB_CREATE_DB_USER, DEFAULT_PAGE);
return;
}
// grant the roles
sql = "GRANT ALL ON `?`.* TO '?'@'localhost'";
int result = executeStatement(false, wizardModel.createUserUsername,
wizardModel.createUserPassword, sql, wizardModel.databaseName, connectionUsername);
// throw the user back to the main screen if this error occurs
if (result < 0) {
reportError(ErrorMessageConstants.ERROR_DB_GRANT_PRIV, DEFAULT_PAGE);
return;
} else {
wizardModel.workLog.add("Granted user " + connectionUsername
+ " all privileges to database " + wizardModel.databaseName);
}
addExecutedTask(WizardTask.CREATE_DB_USER);
} else {
connectionUsername = wizardModel.currentDatabaseUsername;
connectionPassword = wizardModel.currentDatabasePassword;
}
String finalDatabaseConnectionString = wizardModel.databaseConnection.replace("@DBNAME@",
wizardModel.databaseName);
// verify that the database connection works
if (!verifyConnection(connectionUsername, connectionPassword, finalDatabaseConnectionString)) {
setMessage("Verify that the database connection works");
// redirect to setup page if we got an error
reportError("Unable to connect to database", DEFAULT_PAGE);
return;
}
// save the properties for startup purposes
Properties runtimeProperties = new Properties();
runtimeProperties.put("connection.url", finalDatabaseConnectionString);
runtimeProperties.put("connection.username", connectionUsername);
runtimeProperties.put("connection.password", connectionPassword);
if (StringUtils.hasText(wizardModel.databaseDriver))
runtimeProperties.put("connection.driver_class", wizardModel.databaseDriver);
runtimeProperties.put("module.allow_web_admin", wizardModel.moduleWebAdmin.toString());
runtimeProperties.put("auto_update_database", wizardModel.autoUpdateDatabase.toString());
runtimeProperties.put(OpenmrsConstants.ENCRYPTION_VECTOR_RUNTIME_PROPERTY,
Base64.encode(Security.generateNewInitVector()));
runtimeProperties.put(OpenmrsConstants.ENCRYPTION_KEY_RUNTIME_PROPERTY,
Base64.encode(Security.generateNewSecretKey()));
Properties properties = Context.getRuntimeProperties();
properties.putAll(runtimeProperties);
runtimeProperties = properties;
Context.setRuntimeProperties(runtimeProperties);
/**
* A callback class that prints out info about liquibase changesets
*/
class PrintingChangeSetExecutorCallback implements ChangeSetExecutorCallback {
private int i = 1;
private String message;
public PrintingChangeSetExecutorCallback(String message) {
this.message = message;
}
/**
* @see org.openmrs.util.DatabaseUpdater.ChangeSetExecutorCallback#executing(liquibase.ChangeSet,
* int)
*/
@Override
public void executing(ChangeSet changeSet, int numChangeSetsToRun) {
setMessage(message + " (" + i++ + "/" + numChangeSetsToRun + "): Author: "
+ changeSet.getAuthor() + " Comments: " + changeSet.getComments() + " Description: "
+ changeSet.getDescription());
setCompletedPercentage(Math.round(i * 100 / numChangeSetsToRun));
}
}
if (wizardModel.createTables) {
// use liquibase to create core data + tables
try {
setMessage("Executing " + LIQUIBASE_SCHEMA_DATA);
setExecutingTask(WizardTask.CREATE_TABLES);
DatabaseUpdater.executeChangelog(LIQUIBASE_SCHEMA_DATA, null,
new PrintingChangeSetExecutorCallback("OpenMRS schema file"));
addExecutedTask(WizardTask.CREATE_TABLES);
//reset for this task
setCompletedPercentage(0);
setExecutingTask(WizardTask.ADD_CORE_DATA);
DatabaseUpdater.executeChangelog(LIQUIBASE_CORE_DATA, null,
new PrintingChangeSetExecutorCallback("OpenMRS core data file"));
wizardModel.workLog.add("Created database tables and added core data");
addExecutedTask(WizardTask.ADD_CORE_DATA);
}
catch (Exception e) {
reportError(ErrorMessageConstants.ERROR_DB_CREATE_TABLES_OR_ADD_DEMO_DATA, DEFAULT_PAGE,
e.getMessage());
log.warn("Error while trying to create tables and demo data", e);
}
}
if (wizardModel.importTestData) {
try {
setMessage("Importing test data");
setExecutingTask(WizardTask.IMPORT_TEST_DATA);
setCompletedPercentage(0);
HttpURLConnection urlConnection = (HttpURLConnection) new URL(wizardModel.productionUrl
+ RELEASE_TESTING_MODULE_PATH + "generateTestDataSet.form").openConnection();
urlConnection.setConnectTimeout(5000);
urlConnection.setUseCaches(false);
importTestDataSet(urlConnection.getInputStream(), finalDatabaseConnectionString,
connectionUsername, connectionPassword);
setMessage("Importing installed modules...");
if (!TestInstallUtil.addZippedTestModules(new ZipInputStream(TestInstallUtil
.getResourceInputStream(wizardModel.productionUrl + RELEASE_TESTING_MODULE_PATH
+ "getModules.htm")))) {
reportError(ErrorMessageConstants.ERROR_DB_UNABLE_TO_ADD_MODULES, DEFAULT_PAGE,
new Object[] {});
log.warn("Failed to add modules");
}
wizardModel.workLog.add("Imported test data");
addExecutedTask(WizardTask.IMPORT_TEST_DATA);
}
catch (Exception e) {
reportError(ErrorMessageConstants.ERROR_DB_IMPORT_TEST_DATA, DEFAULT_PAGE, e.getMessage());
log.warn("Error while trying to import test data", e);
return;
}
}
// add demo data only if creating tables fresh and user selected the option add demo data
if (wizardModel.createTables && wizardModel.addDemoData) {
try {
setMessage("Adding demo data");
setCompletedPercentage(0);
setExecutingTask(WizardTask.ADD_DEMO_DATA);
DatabaseUpdater.executeChangelog(LIQUIBASE_DEMO_DATA, null,
new PrintingChangeSetExecutorCallback("OpenMRS demo patients, users, and forms"));
wizardModel.workLog.add("Added demo data");
addExecutedTask(WizardTask.ADD_DEMO_DATA);
}
catch (Exception e) {
reportError(ErrorMessageConstants.ERROR_DB_CREATE_TABLES_OR_ADD_DEMO_DATA, DEFAULT_PAGE,
e.getMessage());
log.warn("Error while trying to add demo data", e);
}
}
// update the database to the latest version
try {
setMessage("Updating the database to the latest version");
setCompletedPercentage(0);
setExecutingTask(WizardTask.UPDATE_TO_LATEST);
DatabaseUpdater.executeChangelog(null, null, new PrintingChangeSetExecutorCallback(
"Updating database tables to latest version "));
addExecutedTask(WizardTask.UPDATE_TO_LATEST);
}
catch (Exception e) {
reportError(ErrorMessageConstants.ERROR_DB_UPDATE_TO_LATEST, DEFAULT_PAGE, e.getMessage());
log.warn("Error while trying to update to the latest database version", e);
return;
}
setExecutingTask(null);
setMessage("Starting OpenMRS");
// start spring
// after this point, all errors need to also call: contextLoader.closeWebApplicationContext(event.getServletContext())
// logic copied from org.springframework.web.context.ContextLoaderListener
ContextLoader contextLoader = new ContextLoader();
contextLoader.initWebApplicationContext(filterConfig.getServletContext());
// start openmrs
try {
Context.openSession();
// load core modules so that required modules are known at openmrs startup
Listener.loadBundledModules(filterConfig.getServletContext());
Context.startup(runtimeProperties);
}
catch (DatabaseUpdateException updateEx) {
log.warn("Error while running the database update file", updateEx);
reportError(ErrorMessageConstants.ERROR_DB_UPDATE, DEFAULT_PAGE, updateEx.getMessage());
return;
}
catch (InputRequiredException inputRequiredEx) {
// TODO display a page looping over the required input and ask the user for each.
// When done and the user and put in their say, call DatabaseUpdater.update(Map);
// with the user's question/answer pairs
log.warn("Unable to continue because user input is required for the db updates and we cannot do anything about that right now");
reportError(ErrorMessageConstants.ERROR_INPUT_REQ, DEFAULT_PAGE);
return;
}
catch (MandatoryModuleException mandatoryModEx) {
log.warn(
"A mandatory module failed to start. Fix the error or unmark it as mandatory to continue.",
mandatoryModEx);
reportError(ErrorMessageConstants.ERROR_MANDATORY_MOD_REQ, DEFAULT_PAGE,
mandatoryModEx.getMessage());
return;
}
catch (OpenmrsCoreModuleException coreModEx) {
log.warn(
"A core module failed to start. Make sure that all core modules (with the required minimum versions) are installed and starting properly.",
coreModEx);
reportError(ErrorMessageConstants.ERROR_CORE_MOD_REQ, DEFAULT_PAGE, coreModEx.getMessage());
return;
}
// TODO catch openmrs errors here and drop the user back out to the setup screen
if (!wizardModel.implementationId.equals("")) {
try {
Context.addProxyPrivilege(PrivilegeConstants.MANAGE_GLOBAL_PROPERTIES);
Context.addProxyPrivilege(PrivilegeConstants.MANAGE_CONCEPT_SOURCES);
Context.addProxyPrivilege(PrivilegeConstants.VIEW_CONCEPT_SOURCES);
Context.addProxyPrivilege(PrivilegeConstants.MANAGE_IMPLEMENTATION_ID);
ImplementationId implId = new ImplementationId();
implId.setName(wizardModel.implementationIdName);
implId.setImplementationId(wizardModel.implementationId);
implId.setPassphrase(wizardModel.implementationIdPassPhrase);
implId.setDescription(wizardModel.implementationIdDescription);
Context.getAdministrationService().setImplementationId(implId);
}
catch (Throwable t) {
reportError(ErrorMessageConstants.ERROR_SET_INPL_ID, DEFAULT_PAGE, t.getMessage());
log.warn("Implementation ID could not be set.", t);
Context.shutdown();
WebModuleUtil.shutdownModules(filterConfig.getServletContext());
contextLoader.closeWebApplicationContext(filterConfig.getServletContext());
return;
}
finally {
Context.removeProxyPrivilege(PrivilegeConstants.MANAGE_GLOBAL_PROPERTIES);
Context.removeProxyPrivilege(PrivilegeConstants.MANAGE_CONCEPT_SOURCES);
Context.removeProxyPrivilege(PrivilegeConstants.VIEW_CONCEPT_SOURCES);
Context.removeProxyPrivilege(PrivilegeConstants.MANAGE_IMPLEMENTATION_ID);
}
}
try {
// change the admin user password from "test" to what they input above
if (wizardModel.createTables) {
Context.authenticate("admin", "test");
Context.getUserService().changePassword("test", wizardModel.adminUserPassword);
Context.logout();
}
// web load modules
Listener.performWebStartOfModules(filterConfig.getServletContext());
// start the scheduled tasks
SchedulerUtil.startup(runtimeProperties);
}
catch (Throwable t) {
Context.shutdown();
WebModuleUtil.shutdownModules(filterConfig.getServletContext());
contextLoader.closeWebApplicationContext(filterConfig.getServletContext());
reportError(ErrorMessageConstants.ERROR_COMPLETE_STARTUP, DEFAULT_PAGE, t.getMessage());
log.warn("Unable to complete the startup.", t);
return;
}
// output properties to the openmrs runtime properties file so that this wizard is not run again
FileOutputStream fos = null;
try {
fos = new FileOutputStream(getRuntimePropertiesFile());
OpenmrsUtil.storeProperties(runtimeProperties, fos,
"Auto generated by OpenMRS initialization wizard");
wizardModel.workLog.add("Saved runtime properties file " + getRuntimePropertiesFile());
// don't need to catch errors here because we tested it at the beginning of the wizard
}
finally {
if (fos != null) {
fos.close();
}
}
// set this so that the wizard isn't run again on next page load
Context.closeSession();
}
catch (IOException e) {
reportError(ErrorMessageConstants.ERROR_COMPLETE_STARTUP, DEFAULT_PAGE, e.getMessage());
}
finally {
if (!hasErrors()) {
// set this so that the wizard isn't run again on next page load
setInitializationComplete(true);
// we should also try to store selected by user language
// if user wants to system will do it for him
FilterUtil.storeLocale(wizardModel.localeToSave);
}
setInstallationStarted(false);
}
}
};
thread = new Thread(r);
}
}
/**
* Check whether openmrs database is empty. Having just one non-liquibase table in the given
* database qualifies this as a non-empty database.
*
* @param props the runtime properties
* @return true/false whether openmrs database is empty or doesn't exist yet
*/
private static boolean isDatabaseEmpty(Properties props) {
if (props != null) {
String databaseConnectionFinalUrl = props.getProperty("connection.url");
if (databaseConnectionFinalUrl == null)
return true;
String connectionUsername = props.getProperty("connection.username");
if (connectionUsername == null)
return true;
String connectionPassword = props.getProperty("connection.password");
if (connectionPassword == null)
return true;
Connection connection = null;
try {
DatabaseUtil.loadDatabaseDriver(databaseConnectionFinalUrl);
connection = DriverManager.getConnection(databaseConnectionFinalUrl, connectionUsername, connectionPassword);
DatabaseMetaData dbMetaData = (DatabaseMetaData) connection.getMetaData();
String[] types = { "TABLE" };
//get all tables
ResultSet tbls = dbMetaData.getTables(null, null, null, types);
while (tbls.next()) {
String tableName = tbls.getString("TABLE_NAME");
//if any table exist besides "liquibasechangelog" or "liquibasechangeloglock", return false
if (!("liquibasechangelog".equals(tableName)) && !("liquibasechangeloglock".equals(tableName)))
return false;
}
return true;
}
catch (Exception e) {
//pass
}
finally {
try {
if (connection != null) {
connection.close();
}
}
catch (Throwable t) {
//pass
}
}
//if catch an exception while query database, then consider as database is empty.
return true;
} else
return true;
}
/**
* Convenience method that loads the database driver
*
* @param connection the database connection string
* @param databaseDriver the database driver class name to load
* @return the loaded driver string
*/
public static String loadDriver(String connection, String databaseDriver) {
String loadedDriverString = null;
try {
loadedDriverString = DatabaseUtil.loadDatabaseDriver(connection, databaseDriver);
log.info("using database driver :" + loadedDriverString);
}
catch (ClassNotFoundException e) {
log.error("The given database driver class was not found. "
+ "Please ensure that the database driver jar file is on the class path "
+ "(like in the webapp's lib folder)");
}
return loadedDriverString;
}
}
| false | true | protected void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException,
ServletException {
String page = httpRequest.getParameter("page");
Map<String, Object> referenceMap = new HashMap<String, Object>();
// we need to save current user language in references map since it will be used when template
// will be rendered
if (httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE) != null) {
referenceMap
.put(FilterUtil.LOCALE_ATTRIBUTE, httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
}
// if any body has already started installation
if (isInstallationStarted()) {
httpResponse.setContentType("text/html");
renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
return;
}
// if any body has already started installation
if (isInstallationStarted()) {
httpResponse.setContentType("text/html");
renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
return;
}
if (DEFAULT_PAGE.equals(page)) {
// get props and render the first page
File runtimeProperties = getRuntimePropertiesFile();
if (!runtimeProperties.exists()) {
try {
runtimeProperties.createNewFile();
// reset the error objects in case of refresh
wizardModel.canCreate = true;
wizardModel.cannotCreateErrorMessage = "";
}
catch (IOException io) {
wizardModel.canCreate = false;
wizardModel.cannotCreateErrorMessage = io.getMessage();
}
// check this before deleting the file again
wizardModel.canWrite = runtimeProperties.canWrite();
// delete the file again after testing the create/write
// so that if the user stops the webapp before finishing
// this wizard, they can still get back into it
runtimeProperties.delete();
} else {
wizardModel.canWrite = runtimeProperties.canWrite();
}
wizardModel.runtimePropertiesPath = runtimeProperties.getAbsolutePath();
checkLocaleAttributes(httpRequest);
referenceMap
.put(FilterUtil.LOCALE_ATTRIBUTE, httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
log.info("Locale stored in session is " + httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
httpResponse.setContentType("text/html");
// otherwise do step one of the wizard
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
} else if (INSTALL_METHOD.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
referenceMap.put(FilterUtil.REMEMBER_ATTRIBUTE,
httpRequest.getSession().getAttribute(FilterUtil.REMEMBER_ATTRIBUTE) != null);
referenceMap.put(FilterUtil.LOCALE_ATTRIBUTE,
httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
renderTemplate(CHOOSE_LANG, referenceMap, httpResponse);
return;
}
wizardModel.installMethod = httpRequest.getParameter("install_method");
if (InitializationWizardModel.INSTALL_METHOD_SIMPLE.equals(wizardModel.installMethod)) {
page = SIMPLE_SETUP;
} else if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
page = TESTING_PRODUCTION_URL_SETUP;
wizardModel.databaseName = InitializationWizardModel.DEFAULT_TEST_DATABASE_NAME;
} else {
page = DATABASE_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
} // simple method
else if (SIMPLE_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
return;
}
wizardModel.databaseConnection = Context.getRuntimeProperties().getProperty("connection.url",
wizardModel.databaseConnection);
wizardModel.createDatabaseUsername = Context.getRuntimeProperties().getProperty("connection.username",
wizardModel.createDatabaseUsername);
wizardModel.createUserUsername = wizardModel.createDatabaseUsername;
wizardModel.databaseRootPassword = httpRequest.getParameter("database_root_password");
checkForEmptyValue(wizardModel.databaseRootPassword, errors, ErrorMessageConstants.ERROR_DB_PSDW_REQ);
wizardModel.hasCurrentOpenmrsDatabase = false;
wizardModel.createTables = true;
// default wizardModel.databaseName is openmrs
// default wizardModel.createDatabaseUsername is root
wizardModel.createDatabasePassword = wizardModel.databaseRootPassword;
wizardModel.addDemoData = "yes".equals(httpRequest.getParameter("add_demo_data"));
wizardModel.hasCurrentDatabaseUser = false;
wizardModel.createDatabaseUser = true;
// default wizardModel.createUserUsername is root
wizardModel.createUserPassword = wizardModel.databaseRootPassword;
wizardModel.moduleWebAdmin = true;
wizardModel.autoUpdateDatabase = false;
wizardModel.adminUserPassword = InitializationWizardModel.ADMIN_DEFAULT_PASSWORD;
try {
loadedDriverString = DatabaseUtil.loadDatabaseDriver(wizardModel.databaseConnection,
wizardModel.databaseDriver);
}
catch (ClassNotFoundException e) {
errors.put(ErrorMessageConstants.ERROR_DB_DRIVER_CLASS_REQ, null);
renderTemplate(page, referenceMap, httpResponse);
return;
}
if (errors.isEmpty()) {
page = WIZARD_COMPLETE;
}
renderTemplate(page, referenceMap, httpResponse);
} // step one
else if (DATABASE_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
page = TESTING_AUTHENTICATION_SETUP;
} else {
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
}
return;
}
wizardModel.databaseConnection = httpRequest.getParameter("database_connection");
checkForEmptyValue(wizardModel.databaseConnection, errors, ErrorMessageConstants.ERROR_DB_CONN_REQ);
wizardModel.databaseDriver = httpRequest.getParameter("database_driver");
checkForEmptyValue(wizardModel.databaseConnection, errors, ErrorMessageConstants.ERROR_DB_DRIVER_REQ);
loadedDriverString = loadDriver(wizardModel.databaseConnection, wizardModel.databaseDriver);
if (!StringUtils.hasText(loadedDriverString)) {
errors.put(ErrorMessageConstants.ERROR_DB_DRIVER_CLASS_REQ, null);
renderTemplate(page, referenceMap, httpResponse);
return;
}
//TODO make each bit of page logic a (unit testable) method
// asked the user for their desired database name
if ("yes".equals(httpRequest.getParameter("current_openmrs_database"))) {
wizardModel.databaseName = httpRequest.getParameter("openmrs_current_database_name");
checkForEmptyValue(wizardModel.databaseName, errors, ErrorMessageConstants.ERROR_DB_CURR_NAME_REQ);
wizardModel.hasCurrentOpenmrsDatabase = true;
// TODO check to see if this is an active database
} else {
// mark this wizard as a "to create database" (done at the end)
wizardModel.hasCurrentOpenmrsDatabase = false;
wizardModel.createTables = true;
wizardModel.databaseName = httpRequest.getParameter("openmrs_new_database_name");
checkForEmptyValue(wizardModel.databaseName, errors, ErrorMessageConstants.ERROR_DB_NEW_NAME_REQ);
// TODO create database now to check if its possible?
wizardModel.createDatabaseUsername = httpRequest.getParameter("create_database_username");
checkForEmptyValue(wizardModel.createDatabaseUsername, errors, ErrorMessageConstants.ERROR_DB_USER_NAME_REQ);
wizardModel.createDatabasePassword = httpRequest.getParameter("create_database_password");
checkForEmptyValue(wizardModel.createDatabasePassword, errors, ErrorMessageConstants.ERROR_DB_USER_PSWD_REQ);
}
if (errors.isEmpty()) {
page = DATABASE_TABLES_AND_USER;
}
renderTemplate(page, referenceMap, httpResponse);
} // step two
else if (DATABASE_TABLES_AND_USER.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(DATABASE_SETUP, referenceMap, httpResponse);
return;
}
if (wizardModel.hasCurrentOpenmrsDatabase) {
wizardModel.createTables = "yes".equals(httpRequest.getParameter("create_tables"));
}
wizardModel.addDemoData = "yes".equals(httpRequest.getParameter("add_demo_data"));
if ("yes".equals(httpRequest.getParameter("current_database_user"))) {
wizardModel.currentDatabaseUsername = httpRequest.getParameter("current_database_username");
checkForEmptyValue(wizardModel.currentDatabaseUsername, errors,
ErrorMessageConstants.ERROR_DB_CUR_USER_NAME_REQ);
wizardModel.currentDatabasePassword = httpRequest.getParameter("current_database_password");
checkForEmptyValue(wizardModel.currentDatabasePassword, errors,
ErrorMessageConstants.ERROR_DB_CUR_USER_PSWD_REQ);
wizardModel.hasCurrentDatabaseUser = true;
wizardModel.createDatabaseUser = false;
} else {
wizardModel.hasCurrentDatabaseUser = false;
wizardModel.createDatabaseUser = true;
// asked for the root mysql username/password
wizardModel.createUserUsername = httpRequest.getParameter("create_user_username");
checkForEmptyValue(wizardModel.createUserUsername, errors, ErrorMessageConstants.ERROR_DB_USER_NAME_REQ);
wizardModel.createUserPassword = httpRequest.getParameter("create_user_password");
checkForEmptyValue(wizardModel.createUserPassword, errors, ErrorMessageConstants.ERROR_DB_USER_PSWD_REQ);
}
if (errors.isEmpty()) { // go to next page
page = InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod) ? WIZARD_COMPLETE
: OTHER_RUNTIME_PROPS;
}
renderTemplate(page, referenceMap, httpResponse);
} // step three
else if (OTHER_RUNTIME_PROPS.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(DATABASE_TABLES_AND_USER, referenceMap, httpResponse);
return;
}
wizardModel.moduleWebAdmin = "yes".equals(httpRequest.getParameter("module_web_admin"));
wizardModel.autoUpdateDatabase = "yes".equals(httpRequest.getParameter("auto_update_database"));
if (wizardModel.createTables) { // go to next page if they are creating tables
page = ADMIN_USER_SETUP;
} else { // skip a page
page = IMPLEMENTATION_ID_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
} // optional step four
else if (ADMIN_USER_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(OTHER_RUNTIME_PROPS, referenceMap, httpResponse);
return;
}
wizardModel.adminUserPassword = httpRequest.getParameter("new_admin_password");
String adminUserConfirm = httpRequest.getParameter("new_admin_password_confirm");
// throw back to admin user if passwords don't match
if (!wizardModel.adminUserPassword.equals(adminUserConfirm)) {
errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSWDS_MATCH, null);
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
return;
}
// throw back if the user didn't put in a password
if (wizardModel.adminUserPassword.equals("")) {
errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSDW_EMPTY, null);
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
return;
}
try {
OpenmrsUtil.validatePassword("admin", wizardModel.adminUserPassword, "admin");
}
catch (PasswordException p) {
errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSDW_WEAK, null);
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
return;
}
if (errors.isEmpty()) { // go to next page
page = IMPLEMENTATION_ID_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
} // optional step five
else if (IMPLEMENTATION_ID_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
if (wizardModel.createTables)
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
else
renderTemplate(OTHER_RUNTIME_PROPS, referenceMap, httpResponse);
return;
}
wizardModel.implementationIdName = httpRequest.getParameter("implementation_name");
wizardModel.implementationId = httpRequest.getParameter("implementation_id");
wizardModel.implementationIdPassPhrase = httpRequest.getParameter("pass_phrase");
wizardModel.implementationIdDescription = httpRequest.getParameter("description");
// throw back if the user-specified ID is invalid (contains ^ or |).
if (wizardModel.implementationId.indexOf('^') != -1 || wizardModel.implementationId.indexOf('|') != -1) {
errors.put(ErrorMessageConstants.ERROR_DB_IMPL_ID_REQ, null);
renderTemplate(IMPLEMENTATION_ID_SETUP, referenceMap, httpResponse);
return;
}
if (errors.isEmpty()) { // go to next page
page = WIZARD_COMPLETE;
}
renderTemplate(page, referenceMap, httpResponse);
} else if (WIZARD_COMPLETE.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
if (InitializationWizardModel.INSTALL_METHOD_SIMPLE.equals(wizardModel.installMethod)) {
page = SIMPLE_SETUP;
} else {
page = IMPLEMENTATION_ID_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
return;
}
wizardModel.tasksToExecute = new ArrayList<WizardTask>();
if (!wizardModel.hasCurrentOpenmrsDatabase)
wizardModel.tasksToExecute.add(WizardTask.CREATE_SCHEMA);
if (wizardModel.createDatabaseUser)
wizardModel.tasksToExecute.add(WizardTask.CREATE_DB_USER);
if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
wizardModel.importTestData = true;
wizardModel.createTables = true;
wizardModel.addDemoData = false;
wizardModel.tasksToExecute.add(WizardTask.CREATE_TABLES);
wizardModel.tasksToExecute.add(WizardTask.ADD_CORE_DATA);
wizardModel.tasksToExecute.add(WizardTask.IMPORT_TEST_DATA);
} else {
if (wizardModel.createTables) {
wizardModel.tasksToExecute.add(WizardTask.CREATE_TABLES);
wizardModel.tasksToExecute.add(WizardTask.ADD_CORE_DATA);
}
if (wizardModel.addDemoData)
wizardModel.tasksToExecute.add(WizardTask.ADD_DEMO_DATA);
}
wizardModel.tasksToExecute.add(WizardTask.UPDATE_TO_LATEST);
if (httpRequest.getSession().getAttribute(FilterUtil.REMEMBER_ATTRIBUTE) != null) {
wizardModel.localeToSave = String
.valueOf(httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
}
referenceMap.put("tasksToExecute", wizardModel.tasksToExecute);
//if no one has run any installation
if (!isInstallationStarted()) {
initJob = new InitializationCompletion();
setInstallationStarted(true);
initJob.start();
}
referenceMap.put("isInstallationStarted", isInstallationStarted());
renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
} else if (TESTING_PRODUCTION_URL_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
return;
}
wizardModel.productionUrl = httpRequest.getParameter("productionUrl");
checkForEmptyValue(wizardModel.productionUrl, errors, "install.testing.production.url.required");
if (errors.isEmpty()) {
//Check if the production system is running
if (TestInstallUtil.testConnection(wizardModel.productionUrl)) {
//Check if the test module is installed by connecting to its setting page
if (TestInstallUtil.testConnection(wizardModel.productionUrl.concat(RELEASE_TESTING_MODULE_PATH
+ "settings.htm"))) {
page = TESTING_AUTHENTICATION_SETUP;
} else {
errors.put("install.testing.noTestingModule", null);
}
} else {
errors.put("install.testing.invalidProductionUrl", new Object[] { wizardModel.productionUrl });
}
}
renderTemplate(page, referenceMap, httpResponse);
return;
} else if (TESTING_AUTHENTICATION_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(TESTING_PRODUCTION_URL_SETUP, referenceMap, httpResponse);
return;
}
//Authenticate to production server
wizardModel.productionUsername = httpRequest.getParameter("username");
wizardModel.productionPassword = httpRequest.getParameter("password");
checkForEmptyValue(wizardModel.productionUsername, errors, "install.testing.username.required");
checkForEmptyValue(wizardModel.productionPassword, errors, "install.testing.password.required");
if (errors.isEmpty())
page = DATABASE_SETUP;
renderTemplate(page, referenceMap, httpResponse);
return;
}
}
| protected void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException,
ServletException {
String page = httpRequest.getParameter("page");
Map<String, Object> referenceMap = new HashMap<String, Object>();
// we need to save current user language in references map since it will be used when template
// will be rendered
if (httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE) != null) {
referenceMap
.put(FilterUtil.LOCALE_ATTRIBUTE, httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
}
// if any body has already started installation
if (isInstallationStarted()) {
httpResponse.setContentType("text/html");
renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
return;
}
// if any body has already started installation
if (isInstallationStarted()) {
httpResponse.setContentType("text/html");
renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
return;
}
if (DEFAULT_PAGE.equals(page)) {
// get props and render the first page
File runtimeProperties = getRuntimePropertiesFile();
if (!runtimeProperties.exists()) {
try {
runtimeProperties.createNewFile();
// reset the error objects in case of refresh
wizardModel.canCreate = true;
wizardModel.cannotCreateErrorMessage = "";
}
catch (IOException io) {
wizardModel.canCreate = false;
wizardModel.cannotCreateErrorMessage = io.getMessage();
}
// check this before deleting the file again
wizardModel.canWrite = runtimeProperties.canWrite();
// delete the file again after testing the create/write
// so that if the user stops the webapp before finishing
// this wizard, they can still get back into it
runtimeProperties.delete();
} else {
wizardModel.canWrite = runtimeProperties.canWrite();
}
wizardModel.runtimePropertiesPath = runtimeProperties.getAbsolutePath();
checkLocaleAttributes(httpRequest);
referenceMap
.put(FilterUtil.LOCALE_ATTRIBUTE, httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
log.info("Locale stored in session is " + httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
httpResponse.setContentType("text/html");
// otherwise do step one of the wizard
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
} else if (INSTALL_METHOD.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
referenceMap.put(FilterUtil.REMEMBER_ATTRIBUTE,
httpRequest.getSession().getAttribute(FilterUtil.REMEMBER_ATTRIBUTE) != null);
referenceMap.put(FilterUtil.LOCALE_ATTRIBUTE,
httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
renderTemplate(CHOOSE_LANG, referenceMap, httpResponse);
return;
}
wizardModel.installMethod = httpRequest.getParameter("install_method");
if (InitializationWizardModel.INSTALL_METHOD_SIMPLE.equals(wizardModel.installMethod)) {
page = SIMPLE_SETUP;
} else if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
page = TESTING_PRODUCTION_URL_SETUP;
wizardModel.databaseName = InitializationWizardModel.DEFAULT_TEST_DATABASE_NAME;
} else {
page = DATABASE_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
} // simple method
else if (SIMPLE_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
return;
}
wizardModel.databaseConnection = Context.getRuntimeProperties().getProperty("connection.url",
wizardModel.databaseConnection);
wizardModel.createDatabaseUsername = Context.getRuntimeProperties().getProperty("connection.username",
wizardModel.createDatabaseUsername);
wizardModel.createUserUsername = wizardModel.createDatabaseUsername;
wizardModel.databaseRootPassword = httpRequest.getParameter("database_root_password");
checkForEmptyValue(wizardModel.databaseRootPassword, errors, ErrorMessageConstants.ERROR_DB_PSDW_REQ);
wizardModel.hasCurrentOpenmrsDatabase = false;
wizardModel.createTables = true;
// default wizardModel.databaseName is openmrs
// default wizardModel.createDatabaseUsername is root
wizardModel.createDatabasePassword = wizardModel.databaseRootPassword;
wizardModel.addDemoData = "yes".equals(httpRequest.getParameter("add_demo_data"));
wizardModel.hasCurrentDatabaseUser = false;
wizardModel.createDatabaseUser = true;
// default wizardModel.createUserUsername is root
wizardModel.createUserPassword = wizardModel.databaseRootPassword;
wizardModel.moduleWebAdmin = true;
wizardModel.autoUpdateDatabase = false;
wizardModel.adminUserPassword = InitializationWizardModel.ADMIN_DEFAULT_PASSWORD;
try {
loadedDriverString = DatabaseUtil.loadDatabaseDriver(wizardModel.databaseConnection,
wizardModel.databaseDriver);
}
catch (ClassNotFoundException e) {
errors.put(ErrorMessageConstants.ERROR_DB_DRIVER_CLASS_REQ, null);
renderTemplate(page, referenceMap, httpResponse);
return;
}
if (errors.isEmpty()) {
page = WIZARD_COMPLETE;
}
renderTemplate(page, referenceMap, httpResponse);
} // step one
else if (DATABASE_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
page = TESTING_AUTHENTICATION_SETUP;
} else {
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
}
return;
}
wizardModel.databaseConnection = httpRequest.getParameter("database_connection");
checkForEmptyValue(wizardModel.databaseConnection, errors, ErrorMessageConstants.ERROR_DB_CONN_REQ);
wizardModel.databaseDriver = httpRequest.getParameter("database_driver");
checkForEmptyValue(wizardModel.databaseConnection, errors, ErrorMessageConstants.ERROR_DB_DRIVER_REQ);
loadedDriverString = loadDriver(wizardModel.databaseConnection, wizardModel.databaseDriver);
if (!StringUtils.hasText(loadedDriverString)) {
errors.put(ErrorMessageConstants.ERROR_DB_DRIVER_CLASS_REQ, null);
renderTemplate(page, referenceMap, httpResponse);
return;
}
//TODO make each bit of page logic a (unit testable) method
// asked the user for their desired database name
if ("yes".equals(httpRequest.getParameter("current_openmrs_database"))) {
wizardModel.databaseName = httpRequest.getParameter("openmrs_current_database_name");
checkForEmptyValue(wizardModel.databaseName, errors, ErrorMessageConstants.ERROR_DB_CURR_NAME_REQ);
wizardModel.hasCurrentOpenmrsDatabase = true;
// TODO check to see if this is an active database
} else {
// mark this wizard as a "to create database" (done at the end)
wizardModel.hasCurrentOpenmrsDatabase = false;
wizardModel.createTables = true;
wizardModel.databaseName = httpRequest.getParameter("openmrs_new_database_name");
checkForEmptyValue(wizardModel.databaseName, errors, ErrorMessageConstants.ERROR_DB_NEW_NAME_REQ);
// TODO create database now to check if its possible?
wizardModel.createDatabaseUsername = httpRequest.getParameter("create_database_username");
checkForEmptyValue(wizardModel.createDatabaseUsername, errors, ErrorMessageConstants.ERROR_DB_USER_NAME_REQ);
wizardModel.createDatabasePassword = httpRequest.getParameter("create_database_password");
checkForEmptyValue(wizardModel.createDatabasePassword, errors, ErrorMessageConstants.ERROR_DB_USER_PSWD_REQ);
}
if (errors.isEmpty()) {
page = DATABASE_TABLES_AND_USER;
}
renderTemplate(page, referenceMap, httpResponse);
} // step two
else if (DATABASE_TABLES_AND_USER.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(DATABASE_SETUP, referenceMap, httpResponse);
return;
}
if (wizardModel.hasCurrentOpenmrsDatabase) {
wizardModel.createTables = "yes".equals(httpRequest.getParameter("create_tables"));
}
wizardModel.addDemoData = "yes".equals(httpRequest.getParameter("add_demo_data"));
if ("yes".equals(httpRequest.getParameter("current_database_user"))) {
wizardModel.currentDatabaseUsername = httpRequest.getParameter("current_database_username");
checkForEmptyValue(wizardModel.currentDatabaseUsername, errors,
ErrorMessageConstants.ERROR_DB_CUR_USER_NAME_REQ);
wizardModel.currentDatabasePassword = httpRequest.getParameter("current_database_password");
checkForEmptyValue(wizardModel.currentDatabasePassword, errors,
ErrorMessageConstants.ERROR_DB_CUR_USER_PSWD_REQ);
wizardModel.hasCurrentDatabaseUser = true;
wizardModel.createDatabaseUser = false;
} else {
wizardModel.hasCurrentDatabaseUser = false;
wizardModel.createDatabaseUser = true;
// asked for the root mysql username/password
wizardModel.createUserUsername = httpRequest.getParameter("create_user_username");
checkForEmptyValue(wizardModel.createUserUsername, errors, ErrorMessageConstants.ERROR_DB_USER_NAME_REQ);
wizardModel.createUserPassword = httpRequest.getParameter("create_user_password");
checkForEmptyValue(wizardModel.createUserPassword, errors, ErrorMessageConstants.ERROR_DB_USER_PSWD_REQ);
}
if (errors.isEmpty()) { // go to next page
page = InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod) ? WIZARD_COMPLETE
: OTHER_RUNTIME_PROPS;
}
renderTemplate(page, referenceMap, httpResponse);
} // step three
else if (OTHER_RUNTIME_PROPS.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(DATABASE_TABLES_AND_USER, referenceMap, httpResponse);
return;
}
wizardModel.moduleWebAdmin = "yes".equals(httpRequest.getParameter("module_web_admin"));
wizardModel.autoUpdateDatabase = "yes".equals(httpRequest.getParameter("auto_update_database"));
if (wizardModel.createTables) { // go to next page if they are creating tables
page = ADMIN_USER_SETUP;
} else { // skip a page
page = IMPLEMENTATION_ID_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
} // optional step four
else if (ADMIN_USER_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(OTHER_RUNTIME_PROPS, referenceMap, httpResponse);
return;
}
wizardModel.adminUserPassword = httpRequest.getParameter("new_admin_password");
String adminUserConfirm = httpRequest.getParameter("new_admin_password_confirm");
// throw back to admin user if passwords don't match
if (!wizardModel.adminUserPassword.equals(adminUserConfirm)) {
errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSWDS_MATCH, null);
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
return;
}
// throw back if the user didn't put in a password
if (wizardModel.adminUserPassword.equals("")) {
errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSDW_EMPTY, null);
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
return;
}
try {
OpenmrsUtil.validatePassword("admin", wizardModel.adminUserPassword, "admin");
}
catch (PasswordException p) {
errors.put(ErrorMessageConstants.ERROR_DB_ADM_PSDW_WEAK, null);
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
return;
}
if (errors.isEmpty()) { // go to next page
page = IMPLEMENTATION_ID_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
} // optional step five
else if (IMPLEMENTATION_ID_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
if (wizardModel.createTables)
renderTemplate(ADMIN_USER_SETUP, referenceMap, httpResponse);
else
renderTemplate(OTHER_RUNTIME_PROPS, referenceMap, httpResponse);
return;
}
wizardModel.implementationIdName = httpRequest.getParameter("implementation_name");
wizardModel.implementationId = httpRequest.getParameter("implementation_id");
wizardModel.implementationIdPassPhrase = httpRequest.getParameter("pass_phrase");
wizardModel.implementationIdDescription = httpRequest.getParameter("description");
// throw back if the user-specified ID is invalid (contains ^ or |).
if (wizardModel.implementationId.indexOf('^') != -1 || wizardModel.implementationId.indexOf('|') != -1) {
errors.put(ErrorMessageConstants.ERROR_DB_IMPL_ID_REQ, null);
renderTemplate(IMPLEMENTATION_ID_SETUP, referenceMap, httpResponse);
return;
}
if (errors.isEmpty()) { // go to next page
page = WIZARD_COMPLETE;
}
renderTemplate(page, referenceMap, httpResponse);
} else if (WIZARD_COMPLETE.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
if (InitializationWizardModel.INSTALL_METHOD_SIMPLE.equals(wizardModel.installMethod)) {
page = SIMPLE_SETUP;
} else {
page = IMPLEMENTATION_ID_SETUP;
}
renderTemplate(page, referenceMap, httpResponse);
return;
}
wizardModel.tasksToExecute = new ArrayList<WizardTask>();
if (!wizardModel.hasCurrentOpenmrsDatabase)
wizardModel.tasksToExecute.add(WizardTask.CREATE_SCHEMA);
if (wizardModel.createDatabaseUser)
wizardModel.tasksToExecute.add(WizardTask.CREATE_DB_USER);
if (InitializationWizardModel.INSTALL_METHOD_TESTING.equals(wizardModel.installMethod)) {
wizardModel.importTestData = true;
wizardModel.createTables = false;
wizardModel.addDemoData = false;
wizardModel.tasksToExecute.add(WizardTask.IMPORT_TEST_DATA);
} else {
if (wizardModel.createTables) {
wizardModel.tasksToExecute.add(WizardTask.CREATE_TABLES);
wizardModel.tasksToExecute.add(WizardTask.ADD_CORE_DATA);
}
if (wizardModel.addDemoData)
wizardModel.tasksToExecute.add(WizardTask.ADD_DEMO_DATA);
}
wizardModel.tasksToExecute.add(WizardTask.UPDATE_TO_LATEST);
if (httpRequest.getSession().getAttribute(FilterUtil.REMEMBER_ATTRIBUTE) != null) {
wizardModel.localeToSave = String
.valueOf(httpRequest.getSession().getAttribute(FilterUtil.LOCALE_ATTRIBUTE));
}
referenceMap.put("tasksToExecute", wizardModel.tasksToExecute);
//if no one has run any installation
if (!isInstallationStarted()) {
initJob = new InitializationCompletion();
setInstallationStarted(true);
initJob.start();
}
referenceMap.put("isInstallationStarted", isInstallationStarted());
renderTemplate(PROGRESS_VM, referenceMap, httpResponse);
} else if (TESTING_PRODUCTION_URL_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(INSTALL_METHOD, referenceMap, httpResponse);
return;
}
wizardModel.productionUrl = httpRequest.getParameter("productionUrl");
checkForEmptyValue(wizardModel.productionUrl, errors, "install.testing.production.url.required");
if (errors.isEmpty()) {
//Check if the production system is running
if (TestInstallUtil.testConnection(wizardModel.productionUrl)) {
//Check if the test module is installed by connecting to its setting page
if (TestInstallUtil.testConnection(wizardModel.productionUrl.concat(RELEASE_TESTING_MODULE_PATH
+ "settings.htm"))) {
page = TESTING_AUTHENTICATION_SETUP;
} else {
errors.put("install.testing.noTestingModule", null);
}
} else {
errors.put("install.testing.invalidProductionUrl", new Object[] { wizardModel.productionUrl });
}
}
renderTemplate(page, referenceMap, httpResponse);
return;
} else if (TESTING_AUTHENTICATION_SETUP.equals(page)) {
if ("Back".equals(httpRequest.getParameter("back"))) {
renderTemplate(TESTING_PRODUCTION_URL_SETUP, referenceMap, httpResponse);
return;
}
//Authenticate to production server
wizardModel.productionUsername = httpRequest.getParameter("username");
wizardModel.productionPassword = httpRequest.getParameter("password");
checkForEmptyValue(wizardModel.productionUsername, errors, "install.testing.username.required");
checkForEmptyValue(wizardModel.productionPassword, errors, "install.testing.password.required");
if (errors.isEmpty())
page = DATABASE_SETUP;
renderTemplate(page, referenceMap, httpResponse);
return;
}
}
|
diff --git a/java/drda/org/apache/derby/impl/drda/Session.java b/java/drda/org/apache/derby/impl/drda/Session.java
index 8d1ea42df..e60fcb6bb 100644
--- a/java/drda/org/apache/derby/impl/drda/Session.java
+++ b/java/drda/org/apache/derby/impl/drda/Session.java
@@ -1,292 +1,293 @@
/*
Derby - Class org.apache.derby.impl.drda.Session
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.derby.impl.drda;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Enumeration;
import java.util.Hashtable;
import org.apache.derby.iapi.tools.i18n.LocalizedResource;
import java.sql.SQLException;
/**
Session stores information about the current session
It is used so that a DRDAConnThread can work on any session.
*/
class Session
{
// session states
protected static final int INIT = 1; // before exchange of server attributes
protected static final int ATTEXC = 2; // after first exchange of server attributes
protected static final int SECACC = 3; // after ACCSEC (Security Manager Accessed)
protected static final int CHKSEC = 4; // after SECCHK (Checked Security)
protected static final int CLOSED = 5; // session has ended
// session types
protected static final int DRDA_SESSION = 1;
protected static final int CMD_SESSION = 2;
// trace name prefix and suffix
private static final String TRACENAME_PREFIX = "Server";
private static final String TRACENAME_SUFFIX = ".trace";
// session information
protected Socket clientSocket; // session socket
protected int connNum; // connection number
protected InputStream sessionInput; // session input stream
protected OutputStream sessionOutput; // session output stream
protected String traceFileName; // trace file name for session
protected boolean traceOn; // whether trace is currently on for the session
protected int state; // the current state of the session
protected int sessionType; // type of session - DRDA or NetworkServerControl command
protected String drdaID; // DRDA ID of the session
protected DssTrace dssTrace; // trace object associated with the session
protected AppRequester appRequester; // Application requester for this session
protected Database database; // current database
protected int qryinsid; // unique identifier for each query
protected LocalizedResource langUtil; // localization information for command session
// client
private Hashtable dbtable; // Table of databases accessed in this session
private NetworkServerControlImpl nsctrl; // NetworkServerControlImpl needed for logging
// message if tracing fails.
// constructor
/**
* Session constructor
*
* @param connNum connection number
* @param clientSocket communications socket for this session
* @param traceDirectory location for trace files
* @param traceOn whether to start tracing this connection
*
* @exception throws IOException
*/
Session (NetworkServerControlImpl nsctrl, int connNum, Socket clientSocket, String traceDirectory,
boolean traceOn) throws Exception
{
- this.nsctrl = nsctrl;
+ this.nsctrl = nsctrl;
this.connNum = connNum;
this.clientSocket = clientSocket;
this.traceOn = traceOn;
if (traceOn)
dssTrace = new DssTrace();
dbtable = new Hashtable();
initialize(traceDirectory);
}
/**
* Close session - close connection sockets and set state to closed
*
*/
protected void close() throws SQLException
{
try {
sessionInput.close();
sessionOutput.close();
clientSocket.close();
if (dbtable != null)
for (Enumeration e = dbtable.elements() ; e.hasMoreElements() ;)
{
((Database) e.nextElement()).close();
}
}catch (IOException e) {} // ignore IOException when we are shutting down
finally {
state = CLOSED;
dbtable = null;
database = null;
}
}
/**
* initialize a server trace for the DRDA protocol
*
* @param traceDirectory - directory for trace file
- * @param throwException - true if we should throw an exception if turning on tracing fails.
- * We do this for NetworkServerControl API commands.
+ * @param throwException - true if we should throw an exception if
+ * turning on tracing fails. We do this
+ * for NetworkServerControl API commands.
* @throws IOException
*/
protected void initTrace(String traceDirectory, boolean throwException) throws Exception
{
if (traceDirectory != null)
traceFileName = traceDirectory + "/" + TRACENAME_PREFIX+
connNum+ TRACENAME_SUFFIX;
else
traceFileName = TRACENAME_PREFIX +connNum+ TRACENAME_SUFFIX;
if (dssTrace == null)
dssTrace = new DssTrace();
- try {
- dssTrace.startComBufferTrace (traceFileName);
- traceOn = true;
- } catch (Exception e)
- {
- if (throwException)
- throw e;
- // If there is an error starting tracing for the session,
- // log to the console and derby.log and do not turn tracing on.
- // let connection continue.
- nsctrl.consoleExceptionPrintTrace(e);
- }
+ try {
+ dssTrace.startComBufferTrace(traceFileName);
+ traceOn = true;
+ } catch (Exception e) {
+ if (throwException) {
+ throw e;
+ }
+ // If there is an error starting tracing for the session,
+ // log to the console and derby.log and do not turn tracing on.
+ // let connection continue.
+ nsctrl.consoleExceptionPrintTrace(e);
+ }
}
/**
* Set tracing on
*
* @param traceDirectory directory for trace files
* @throws Exception
*/
protected void setTraceOn(String traceDirectory, boolean throwException) throws Exception
{
if (traceOn)
return;
initTrace(traceDirectory, throwException);
}
/**
* Get whether tracing is on
*
* @return true if tracing is on false otherwise
*/
protected boolean isTraceOn()
{
if (traceOn)
return true;
else
return false;
}
/**
* Get connection number
*
* @return connection number
*/
protected int getConnNum()
{
return connNum;
}
/**
* Set tracing off
*
*/
protected void setTraceOff()
{
if (! traceOn)
return;
traceOn = false;
if (traceFileName != null)
dssTrace.stopComBufferTrace();
}
/**
* Add database to session table
*/
protected void addDatabase(Database d)
{
dbtable.put(d.dbName, d);
}
/**
* Get database
*/
protected Database getDatabase(String dbName)
{
return (Database)dbtable.get(dbName);
}
/**
* Get requried security checkpoint.
* Used to verify EXCSAT/ACCSEC/SECCHK order.
*
* @return next required Security checkpoint or -1 if
* neither ACCSEC or SECCHK are required at this time.
*
*/
protected int getRequiredSecurityCodepoint()
{
switch (state)
{
case ATTEXC:
// On initial exchange of attributes we require ACCSEC
// to access security manager
return CodePoint.ACCSEC;
case SECACC:
// After security manager has been accessed successfully we
// require SECCHK to check security
return CodePoint.SECCHK;
default:
return -1;
}
}
/**
* Check if a security codepoint is required
*
* @return true if ACCSEC or SECCHK are required at this time.
*/
protected boolean requiresSecurityCodepoint()
{
return (getRequiredSecurityCodepoint() != -1);
}
/**
* Set Session state
*
*/
protected void setState(int s)
{
state = s;
}
/**
* Get session into initial state
*
* @param traceDirectory - directory for trace files
*/
private void initialize(String traceDirectory)
throws Exception
{
sessionInput = clientSocket.getInputStream();
sessionOutput = clientSocket.getOutputStream();
if (traceOn)
initTrace(traceDirectory,false);
state = INIT;
}
protected String buildRuntimeInfo(String indent, LocalizedResource localLangUtil)
{
String s = "";
s += indent + localLangUtil.getTextMessage("DRDA_RuntimeInfoSessionNumber.I")
+ connNum + "\n";
if (database == null)
return s;
s += database.buildRuntimeInfo(indent,localLangUtil);
s += "\n";
return s;
}
}
| false | false | null | null |
diff --git a/SimpleSim/RobotThread.java b/SimpleSim/RobotThread.java
index 75ea30e..5d205d5 100644
--- a/SimpleSim/RobotThread.java
+++ b/SimpleSim/RobotThread.java
@@ -1,110 +1,110 @@
/**
* File: RobotThread.java
* @author: Tucker Trainor <[email protected]>
*
* Based on original code "EchoThread.java" by Adam J. Lee ([email protected])
*
* A thread that accepts a series of transactions from the Robot and sends them
* to a CloudServer
*/
import java.lang.Thread;
import java.net.Socket;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ConnectException;
import java.util.Date;
import java.util.ArrayList;
public class RobotThread extends Thread {
private final int transNumber;
private final String transactions;
private final String server;
private final int port;
private ArrayList<Integer> commitStack = new ArrayList<Integer>();
/**
* Constructor that sets up transaction communication
*
* @param _transNumber - the number of this transaction set
* @param _transactions - A string representing the queries to be run
* @param _server - The server name where the primary Transaction Manager
* is located
* @param _port - The port number of the server
*/
public RobotThread(int _transNumber, String _transactions, String _server, int _port) {
transNumber = _transNumber;
transactions = _transactions;
server = _server;
port = _port;
}
/**
* run() is basically the main method of a thread. This thread
* simply reads Message objects off of the socket.
*/
public void run() {
try {
// Divide transaction into groups to process in chunks (i.e., all
// contiguous READs or WRITEs)
String queryGroups[] = transactions.split(";");
int groupIndex = 0;
// Loop to send query qroups
while (groupIndex < queryGroups.length) {
// Connect to the specified server
final Socket sock = new Socket(server, port);
// System.out.println("Connected to " + server +
// " on port " + port);
// Set up I/O streams with the server
final ObjectOutputStream output = new ObjectOutputStream(sock.getOutputStream());
final ObjectInputStream input = new ObjectInputStream(sock.getInputStream());
Message msg = null, resp = null;
// Read and send message
msg = new Message(queryGroups[groupIndex]);
output.writeObject(msg);
// Get ACK and print
resp = (Message)input.readObject();
if (resp.theMessage.equals("ACK")) {
// System.out.println("RobotThread: query group processed");
}
- else if (resp.theMessage.substring(0,3) == "ACS") { // add to commitStack
+ else if (resp.theMessage.substring(0,3).equals("ACS")) { // add to commitStack
// parse server number from message
String temp[] = resp.theMessage.split(" ");
int commitOnServer = Integer.parseInt(temp[1]);
if (!commitStack.contains(commitOnServer)) { // add if new #
commitStack.add(commitOnServer);
System.out.println("RobotThread: transaction " + transNumber + " added server " + commitOnServer + " to commit stack");
}
}
else if (resp.theMessage.equals("FIN")) {
TransactionLog.entry.get(transNumber).setEndTime(new Date().getTime());
ThreadCounter.threadComplete(); // remove thread from active count
System.out.println("RobotThread: transaction " + transNumber + " complete");
}
else { // Something went wrong
System.out.println("RobotThread: query handling error");
// break; // ?
}
// Close connection to server
sock.close();
groupIndex++;
}
}
catch (ConnectException ce) {
System.err.println(ce.getMessage() +
": Check server address and port number.");
ce.printStackTrace(System.err);
}
catch (Exception e) {
System.err.println("Error: " + e.getMessage());
e.printStackTrace(System.err);
}
}
}
\ No newline at end of file
| true | false | null | null |
diff --git a/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/integrationtests/AbstractNexusIntegrationTest.java b/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/integrationtests/AbstractNexusIntegrationTest.java
index a733694a4..b75128b61 100644
--- a/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/integrationtests/AbstractNexusIntegrationTest.java
+++ b/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/integrationtests/AbstractNexusIntegrationTest.java
@@ -1,628 +1,634 @@
package org.sonatype.nexus.integrationtests;
import static org.junit.Assert.fail;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileFilter;
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.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
+import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import junit.framework.Assert;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.apache.maven.wagon.ConnectionException;
import org.apache.maven.wagon.ResourceDoesNotExistException;
import org.apache.maven.wagon.TransferFailedException;
import org.apache.maven.wagon.authentication.AuthenticationException;
import org.apache.maven.wagon.authorization.AuthorizationException;
import org.codehaus.plexus.ContainerConfiguration;
import org.codehaus.plexus.DefaultContainerConfiguration;
import org.codehaus.plexus.DefaultPlexusContainer;
import org.codehaus.plexus.PlexusContainer;
import org.codehaus.plexus.PlexusContainerException;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.restlet.Client;
import org.restlet.data.MediaType;
import org.restlet.data.Metadata;
import org.restlet.data.Method;
import org.restlet.data.Protocol;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.sonatype.appbooter.ForkedAppBooter;
import org.sonatype.appbooter.ctl.AppBooterServiceException;
import org.sonatype.nexus.artifact.Gav;
import org.sonatype.nexus.rest.model.StatusResourceResponse;
import org.sonatype.nexus.rest.xstream.XStreamInitializer;
import org.sonatype.nexus.test.utils.DeployUtils;
import org.xml.sax.XMLReader;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.XppDriver;
/**
- * TODO: add REST restart to make tests faster <BR/> curl --user admin:admin123 --request PUT
- * http://localhost:8081/nexus/service/local/status/command --data STOP <BR/> curl --user admin:admin123 --request PUT
- * http://localhost:8081/nexus/service/local/status/command --data START <BR/> curl --user admin:admin123 --request PUT
- * http://localhost:8081/nexus/service/local/status/command --data RESTART <BR/> <BR/> NOTE, this class is not really
- * abstract so I can work around a the <code>@BeforeClass</code>, <code>@AfterClass</code> issues
+ * NOTE, this class is not really abstract so I can work around a the <code>@BeforeClass</code>, <code>@AfterClass</code> issues, this should be refactored a little, but it might be ok, if we switch to TestNg
*/
public class AbstractNexusIntegrationTest
{
private PlexusContainer container;
private Map<String, Object> context;
private String basedir;
private static boolean NEEDS_INIT = false;
private static boolean NEEDS_HARD_STOP = false;
public static final String REPOSITORY_RELATIVE_URL = "content/repositories/";
public static final String GROUP_REPOSITORY_RELATIVE_URL = "content/groups/";
private String nexusBaseDir;
private String baseNexusUrl;
private String nexusTestRepoUrl;
private String nexusWorkDir;
private static final String STATUS_STOPPED = "STOPPED";
private static final String STATUS_STARTED = "STARTED";
public static final String RELATIVE_CONF_DIR = "runtime/apps/nexus/conf";
protected AbstractNexusIntegrationTest()
{
this( "nexus-test-harness-repo" );
}
protected AbstractNexusIntegrationTest( String testRepositoryId )
{
this.setupContainer();
// we also need to setup a couple fields, that need to be pulled out of a bundle
ResourceBundle rb = ResourceBundle.getBundle( "baseTest" );
this.nexusBaseDir = rb.getString( "nexus.base.dir" );
this.baseNexusUrl = rb.getString( "nexus.base.url" );
this.nexusWorkDir = rb.getString( "nexus.work.dir" );
this.nexusTestRepoUrl = baseNexusUrl + REPOSITORY_RELATIVE_URL + testRepositoryId + "/";
}
/**
* To me this seems like a bad hack around this problem. I don't have any other thoughts though. <BR/>If you see
* this and think: "Wow, why did he to that instead of XYZ, please let me know." <BR/> The issue is that we want to
* init the tests once (to start/stop the app) and the <code>@BeforeClass</code> is static, so we don't have access to the package name of the running tests. We are going to
* use the package name to find resources for additional setup. NOTE: With this setup running multiple
* Test at the same time is not possible.
* @throws Exception
*/
@Before
public void oncePerClassSetUp()
throws Exception
{
synchronized ( AbstractNexusIntegrationTest.class )
{
if ( NEEDS_INIT )
{
// clean common work dir
// this.cleanWorkDir();
// copy nexus config
this.copyNexusConfig();
// start nexus
this.startNexus();
// deploy artifacts
this.deployArtifacts();
NEEDS_INIT = false;
}
}
}
private void cleanWorkDir()
throws IOException
{
File workDir = new File( this.nexusWorkDir );
// to make sure I don't delete all my MP3's and pictures, or totally screw anyone.
// check for 'target' and not allow any '..'
if ( workDir.getAbsolutePath().lastIndexOf( "target" ) != -1
&& workDir.getAbsolutePath().lastIndexOf( ".." ) == -1 )
{
// delete work dir
FileUtils.deleteDirectory( workDir );
}
}
private void deployArtifacts()
throws IOException, XmlPullParserException, ConnectionException, AuthenticationException,
TransferFailedException, ResourceDoesNotExistException, AuthorizationException, ComponentLookupException
{
// test the test directory
File projectsDir = this.getTestResourceAsFile( "projects" );
System.out.println( "projectsDir: " + projectsDir );
// if null there is nothing to deploy...
if ( projectsDir != null )
{
// we have the parent dir, for each child (one level) we need to grab the pom.xml out of it and parse it,
// and then deploy the artifact, sounds like fun, right!
File[] projectFolders = projectsDir.listFiles( new FileFilter()
{
public boolean accept( File pathname )
{
return ( !pathname.getName().endsWith( ".svn" ) && pathname.isDirectory() && new File( pathname,
"pom.xml" ).exists() );
}
} );
for ( int ii = 0; ii < projectFolders.length; ii++ )
{
File project = projectFolders[ii];
// we already check if the pom.xml was in here.
File pom = new File( project, "pom.xml" );
MavenXpp3Reader reader = new MavenXpp3Reader();
FileInputStream fis = new FileInputStream( pom );
Model model = reader.read( new FileInputStream( pom ) );
fis.close();
// a helpful note so you don't need to dig into the code to much.
if ( model.getDistributionManagement() == null
|| model.getDistributionManagement().getRepository() == null )
{
Assert.fail( "The test artifact is either missing or has an invalid Distribution Management section." );
}
String deployUrl = model.getDistributionManagement().getRepository().getUrl();
// FIXME, this needs to be fluffed up a little, should add the classifier, etc.
String artifactFileName = model.getArtifactId() + "." + model.getPackaging();
File artifactFile = new File( project, artifactFileName );
System.out.println( "wow, this is working: " + artifactFile );
// deploy pom
DeployUtils.deployWithWagon( this.container, "http", deployUrl, pom,
this.getRelitiveArtifactPath( model.getGroupId(), model.getArtifactId(),
model.getVersion(), "pom" ) );
// deploy artifact
DeployUtils.deployWithWagon( this.container, "http", deployUrl, artifactFile,
this.getRelitiveArtifactPath( model.getGroupId(), model.getArtifactId(),
model.getVersion(), model.getPackaging() ) );
}
}
}
@After
public void afterTest()
throws Exception
{
}
private void startNexus()
throws Exception
{
// if nexus is running but stopped we only want to do a softstart
// and we don't want to start if it is already running.
try
{
if ( this.isNexusRunning() )
{
// we have nothing to do if its running
return;
}
else
{
this.doSoftStart();
}
}
catch ( IOException e )
{
// nexus is not running....
// that is ok, most likely someone ran a single test from eclipse
// we need a hard start
NEEDS_HARD_STOP = true;
-
+
System.out.println( "***************************" );
System.out.println( "*\n*" );
System.out.println( "* DOING A HARD START OF NEXUS." );
System.out.println( "* If your not running a single test manually, then something bad happened" );
System.out.println( "*\n*" );
System.out.println( "***************************" );
ForkedAppBooter appBooter =
(ForkedAppBooter) TestContainer.getInstance().lookup( ForkedAppBooter.ROLE, "TestForkedAppBooter" );
appBooter.start();
- }
+ }
}
private void stopNexus()
throws Exception
{
// craptastic state machine
if ( !NEEDS_HARD_STOP )
{
// normal flow is to soft stop
this.doSoftStop();
}
else
{
// must reset
NEEDS_HARD_STOP = false;
ForkedAppBooter appBooter =
(ForkedAppBooter) TestContainer.getInstance().lookup( ForkedAppBooter.ROLE, "TestForkedAppBooter" );
try
{
appBooter.stop();
}
catch ( AppBooterServiceException e )
{
Assert.fail( "The Test failed to stop a forked JVM, so, it was either (most likely) not running or an orphaned process that you will need to kill." );
}
}
}
private void copyNexusConfig()
throws IOException
{
// the test can override the test config.
File testNexusConfig = this.getTestResourceAsFile( "test-config/nexus.xml" );
// if the tests doesn't have a different config then use the default.
// we need to replace every time to make sure no one changes it.
if ( testNexusConfig == null || !testNexusConfig.exists() )
{
testNexusConfig = this.getResource( "default-config/nexus.xml" );
}
else
{
System.out.println( "This test is using its own nexus.xml: " + testNexusConfig );
}
System.out.println( "copying nexus.xml to: "
+ new File( this.nexusBaseDir + "/" + RELATIVE_CONF_DIR, "nexus.xml" ) );
FileUtils.copyFile( testNexusConfig, new File( this.nexusBaseDir + "/" + RELATIVE_CONF_DIR, "nexus.xml" ) );
}
/**
* Returns a File if it exists, null otherwise. Files returned by this method must be located in the
* "src/test/resourcs/nexusXXX/" folder.
*
* @param relativePath path relative to the nexusXXX directory.
* @return A file specified by the relativePath. or null if it does not exist.
*/
protected File getTestResourceAsFile( String relativePath )
{
String resource = this.getTestId() + "/" + relativePath;
return this.getResource( resource );
}
protected String getTestId()
{
String packageName = this.getClass().getPackage().getName();
return packageName.substring( packageName.lastIndexOf( '.' ) + 1, packageName.length() );
}
/**
* Returns a File if it exists, null otherwise. Files returned by this method must be located in the
* "src/test/resourcs/nexusXXX/files/" folder.
*
* @param relativePath path relative to the files directory.
* @return A file specified by the relativePath. or null if it does not exist.
*/
protected File getTestFile( String relativePath )
{
return this.getTestResourceAsFile( "files/" + relativePath );
}
protected File getResource( String resource )
{
System.out.println( "Looking for resource: " + resource );
URL classURL = Thread.currentThread().getContextClassLoader().getResource( resource );
System.out.println( "found: " + classURL );
- return classURL == null ? null : new File( classURL.getFile() );
+
+ try
+ {
+ return classURL == null ? null : new File( URLDecoder.decode( classURL.getFile(), "UTF-8" ) );
+ }
+ catch ( UnsupportedEncodingException e )
+ {
+ throw new RuntimeException( "This test assumes the use of UTF-8 encoding: " + e.getMessage(), e );
+ }
}
/**
* See oncePerClassSetUp.
*/
@BeforeClass
public static void staticOncePerClassSetUp()
{
// hacky state machine
NEEDS_INIT = true;
}
@AfterClass
public static void oncePerClassTearDown()
throws Exception
{
// stop nexus
new AbstractNexusIntegrationTest().stopNexus();
}
private void setupContainer()
{
// ----------------------------------------------------------------------------
// Context Setup
// ----------------------------------------------------------------------------
context = new HashMap<String, Object>();
context.put( "basedir", basedir );
boolean hasPlexusHome = context.containsKey( "plexus.home" );
if ( !hasPlexusHome )
{
File f = new File( basedir, "target/plexus-home" );
if ( !f.isDirectory() )
{
f.mkdir();
}
context.put( "plexus.home", f.getAbsolutePath() );
}
// ----------------------------------------------------------------------------
// Configuration
// ----------------------------------------------------------------------------
ContainerConfiguration containerConfiguration =
new DefaultContainerConfiguration().setName( "test" ).setContext( context ).setContainerConfiguration(
getClass().getName().replace(
'.',
'/' )
+ ".xml" );
try
{
container = new DefaultPlexusContainer( containerConfiguration );
}
catch ( PlexusContainerException e )
{
e.printStackTrace();
fail( "Failed to create plexus container." );
}
}
protected Object lookup( String componentKey )
throws Exception
{
return container.lookup( componentKey );
}
protected Object lookup( String role, String id )
throws Exception
{
return container.lookup( role, id );
}
protected String getRelitiveArtifactPath( Gav gav )
throws FileNotFoundException
{
return this.getRelitiveArtifactPath( gav.getGroupId(), gav.getArtifactId(), gav.getVersion(),
gav.getExtension() );
}
protected String getRelitiveArtifactPath( String groupId, String artifactId, String version, String extension )
throws FileNotFoundException
{
return groupId.replace( '.', '/' ) + "/" + artifactId + "/" + version + "/" + artifactId + "-" + version + "."
+ extension;
}
protected File downloadArtifact( Gav gav, String targetDirectory )
throws IOException
{
return this.downloadArtifact( gav.getGroupId(), gav.getArtifactId(), gav.getVersion(), gav.getExtension(),
targetDirectory );
}
protected File downloadArtifact( String groupId, String artifact, String version, String type,
String targetDirectory )
throws IOException
{
return this.downloadArtifact( this.nexusTestRepoUrl, groupId, artifact, version, type, targetDirectory );
}
protected File downloadArtifactFromRepository( String repoId, Gav gav, String targetDirectory )
throws IOException
{
return this.downloadArtifact( this.baseNexusUrl + REPOSITORY_RELATIVE_URL + repoId + "/", gav.getGroupId(),
gav.getArtifactId(), gav.getVersion(), gav.getExtension(), targetDirectory );
}
protected File downloadArtifactFromGroup( String groupId, Gav gav, String targetDirectory )
throws IOException
{
return this.downloadArtifact( this.baseNexusUrl + GROUP_REPOSITORY_RELATIVE_URL + groupId + "/",
gav.getGroupId(), gav.getArtifactId(), gav.getVersion(), gav.getExtension(),
targetDirectory );
}
protected File downloadArtifact( String baseUrl, String groupId, String artifact, String version, String type,
String targetDirectory )
throws IOException
{
URL url =
new URL( baseUrl + groupId.replace( '.', '/' ) + "/" + artifact + "/" + version + "/" + artifact + "-"
+ version + "." + type );
return this.downloadFile( url, targetDirectory + "/" + artifact + "-" + version + "." + type );
}
protected File downloadFile( URL url, String targetFile )
throws IOException
{
OutputStream out = null;
URLConnection conn = null;
InputStream in = null;
File downloadedFile = new File( targetFile );
// if this is null then someone was getting really creative with the tests, but hey, we will let them...
if ( downloadedFile.getParentFile() != null )
{
downloadedFile.getParentFile().mkdirs();
}
try
{
System.out.println( "Downloading file: " + url );
out = new BufferedOutputStream( new FileOutputStream( downloadedFile ) );
conn = url.openConnection();
in = conn.getInputStream();
byte[] buffer = new byte[1024];
int numRead;
long numWritten = 0;
while ( ( numRead = in.read( buffer ) ) != -1 )
{
out.write( buffer, 0, numRead );
numWritten += numRead;
}
}
finally
{
try
{
if ( out != null )
{
out.close();
}
if ( in != null )
{
in.close();
}
}
catch ( IOException e )
{
}
}
return downloadedFile;
}
private void sendNexusStatusCommand( String command )
{
String serviceURI = this.getBaseNexusUrl() + "service/local/status/command";
Request request = new Request();
request.setResourceRef( serviceURI );
request.setMethod( Method.PUT );
request.setEntity( command, MediaType.TEXT_ALL );
Client client = new Client( Protocol.HTTP );
Response response = client.handle( request );
if ( !response.getStatus().isSuccess() )
{
Assert.fail( "Could not " + command + " Nexus: (" + response.getStatus() + ")" );
}
}
protected void doSoftStop()
{
this.sendNexusStatusCommand( "STOP" );
}
protected void doSoftStart()
{
this.sendNexusStatusCommand( "START" );
}
protected void doSoftRestart()
{
this.sendNexusStatusCommand( "RESTART" );
}
protected boolean isNexusRunning()
throws IOException
{
return ( STATUS_STARTED.equals( this.getNexusStatus().getData().getState() ) );
}
protected StatusResourceResponse getNexusStatus()
throws IOException
{
XStream xstream = new XStream();
StatusResourceResponse status = null;
status =
(StatusResourceResponse) xstream.fromXML( new URL( this.getBaseNexusUrl() + "service/local/status" ).openStream() );
return status;
}
public String getBaseNexusUrl()
{
return baseNexusUrl;
}
public void setBaseNexusUrl( String baseNexusUrl )
{
this.baseNexusUrl = baseNexusUrl;
}
public String getNexusTestRepoUrl()
{
return nexusTestRepoUrl;
}
public void setNexusTestRepoUrl( String nexusTestRepoUrl )
{
this.nexusTestRepoUrl = nexusTestRepoUrl;
}
public PlexusContainer getContainer()
{
return this.container;
}
}
| false | false | null | null |
diff --git a/server/src/com/xhills/golf_party/controller/api/v1/me/GetController.java b/server/src/com/xhills/golf_party/controller/api/v1/me/GetController.java
index 2b999df..21f95eb 100644
--- a/server/src/com/xhills/golf_party/controller/api/v1/me/GetController.java
+++ b/server/src/com/xhills/golf_party/controller/api/v1/me/GetController.java
@@ -1,61 +1,62 @@
package com.xhills.golf_party.controller.api.v1.me;
import java.util.List;
import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import com.google.appengine.repackaged.org.json.JSONArray;
import com.xhills.golf_party.common.Const;
import com.xhills.golf_party.common.Me;
import com.xhills.golf_party.model.common.User;
import com.xhills.golf_party.model.me.Group;
import com.xhills.golf_party.service.me.GroupService;
public class GetController extends Controller {
@Override
public Navigation run() throws Exception {
response.setContentType(Const.charEncoding);
String service = asString("service");
if (service != null) {
Me me = (Me) sessionScope("me");
if (me != null) {
if (service.equals("me")) {
User user = me.getUser();
user.toJSONObject().write(response.getWriter());
return null;
} else if (service.equals("my_friends")) {
JSONArray friends = new JSONArray();
for (User friend : me.getFriends()) {
friends.put(friend.toJSONObject());
}
friends.write(response.getWriter());
return null;
} else if (service.equals("my_groups")) {
+ // groups
GroupService gs = new GroupService();
List<Group> groupList =
gs.getMyGroups(me.getUser().getUserid());
JSONArray groups = new JSONArray();
for (Group group : groupList) {
groups.put(group.toJSONObject());
}
groups.write(response.getWriter());
}
}
}
return null;
}
}
diff --git a/server/src/com/xhills/golf_party/controller/api/v1/me/UpdateController.java b/server/src/com/xhills/golf_party/controller/api/v1/me/UpdateController.java
index 6356e7a..ed76dd0 100644
--- a/server/src/com/xhills/golf_party/controller/api/v1/me/UpdateController.java
+++ b/server/src/com/xhills/golf_party/controller/api/v1/me/UpdateController.java
@@ -1,90 +1,90 @@
package com.xhills.golf_party.controller.api.v1.me;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;
import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import com.google.appengine.repackaged.org.json.JSONObject;
import com.xhills.golf_party.common.Const;
import com.xhills.golf_party.common.Me;
import com.xhills.golf_party.common.utils.JSONUtil;
import com.xhills.golf_party.model.me.Group;
import com.xhills.golf_party.service.me.GroupService;
public class UpdateController extends Controller {
private Logger log = Logger.getLogger(getClass().getName());
@Override
public Navigation run() throws Exception {
response.setContentType(Const.charEncoding);
if (!isGet()) {
Me me = (Me) sessionScope("me");
if (me != null) {
if (isPost()) {
// create
JSONObject obj =
JSONUtil.inputStreamToJSONObject(request.getInputStream());
log.info("Create new group. " + obj.getString("name"));
Group group = new Group();
GroupService gs = new GroupService();
group.setOwnerid(me.getUser().getUserid());
group.setName(obj.getString("name"));
group.setUserids(new HashSet<String>());
for (int i = 0; i < obj.getJSONArray("userids").length(); i++) {
String userid = obj.getJSONArray("userids").getString(i);
group.getUserids().add(userid);
}
group = gs.createGroup(group);
group.toJSONObject().write(response.getWriter());
return null;
} else if (isPut()) {
// update
JSONObject obj =
JSONUtil.inputStreamToJSONObject(request.getInputStream());
log.info("Update group. " + obj.getString("name"));
GroupService gs = new GroupService();
Set<String> userids = new HashSet<String>();
for (int i = 0; i < obj.getJSONArray("userids").length(); i++) {
String userid = obj.getJSONArray("userids").getString(i);
userids.add(userid);
}
Group group =
gs.updateGroup(
obj.getLong("id"),
- obj.getString("ownerid"),
+ me.getUser().getUserid(),
obj.getString("name"),
userids);
group.toJSONObject().write(response.getWriter());
return null;
} else if (isDelete()) {
// delete
JSONObject obj =
JSONUtil.inputStreamToJSONObject(request.getInputStream());
long id = obj.getLong("id");
log.info("Delete group. " + id);
GroupService gs = new GroupService();
gs.deleteGroup(id);
response.getWriter().write("null");
return null;
}
}
}
return null;
}
}
| false | false | null | null |
diff --git a/src/main/java/com/google/errorprone/matchers/DeadExceptionMatcher.java b/src/main/java/com/google/errorprone/matchers/DeadExceptionMatcher.java
index d3b9d1b..bdeefb9 100644
--- a/src/main/java/com/google/errorprone/matchers/DeadExceptionMatcher.java
+++ b/src/main/java/com/google/errorprone/matchers/DeadExceptionMatcher.java
@@ -1,44 +1,45 @@
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.matchers;
import com.google.errorprone.SuggestedFix;
import com.google.errorprone.VisitorState;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.Tree.Kind;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import static com.google.errorprone.matchers.Matchers.*;
/**
* @author [email protected] (Alex Eagle)
*/
public class DeadExceptionMatcher extends ErrorProducingMatcher<NewClassTree> {
@Override
public AstError matchWithError(NewClassTree newClassTree, VisitorState state) {
if (allOf(
not(parentNodeIs(Kind.THROW)), // not "throw new Exception..."
not(parentNodeIs(Kind.VARIABLE)), // not "Exception e = new Exception..."
- Matchers.isSubtypeOf(state.symtab.exceptionType)).matches(newClassTree, state)) {
+ not(parentNodeIs(Kind.ASSIGNMENT)), // not "e = new Exception..."
+ isSubtypeOf(state.symtab.exceptionType)).matches(newClassTree, state)) {
DiagnosticPosition pos = ((JCTree) newClassTree).pos();
return new AstError(newClassTree, "Exception created but not thrown, and reference is lost",
new SuggestedFix(pos.getStartPosition(), pos.getStartPosition(), "throw "));
}
return null;
}
}
diff --git a/src/test/resources/NegativeCase1.java b/src/test/resources/NegativeCase1.java
index 288abed..9eb79f5 100644
--- a/src/test/resources/NegativeCase1.java
+++ b/src/test/resources/NegativeCase1.java
@@ -1,26 +1,23 @@
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-import java.lang.Exception;
-import java.lang.IllegalArgumentException;
-import java.lang.RuntimeException;
-
public class NegativeCase1 {
public void noError() {
Exception e = new RuntimeException("stored");
+ e = new UnsupportedOperationException("also stored");
throw new IllegalArgumentException("thrown");
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/src/edu/isi/pegasus/planner/selector/replica/Local.java b/src/edu/isi/pegasus/planner/selector/replica/Local.java
index 51629e019..db6fb4d2b 100644
--- a/src/edu/isi/pegasus/planner/selector/replica/Local.java
+++ b/src/edu/isi/pegasus/planner/selector/replica/Local.java
@@ -1,235 +1,243 @@
/**
* Copyright 2007-2008 University Of Southern California
*
* 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 edu.isi.pegasus.planner.selector.replica;
import edu.isi.pegasus.common.logging.LogManagerFactory;
import edu.isi.pegasus.planner.classes.ReplicaLocation;
import edu.isi.pegasus.planner.selector.ReplicaSelector;
import edu.isi.pegasus.common.logging.LogManager;
import edu.isi.pegasus.planner.common.PegasusProperties;
import edu.isi.pegasus.planner.common.PegRandom;
import edu.isi.pegasus.planner.catalog.replica.ReplicaCatalogEntry;
import java.util.ArrayList;
import java.util.Iterator;
/**
* This replica selector only prefers replicas from the local host and that
* start with a file: URL scheme. It is useful, when you want to stagin
* files to a remote site from your submit host using the Condor file transfer
* mechanism.
*
* <p>
* In order to use the replica selector implemented by this class,
* <pre>
* - the property pegasus.selector.replica must be set to value Local
* </pre>
*
*
* @see org.griphyn.cPlanner.transfer.implementation.Condor
*
* @author Karan Vahi
* @version $Revision$
*/
public class Local implements ReplicaSelector {
/**
* A short description of the replica selector.
*/
private static final String mDescription = "Local from submit host";
/**
* Sanity Check Error Message.
*/
- public static final String SANITY_CHECK_ERROR_MESSAGE = "Local Replica Selector selects only local file URL's. Set transfers to run on submit host";
+ public static final String SANITY_CHECK_ERROR_MESSAGE_PREFIX = "Local Replica Selector selects only local file URL's. Set transfers to run on submit host.";
/**
* The scheme name for file url.
*/
protected static final String FILE_URL_SCHEME = "file:";
/**
* The handle to the logging object that is used to log the various debug
* messages.
*/
protected LogManager mLogger;
/**
* The properties object containing the properties passed to the planner.
*/
protected PegasusProperties mProps;
/**
* The overloaded constructor, that is called by load method.
*
* @param properties the <code>PegasusProperties</code> object containing all
* the properties required by Pegasus.
*
*
*/
public Local( PegasusProperties properties ){
mProps = properties;
mLogger = LogManagerFactory.loadSingletonInstance( properties );
}
/**
* Selects a random replica from all the replica's that have their
* site handle set to local and the pfn's start with a file url scheme.
*
* @param rl the <code>ReplicaLocation</code> object containing all
* the pfn's associated with that LFN.
* @param preferredSite the preffered site for picking up the replicas.
* @param allowLocalFileURLs indicates whether Replica Selector can select a replica
* on the local site / submit host.
*
* @return <code>ReplicaCatalogEntry</code> corresponding to the location selected.
*
* @see org.griphyn.cPlanner.classes.ReplicaLocation
*/
public ReplicaCatalogEntry selectReplica( ReplicaLocation rl,
String preferredSite,
boolean allowLocalFileURLs ){
//sanity check
if( !allowLocalFileURLs && !preferredSite.equals( ReplicaSelector.LOCAL_SITE_HANDLE )){
- throw new RuntimeException( SANITY_CHECK_ERROR_MESSAGE );
+ StringBuffer message = new StringBuffer();
+ message.append( SANITY_CHECK_ERROR_MESSAGE_PREFIX ).
+ append( "For LFN " ).append( rl.getLFN() ). append( " (preferred site , allow local urls) is set to ").
+ append( "(").append( preferredSite ).append( "," ).append( allowLocalFileURLs ).append( ")" );
+ throw new RuntimeException( message.toString() );
}
ReplicaCatalogEntry rce;
ArrayList prefPFNs = new ArrayList();
int locSelected;
String site = null;
// mLogger.log("Selecting a pfn for lfn " + lfn + "\n amongst" + locations ,
// LogManager.DEBUG_MESSAGE_LEVEL);
for ( Iterator it = rl.pfnIterator(); it.hasNext(); ) {
rce = ( ReplicaCatalogEntry ) it.next();
site = rce.getResourceHandle();
if( site == null ){
//skip to next replica
continue;
}
//check if has pool attribute as local, and at same time
//start with a file url scheme
if( site.equals( "local" ) && rce.getPFN().startsWith( FILE_URL_SCHEME ) ){
prefPFNs.add( rce );
}
}
if ( prefPFNs.isEmpty() ) {
//select a random location from
//all the matching locations
//in all likelihood all the urls were file urls and none
//were associated with the preference pool.
throw new RuntimeException( "Unable to select any location on local site from " +
"the list passed for lfn " + rl.getLFN() );
} else {
//select a random location
//amongst the locations
//on the preference pool
int length = prefPFNs.size();
//System.out.println("No of locations found at pool " + prefPool + " are " + length);
locSelected = PegRandom.getInteger( length - 1 );
rce = ( ReplicaCatalogEntry ) prefPFNs.get( locSelected );
}
return rce;
}
/**
* This chooses a location amongst all the locations returned by the
* Replica Mechanism. If a location is found with re/pool attribute same
* as the preference pool, it is taken. This returns all the locations which
* match to the preference pool. This function is called to determine if a
* file does exist on the output pool or not beforehand. We need all the
* location to ensure that we are able to make a match if it so exists.
* Else a random location is selected and returned
*
* @param rl the <code>ReplicaLocation</code> object containing all
* the pfn's associated with that LFN.
* @param preferredSite the preffered site for picking up the replicas.
* @param allowLocalFileURLs indicates whether Replica Selector can select a replica
* on the local site / submit host.
*
* @return <code>ReplicaLocation</code> corresponding to the replicas selected.
*
* @see org.griphyn.cPlanner.classes.ReplicaLocation
*/
public ReplicaLocation selectReplicas( ReplicaLocation rl,
String preferredSite,
boolean allowLocalFileURLs ){
//sanity check
if( !allowLocalFileURLs && !preferredSite.equals( ReplicaSelector.LOCAL_SITE_HANDLE )){
- throw new RuntimeException( SANITY_CHECK_ERROR_MESSAGE );
+ StringBuffer message = new StringBuffer();
+ message.append( SANITY_CHECK_ERROR_MESSAGE_PREFIX ).
+ append( "For LFN " ).append( rl.getLFN() ). append( " (preferred site , allow local urls) is set to ").
+ append( "(").append( preferredSite ).append( "," ).append( allowLocalFileURLs ).append( ")" );
+ throw new RuntimeException( message.toString() );
}
String lfn = rl.getLFN();
ReplicaLocation result = new ReplicaLocation();
result.setLFN( rl.getLFN() );
ReplicaCatalogEntry rce;
String site;
int noOfLocs = 0;
for ( Iterator it = rl.pfnIterator(); it.hasNext(); ) {
noOfLocs++;
rce = ( ReplicaCatalogEntry ) it.next();
site = rce.getResourceHandle();
if ( site != null && site.equals( preferredSite )) {
result.addPFN( rce );
}
else if ( site == null ){
mLogger.log(
" pool attribute not specified for the location objects" +
" in the Replica Catalog", LogManager.WARNING_MESSAGE_LEVEL);
}
}
if ( result.getPFNCount() == 0 ) {
//means we have to choose a random location between 0 and (noOfLocs -1)
int locSelected = PegRandom.getInteger( noOfLocs - 1 );
rce = ( ReplicaCatalogEntry ) rl.getPFN(locSelected );
result.addPFN( rce );
}
return result;
}
/**
* Returns a short description of the replica selector.
*
* @return string corresponding to the description.
*/
public String description(){
return mDescription;
}
}
| false | false | null | null |
diff --git a/src/main/java/net/oneandone/lavender/config/Net.java b/src/main/java/net/oneandone/lavender/config/Net.java
index 872c1fd..08bcda6 100644
--- a/src/main/java/net/oneandone/lavender/config/Net.java
+++ b/src/main/java/net/oneandone/lavender/config/Net.java
@@ -1,174 +1,174 @@
/**
* Copyright 1&1 Internet AG, https://github.com/1and1/
*
* 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.oneandone.lavender.config;
import net.oneandone.sushi.cli.ArgumentException;
import net.oneandone.sushi.fs.file.FileNode;
import java.util.HashMap;
import java.util.Map;
public class Net {
public static Net normal() {
Net net;
net = new Net();
net.add("eu", new Cluster()
.addCdn("cdnfe01.schlund.de")
.addCdn("cdnfe02.schlund.de")
.addCdn("cdnfe03.schlund.de")
- .addDocroot("home/wwwcdn/htdocs/fix", "home/wwwcdn/indexes",
+ .addDocroot("home/wwwcdn/htdocs/fix", "home/wwwcdn/indexes/fix",
new Alias("fix", "s1.uicdn.net", "s2.uicdn.net", "s3.uicdn.net", "s4.uicdn.net")));
net.add("us", new Cluster()
// see http://issue.tool.1and1.com/browse/ITOSHA-3624 and http://issue.tool.1and1.com/browse/ITOSHA-3667
.addCdn("wscdnfelxaa01.fe.server.lan")
.addCdn("wscdnfelxaa02.fe.server.lan")
.addCdn("wscdnfelxaa03.fe.server.lan")
- .addDocroot("home/wwwcdn/htdocs/fix", "home/wwwcdn/indexes",
+ .addDocroot("home/wwwcdn/htdocs/fix", "home/wwwcdn/indexes/fix",
new Alias("fix", "u1.uicdn.net", "u2.uicdn.net", "u3.uicdn.net", "u4.uicdn.net"),
new Alias("akamai", "au1.uicdn.net", "au2.uicdn.net", "au3.uicdn.net", "au4.uicdn.net")));
net.add("flash-eu", new Cluster()
// see http://issue.tool.1and1.com/browse/ITOSHA-3624 and http://issue.tool.1and1.com/browse/ITOSHA-3668
.addFlash("winflasheu1.schlund.de")
.addFlash("winflasheu2.schlund.de")
.addDocroot("", ".lavender",
new Alias("flash")));
net.add("flash-us", new Cluster()
.addFlash("winflashus1.lxa.perfora.net")
.addFlash("winflashus2.lxa.perfora.net")
.addDocroot("", ".lavender",
new Alias("flash")));
// this cluster is only accessible from within 1&1
net.add("internal", new Cluster()
.addStatint("cdnfe01.schlund.de")
.addStatint("cdnfe02.schlund.de")
.addStatint("cdnfe03.schlund.de")
/* the following is excludes to avoid garbage collection of the file inside:
.addDocroot("var/bazaarvoice", "indexes/bazaarvoice",
new Alias("bazaar")) */
.addDocroot("var/svn", "indexes/svn",
new Alias("svn")));
net.add("walter", new Cluster()
.addHost("walter.websales.united.domain", "mhm")
.addDocroot("Users/mhm/lavender/htdocs/fix", "Users/mhm/lavender/indexes/fix",
new Alias("fix", "fix.lavender.walter.websales.united.domain"))
.addDocroot("Users/mhm/lavender/htdocs/flash", "Users/mhm/lavender/indexes/flash",
new Alias("flash"))
.addDocroot("Users/mhm/lavender/htdocs/var/svn", "Users/mhm/lavender/indexes/svn",
new Alias("svn")));
// views
net.addView("eu",
"web", "eu",
"flash", "flash-eu");
net.addView("us",
"web", "us",
"flash", "flash-us");
net.addView("akamai-us",
"web", "us/akamai",
"flash", "flash-us");
net.addView("walter",
"web", "walter",
"flash-eu", "walter/flash",
"svn", "walter/svn");
net.addView("internal",
"svn", "internal/svn");
return net;
}
//--
public static Host local(FileNode basedir) {
return Host.local(basedir);
}
//--
public final Map<String, Cluster> clusters;
public final Map<String, View> views;
public Net() {
clusters = new HashMap<>();
views = new HashMap<>();
}
public void addView(String name, String ... args) {
View view;
String reference;
int idx;
Cluster cluster;
Docroot docroot;
Alias alias;
Object[] tmp;
if ((args.length & 0x01) == 1) {
throw new IllegalArgumentException();
}
view = new View();
for (int i = 0; i < args.length; i += 2) {
reference = args[i + 1];
idx = reference.indexOf('/');
if (idx == -1) {
cluster = cluster(reference);
docroot = cluster.docroots.get(0);
alias = docroot.aliases.get(0);
} else {
cluster = cluster(reference.substring(0, idx));
tmp = cluster.alias(reference.substring(idx + 1));
docroot = (Docroot) tmp[0];
alias = (Alias) tmp[1];
}
view.add(args[i], cluster, docroot, alias);
}
add(name, view);
}
public void add(String name, Cluster cluster) {
if (clusters.put(name, cluster) != null) {
throw new IllegalArgumentException("duplicate cluster: " + name);
}
}
public void add(String name, View view) {
if (views.put(name, view) != null) {
throw new IllegalArgumentException("duplicate view: " + name);
}
}
public Cluster cluster(String name) {
Cluster result;
result = clusters.get(name);
if (result == null) {
throw new ArgumentException("unknown cluster: " + name);
}
return result;
}
public View view(String name) {
View result;
result = views.get(name);
if (result == null) {
throw new ArgumentException("unknown view: " + name);
}
return result;
}
}
diff --git a/src/main/java/net/oneandone/lavender/index/Distributor.java b/src/main/java/net/oneandone/lavender/index/Distributor.java
index 5eaa83c..eeed5d0 100644
--- a/src/main/java/net/oneandone/lavender/index/Distributor.java
+++ b/src/main/java/net/oneandone/lavender/index/Distributor.java
@@ -1,122 +1,118 @@
/**
* Copyright 1&1 Internet AG, https://github.com/1and1/
*
* 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.oneandone.lavender.index;
import net.oneandone.lavender.config.Docroot;
import net.oneandone.lavender.config.Host;
import net.oneandone.sushi.fs.Node;
import net.oneandone.sushi.fs.World;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/** Receives extracted files and uploads them */
public class Distributor {
public static Distributor open(World world, List<Host> hosts, Docroot docroot, String indexName) throws IOException {
Node root;
Node destroot;
Node index;
Map<Node, Node> targets;
Index prev;
Index tmp;
targets = new LinkedHashMap<>(); // to preserve order
prev = null;
for (Host host : hosts) {
root = host.open(world);
destroot = docroot.node(root);
index = docroot.index(root, indexName);
if (index.exists()) {
tmp = Index.load(index);
} else {
tmp = new Index();
}
if (prev == null) {
prev = tmp;
} else {
if (!prev.equals(tmp)) {
throw new IOException("index mismatch");
}
}
targets.put(index, destroot);
}
if (prev == null) {
// no hosts!
prev = new Index();
}
return new Distributor(targets, prev);
}
/** left: index location; right: docroot */
private final Map<Node, Node> targets;
private final Index prev;
private final Index next;
- public Distributor() {
- this(new HashMap<Node, Node>(), new Index());
- }
-
public Distributor(Map<Node, Node> targets, Index prev) {
this.targets = targets;
this.prev = prev;
this.next = new Index();
}
public boolean write(Label label, byte[] data) throws IOException {
Node dest;
String destPath;
Label prevLabel;
boolean changed;
prevLabel = prev.lookup(label.getOriginalPath());
if (prevLabel == null || !Arrays.equals(prevLabel.md5(), label.md5())) {
destPath = label.getLavendelizedPath();
for (Node destroot : targets.values()) {
dest = destroot.join(destPath);
// always create parent, because even if the label exists: a changed md5 sum causes a changed path
dest.getParent().mkdirsOpt();
dest.writeBytes(data);
}
changed = true;
} else {
changed = false;
}
next.add(label);
return changed;
}
/** return next index */
public Index close() throws IOException {
Node index;
if (next.size() == 0) {
return next;
}
for (Map.Entry<Node, Node> entry : targets.entrySet()) {
index = entry.getKey();
index.getParent().mkdirsOpt();
try (OutputStream out = index.createOutputStream()) {
next.save(out);
}
}
return next;
}
}
| false | false | null | null |
diff --git a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/SuperTypeParameterInfo.java b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/SuperTypeParameterInfo.java
index 48cd5894..9e7d9b94 100644
--- a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/SuperTypeParameterInfo.java
+++ b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/SuperTypeParameterInfo.java
@@ -1,40 +1,43 @@
package jp.ac.osaka_u.ist.sel.metricstool.main.data.target;
+
import jp.ac.osaka_u.ist.sel.metricstool.main.security.MetricsToolSecurityManager;
public final class SuperTypeParameterInfo extends TypeParameterInfo {
/**
* �^�p�����[�^���C�h���N���X�^��^���ăI�u�W�F�N�g��������
*
+ * @param ownerUnit ���̌^�p�����[�^�̏��L���j�b�g(�N���X or ���\�b�h)
* @param name �^�p�����[�^��
* @param extendsType ���N���X�^
* @param superType �h���N���X�^
*/
- public SuperTypeParameterInfo(final String name, final TypeInfo extendsType, final TypeInfo superType) {
+ public SuperTypeParameterInfo(final UnitInfo ownerUnit, final String name,
+ final TypeInfo extendsType, final TypeInfo superType) {
- super(name, extendsType);
+ super(ownerUnit, name, extendsType);
MetricsToolSecurityManager.getInstance().checkAccess();
if (null == superType) {
throw new NullPointerException();
}
this.superType = superType;
}
/**
* �h���N���X�^��Ԃ�
*
* @return �h���N���X�^
*/
public TypeInfo getSuperType() {
return this.superType;
}
/**
* �������h���N���X�^��ۑ�����
*/
private final TypeInfo superType;
}
diff --git a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/unresolved/UnresolvedSuperTypeParameterInfo.java b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/unresolved/UnresolvedSuperTypeParameterInfo.java
index 9b1f36b9..8fb453c0 100644
--- a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/unresolved/UnresolvedSuperTypeParameterInfo.java
+++ b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/unresolved/UnresolvedSuperTypeParameterInfo.java
@@ -1,93 +1,101 @@
package jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.CallableUnitInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ClassInfoManager;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.FieldInfoManager;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.MethodInfoManager;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.SuperTypeParameterInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TargetClassInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TypeInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TypeParameterInfo;
+import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.UnitInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.security.MetricsToolSecurityManager;
public final class UnresolvedSuperTypeParameterInfo extends UnresolvedTypeParameterInfo {
/**
* �^�p�����[�^���C�������h���N���X�^��^���ăI�u�W�F�N�g��������
*
+ * @param ownerUnit ���̌^�p�����[�^�̏��L���j�b�g(�N���X or�@���\�b�h)
* @param name �^�p�����[�^��
* @param extendsType ���������N���X�^
* @param superType �������h���N���X�^
*/
- public UnresolvedSuperTypeParameterInfo(final String name,
- final UnresolvedTypeInfo extendsType, final UnresolvedTypeInfo superType) {
+ public UnresolvedSuperTypeParameterInfo(final UnresolvedUnitInfo<?> ownerUnit,
+ final String name, final UnresolvedTypeInfo extendsType,
+ final UnresolvedTypeInfo superType) {
- super(name, extendsType);
+ super(ownerUnit, name, extendsType);
if (null == superType) {
throw new NullPointerException();
}
this.superType = superType;
}
/**
* ���O�������s��
*
* @param usingClass ���O�������s���G���e�B�e�B������N���X
* @param usingMethod ���O�������s���G���e�B�e�B�����郁�\�b�h
* @param classInfoManager �p����N���X�}�l�[�W��
* @param fieldInfoManager �p����t�B�[���h�}�l�[�W��
* @param methodInfoManager �p���郁�\�b�h�}�l�[�W��
*
* @return �����ς݂̌^�p�����[�^
*/
@Override
public TypeParameterInfo resolveType(final TargetClassInfo usingClass,
final CallableUnitInfo usingMethod, final ClassInfoManager classInfoManager,
final FieldInfoManager fieldInfoManager, final MethodInfoManager methodInfoManager) {
// �s���ȌĂяo���łȂ������`�F�b�N
MetricsToolSecurityManager.getInstance().checkAccess();
if (null == classInfoManager) {
throw new NullPointerException();
}
final String name = this.getName();
final UnresolvedTypeInfo unresolvedSuperType = this.getSuperType();
final TypeInfo superType = unresolvedSuperType.resolveType(usingClass, usingMethod,
classInfoManager, fieldInfoManager, methodInfoManager);
+ //�@�^�p�����[�^�̏��L���j�b�g������
+ final UnresolvedUnitInfo<?> unresolvedOwnerUnit = this.getOwnerUnit();
+ final UnitInfo ownerUnit = unresolvedOwnerUnit.resolveUnit(usingClass, usingMethod,
+ classInfoManager, fieldInfoManager, methodInfoManager);
+
// extends �� ������ꍇ
if (this.hasExtendsType()) {
final UnresolvedTypeInfo unresolvedExtendsType = this.getExtendsType();
final TypeInfo extendsType = unresolvedExtendsType.resolveType(usingClass, usingMethod,
classInfoManager, fieldInfoManager, methodInfoManager);
- this.resolvedInfo = new SuperTypeParameterInfo(name, extendsType, superType);
+ this.resolvedInfo = new SuperTypeParameterInfo(ownerUnit, name, extendsType, superType);
} else {
- this.resolvedInfo = new SuperTypeParameterInfo(name, null, superType);
+ this.resolvedInfo = new SuperTypeParameterInfo(ownerUnit, name, null, superType);
}
return this.resolvedInfo;
}
/**
* �������h���N���X�^��Ԃ�
*
* @return �������h���N���X�^
*/
public UnresolvedTypeInfo getSuperType() {
return this.superType;
}
/**
* �������h���N���X�^��ۑ�����
*/
private final UnresolvedTypeInfo superType;
}
| false | false | null | null |
diff --git a/org.eclipse.jubula.client.ui.rcp/src/org/eclipse/jubula/client/ui/rcp/businessprocess/CompletenessBP.java b/org.eclipse.jubula.client.ui.rcp/src/org/eclipse/jubula/client/ui/rcp/businessprocess/CompletenessBP.java
index dfbe94611..3f0657925 100644
--- a/org.eclipse.jubula.client.ui.rcp/src/org/eclipse/jubula/client/ui/rcp/businessprocess/CompletenessBP.java
+++ b/org.eclipse.jubula.client.ui.rcp/src/org/eclipse/jubula/client/ui/rcp/businessprocess/CompletenessBP.java
@@ -1,165 +1,178 @@
/*******************************************************************************
* Copyright (c) 2004, 2010 BREDEX GmbH.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* BREDEX GmbH - initial API and implementation and/or initial documentation
*******************************************************************************/
package org.eclipse.jubula.client.ui.rcp.businessprocess;
import java.lang.reflect.InvocationTargetException;
import java.util.Locale;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IExecutionListener;
import org.eclipse.core.commands.NotHandledException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jubula.client.core.businessprocess.compcheck.CompletenessGuard;
import org.eclipse.jubula.client.core.events.DataEventDispatcher;
import org.eclipse.jubula.client.core.events.DataEventDispatcher.ILanguageChangedListener;
import org.eclipse.jubula.client.core.events.DataEventDispatcher.IProjectOpenedListener;
import org.eclipse.jubula.client.core.model.INodePO;
import org.eclipse.jubula.client.core.model.IProjectPO;
import org.eclipse.jubula.client.core.persistence.GeneralStorage;
import org.eclipse.jubula.client.ui.rcp.Plugin;
import org.eclipse.jubula.client.ui.rcp.i18n.Messages;
import org.eclipse.jubula.tools.constants.DebugConstants;
import org.eclipse.ui.IWorkbenchCommandConstants;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.commands.ICommandService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author BREDEX GmbH
* @created 12.03.2007
*/
public class CompletenessBP implements IProjectOpenedListener,
ILanguageChangedListener {
/** for log messages */
private static Logger log = LoggerFactory.getLogger(CompletenessBP.class);
/** this instance */
private static CompletenessBP instance;
/**
* private constructor
*/
private CompletenessBP() {
DataEventDispatcher ded = DataEventDispatcher.getInstance();
ded.addLanguageChangedListener(this, false);
ded.addProjectOpenedListener(this);
ICommandService commandService = (ICommandService) PlatformUI
.getWorkbench().getService(ICommandService.class);
IExecutionListener saveListener = new IExecutionListener() {
/** {@inheritDoc} */
public void preExecute(String commandId, ExecutionEvent event) {
// empty is ok
}
/** {@inheritDoc} */
public void postExecuteSuccess(String commandId,
Object returnValue) {
- completeProjectCheck();
+ if (isInteresting(commandId)) {
+ completeProjectCheck();
+ }
}
/** {@inheritDoc} */
public void postExecuteFailure(String commandId,
ExecutionException exception) {
- completeProjectCheck();
+ if (isInteresting(commandId)) {
+ completeProjectCheck();
+ }
}
/** {@inheritDoc} */
public void notHandled(String commandId,
NotHandledException exception) {
// empty is ok
}
+
+ /** whether the corresponding command is "interesting" */
+ private boolean isInteresting(String commandId) {
+ boolean isInteresting = false;
+ if (IWorkbenchCommandConstants.FILE_SAVE.equals(commandId)
+ || IWorkbenchCommandConstants.FILE_SAVE_ALL
+ .equals(commandId)) {
+ isInteresting = true;
+ }
+ return isInteresting;
+ }
};
- commandService.getCommand(IWorkbenchCommandConstants.FILE_SAVE)
- .addExecutionListener(saveListener);
- commandService.getCommand(IWorkbenchCommandConstants.FILE_SAVE_ALL)
- .addExecutionListener(saveListener);
+ commandService.addExecutionListener(saveListener);
+ commandService.addExecutionListener(saveListener);
}
/**
* @return the ComponentNamesList
*/
public static CompletenessBP getInstance() {
if (instance == null) {
instance = new CompletenessBP();
}
return instance;
}
/**
* {@inheritDoc}
*/
public void handleProjectOpened() {
completeProjectCheck();
}
/**
* checks the project regardless of user preferences
*/
public void completeProjectCheck() {
final INodePO root = GeneralStorage.getInstance().getProject();
if (root != null) {
Plugin.startLongRunning(Messages
.CompletenessCheckRunningOperation);
try {
PlatformUI.getWorkbench().getProgressService().run(true, false,
new UICompletenessCheckOperation());
} catch (InvocationTargetException e) {
log.error(DebugConstants.ERROR, e);
} catch (InterruptedException e) {
log.error(DebugConstants.ERROR, e);
} finally {
Plugin.stopLongRunning();
}
}
}
/**
* @author Markus Tiede
* @created 07.11.2011
*/
public static class UICompletenessCheckOperation implements
IRunnableWithProgress {
/** {@inheritDoc} */
public void run(IProgressMonitor monitor) {
monitor.beginTask(Messages.CompletenessCheckRunningOperation,
IProgressMonitor.UNKNOWN);
try {
final IProjectPO project = GeneralStorage.getInstance()
.getProject();
final Locale wl = WorkingLanguageBP.getInstance()
.getWorkingLanguage();
CompletenessGuard.checkAll(wl, project);
} finally {
fireCompletenessCheckFinished();
monitor.done();
}
}
}
/** {@inheritDoc} */
public void handleLanguageChanged(Locale locale) {
INodePO root = GeneralStorage.getInstance().getProject();
Locale wl = WorkingLanguageBP.getInstance().getWorkingLanguage();
CompletenessGuard.checkTestData(wl, root);
fireCompletenessCheckFinished();
}
/**
* Notifies that the check is finished.
*/
private static void fireCompletenessCheckFinished() {
DataEventDispatcher.getInstance().fireCompletenessCheckFinished();
}
}
\ No newline at end of file
| false | false | null | null |
diff --git a/citations-tool/tool/src/java/org/sakaiproject/citation/entity/CitationEntityProvider.java b/citations-tool/tool/src/java/org/sakaiproject/citation/entity/CitationEntityProvider.java
index 032c64c..90edeba 100644
--- a/citations-tool/tool/src/java/org/sakaiproject/citation/entity/CitationEntityProvider.java
+++ b/citations-tool/tool/src/java/org/sakaiproject/citation/entity/CitationEntityProvider.java
@@ -1,170 +1,170 @@
package org.sakaiproject.citation.entity;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.sakaiproject.citation.api.Citation;
import org.sakaiproject.citation.api.CitationCollection;
import org.sakaiproject.citation.api.CitationService;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.entitybroker.EntityView;
import org.sakaiproject.entitybroker.entityprovider.annotations.EntityCustomAction;
import org.sakaiproject.entitybroker.entityprovider.capabilities.ActionsExecutable;
import org.sakaiproject.entitybroker.entityprovider.capabilities.AutoRegisterEntityProvider;
import org.sakaiproject.entitybroker.entityprovider.capabilities.Outputable;
import org.sakaiproject.entitybroker.exception.EntityException;
import org.sakaiproject.entitybroker.exception.EntityNotFoundException;
import org.sakaiproject.entitybroker.util.AbstractEntityProvider;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.exception.ServerOverloadException;
import org.sakaiproject.exception.TypeException;
/**
* Citations service is built on top of resources. All permissions checks are
* handled by resources (ContentHostingService). Nothing that accepts the
* Citations List ID should be exposed as it would allow security checks to be
* bypassed.
*
*/
public class CitationEntityProvider extends AbstractEntityProvider implements
AutoRegisterEntityProvider, ActionsExecutable, Outputable {
private CitationService citationService;
private ContentHostingService contentHostingService;
public void setCitationService(CitationService citationService) {
this.citationService = citationService;
}
public void setContentHostingService(
ContentHostingService contentHostingService) {
this.contentHostingService = contentHostingService;
}
public String getEntityPrefix() {
return "citation";
}
@EntityCustomAction(action = "list", viewKey = EntityView.VIEW_LIST)
public DecoratedCitationCollection getCitationList(EntityView view,
Map<String, Object> params) {
StringBuilder resourceId = new StringBuilder();
String[] segments = view.getPathSegments();
for (int i = 2; i < segments.length; i++) {
resourceId.append("/");
resourceId.append(segments[i]);
}
if (resourceId.length() == 0) {
throw new EntityNotFoundException(
"You must supply a path to the citation list.", null);
}
try {
ContentResource resource = contentHostingService
.getResource(resourceId.toString());
if (!CitationService.CITATION_LIST_ID.equals(resource
.getResourceType())) {
throw new EntityException("Not a citation list",
resourceId.toString(), 400);
}
if (resource.getContentLength() > 1024) {
throw new EntityException("Bad citation list",
resourceId.toString(), 400);
}
String citationCollectionId = new String(resource.getContent());
CitationCollection collection = citationService
.getCollection(citationCollectionId);
ResourceProperties properties = resource.getProperties();
String title = properties
.getProperty(ResourceProperties.PROP_DISPLAY_NAME);
String description = properties
.getProperty(ResourceProperties.PROP_DESCRIPTION);
DecoratedCitationCollection dCollection = new DecoratedCitationCollection(
title, description);
for (Citation citation : (List<Citation>) collection.getCitations()) {
dCollection.addCitation(new DecoratedCitation(citation
.getSchema().getIdentifier(), citation
.getCitationProperties()));
}
return dCollection;
} catch (PermissionException e) {
// TODO User logged in?
throw new EntityException("Permission denied",
resourceId.toString(), 401);
} catch (IdUnusedException e) {
throw new EntityException("Not found", resourceId.toString(), 404);
} catch (TypeException e) {
throw new EntityException("Wrong type", resourceId.toString(), 400);
} catch (ServerOverloadException e) {
throw new EntityException("Server Overloaded",
resourceId.toString(), 500);
}
}
//
/**
* This wraps fields from a citation for entity broker.
*
* @author buckett
*
*/
public class DecoratedCitation {
private String type;
private Map<String, String> values;
public DecoratedCitation(String type, Map<String, String> values) {
this.type = type;
this.values = values;
}
public String getType() {
return type;
}
public Map<String, String> getValues() {
return values;
}
}
public class DecoratedCitationCollection {
private String name;
- private String desctiption;
+ private String description;
private List<DecoratedCitation> citations;
public DecoratedCitationCollection(String name, String description) {
this.name = name;
- this.desctiption = description;
+ this.description = description;
this.citations = new ArrayList<DecoratedCitation>();
}
public void addCitation(DecoratedCitation citation) {
citations.add(citation);
}
public String getName() {
return name;
}
- public String getDesctiption() {
- return desctiption;
+ public String getDescription() {
+ return description;
}
public List<DecoratedCitation> getCitations() {
return citations;
}
}
public String[] getHandledOutputFormats() {
return new String[] { JSON, FORM, HTML, XML, TXT };
}
}
| false | false | null | null |
diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/quickdiff/LastSaveReferenceProvider.java b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/quickdiff/LastSaveReferenceProvider.java
index 7a14205eb..1209786fa 100644
--- a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/quickdiff/LastSaveReferenceProvider.java
+++ b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/quickdiff/LastSaveReferenceProvider.java
@@ -1,494 +1,494 @@
/*******************************************************************************
* 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.ui.internal.editors.quickdiff;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import org.eclipse.core.resources.IEncodedStorage;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IStorage;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.content.IContentDescription;
import org.eclipse.core.runtime.jobs.IJobManager;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IStorageEditorInput;
import org.eclipse.ui.editors.text.EditorsUI;
import org.eclipse.ui.editors.text.IStorageDocumentProvider;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.IElementStateListener;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.ui.texteditor.quickdiff.IQuickDiffReferenceProvider;
/**
* Default provider for the quickdiff display - the saved document is taken as
* the reference.
*
* @since 3.0
*/
public class LastSaveReferenceProvider implements IQuickDiffReferenceProvider, IElementStateListener {
/** <code>true</code> if the document has been read. */
private boolean fDocumentRead= false;
/**
* The reference document - might be <code>null</code> even if <code>fDocumentRead</code>
* is <code>true</code>.
*/
private IDocument fReference= null;
/**
* Our unique id that makes us comparable to another instance of the same
* provider. See extension point reference.
*/
private String fId;
/** The current document provider. */
private IDocumentProvider fDocumentProvider;
/** The current editor input. */
private IEditorInput fEditorInput;
/** Private lock no one else will synchronize on. */
private final Object fLock= new Object();
/** The document lock for non-IResources. */
- private Object fDocumentAccessorLock;
+ private final Object fDocumentAccessorLock= new Object();
/** Document lock state, protected by <code>fDocumentAccessorLock</code>. */
private boolean fDocumentLocked;
/**
* The progress monitor for a currently running <code>getReference</code>
* operation, or <code>null</code>.
*/
private IProgressMonitor fProgressMonitor;
/** The text editor we run upon. */
private ITextEditor fEditor;
/**
* A job to put the reading of file contents into a background.
*/
private final class ReadJob extends Job {
/**
* Creates a new instance.
*/
public ReadJob() {
super(QuickDiffMessages.getString("LastSaveReferenceProvider.LastSaveReferenceProvider.readJob.label")); //$NON-NLS-1$
setSystem(true);
setPriority(SHORT);
}
/**
* Calls
* {@link LastSaveReferenceProvider#readDocument(IProgressMonitor, boolean)}
* and returns {@link Status#OK_STATUS}.
*
* {@inheritdoc}
*
* @param monitor {@inheritDoc}
* @return {@link Status#OK_STATUS}
*/
protected IStatus run(IProgressMonitor monitor) {
readDocument(monitor, false);
return Status.OK_STATUS;
}
}
/*
* @see org.eclipse.ui.texteditor.quickdiff.IQuickDiffReferenceProvider#getReference(org.eclipse.core.runtime.IProgressMonitor)
*/
public IDocument getReference(IProgressMonitor monitor) {
if (!fDocumentRead)
readDocument(monitor, true); // force reading it
return fReference;
}
/*
* @see org.eclipse.ui.texteditor.quickdiff.IQuickDiffReferenceProvider#dispose()
*/
public void dispose() {
IProgressMonitor monitor= fProgressMonitor;
if (monitor != null) {
monitor.setCanceled(true);
}
IDocumentProvider provider= fDocumentProvider;
synchronized (fLock) {
if (provider != null)
provider.removeElementStateListener(this);
fEditorInput= null;
fDocumentProvider= null;
fReference= null;
fDocumentRead= false;
fProgressMonitor= null;
fEditor= null;
}
}
/*
* @see org.eclipse.ui.texteditor.quickdiff.IQuickDiffReferenceProvider#getId()
*/
public String getId() {
return fId;
}
/*
* @see org.eclipse.ui.texteditor.quickdiff.IQuickDiffProviderImplementation#setActiveEditor(org.eclipse.ui.texteditor.ITextEditor)
*/
public void setActiveEditor(ITextEditor targetEditor) {
IDocumentProvider provider= null;
IEditorInput input= null;
if (targetEditor != null) {
provider= targetEditor.getDocumentProvider();
input= targetEditor.getEditorInput();
}
// dispose if the editor input or document provider have changed
// note that they may serve multiple editors
if (provider != fDocumentProvider || input != fEditorInput) {
dispose();
synchronized (fLock) {
fEditor= targetEditor;
fDocumentProvider= provider;
fEditorInput= input;
}
}
}
/*
* @see org.eclipse.ui.texteditor.quickdiff.IQuickDiffProviderImplementation#isEnabled()
*/
public boolean isEnabled() {
return fEditorInput != null && fDocumentProvider != null;
}
/*
* @see org.eclipse.ui.texteditor.quickdiff.IQuickDiffProviderImplementation#setId(java.lang.String)
*/
public void setId(String id) {
fId= id;
}
/**
* Reads in the saved document into <code>fReference</code>.
*
* @param monitor a progress monitor, or <code>null</code>
* @param force <code>true</code> if the reference document should also
* be read if the current document is <code>null</code>,<code>false</code>
* if it should only be updated if it already existed.
*/
private void readDocument(IProgressMonitor monitor, boolean force) {
// protect against concurrent disposal
IDocumentProvider prov= fDocumentProvider;
IEditorInput inp= fEditorInput;
IDocument doc= fReference;
ITextEditor editor= fEditor;
if (prov instanceof IStorageDocumentProvider && inp instanceof IStorageEditorInput) {
IStorageEditorInput input= (IStorageEditorInput) inp;
IStorageDocumentProvider provider= (IStorageDocumentProvider) prov;
if (doc == null)
if (force || fDocumentRead)
doc= new Document();
else
return;
IJobManager jobMgr= Platform.getJobManager();
IStorage storage= null;
try {
storage= input.getStorage();
fProgressMonitor= monitor;
// this protects others from not being able to delete the file,
// and protects ourselves from concurrent access to fReference
// (in the case there already is a valid fReference)
// one might argue that this rule should already be in the Job
// description we're running in, however:
// 1) we don't mind waiting for someone else here
// 2) we do not take long, or require other locks etc. -> short
// delay for any other job requiring the lock on file
try {
lockDocument(monitor, jobMgr, storage);
InputStream stream= getFileContents(storage);
if (stream == null)
return;
String encoding;
if (storage instanceof IEncodedStorage)
encoding= ((IEncodedStorage) storage).getCharset();
else
encoding= null;
boolean skipUTF8BOM= isUTF8BOM(encoding, storage);
setDocumentContent(doc, stream, encoding, monitor, skipUTF8BOM);
} finally {
unlockDocument(jobMgr, storage);
fProgressMonitor= null;
}
} catch (IOException e) {
return;
} catch (CoreException e) {
return;
}
if (monitor != null && monitor.isCanceled())
return;
// update state
synchronized (fLock) {
if (fDocumentProvider == provider && fEditorInput == input) {
// only update state if our provider / input pair has not
// been updated in between (dispose or setActiveEditor)
fReference= doc;
fDocumentRead= true;
addElementStateListener(editor, prov);
}
}
}
}
/* utility methods */
private void lockDocument(IProgressMonitor monitor, IJobManager jobMgr, IStorage storage) {
ISchedulingRule rule= null;
if (storage instanceof ISchedulingRule)
rule= (ISchedulingRule) storage;
else if (storage != null)
rule= (ISchedulingRule) storage.getAdapter(ISchedulingRule.class);
if (rule != null) {
jobMgr.beginRule(rule, monitor);
} else synchronized (fDocumentAccessorLock) {
while (fDocumentLocked) {
try {
fDocumentAccessorLock.wait();
} catch (InterruptedException e) {
// nobody interrupts us!
throw new OperationCanceledException();
}
}
fDocumentLocked= true;
}
}
private void unlockDocument(IJobManager jobMgr, IStorage storage) {
ISchedulingRule rule= null;
if (storage instanceof ISchedulingRule)
rule= (ISchedulingRule) storage;
else if (storage != null)
rule= (ISchedulingRule) storage.getAdapter(ISchedulingRule.class);
if (rule != null) {
jobMgr.endRule(rule);
} else synchronized (fDocumentAccessorLock) {
fDocumentLocked= false;
fDocumentAccessorLock.notify();
}
}
/**
* Adds this as element state listener in the UI thread as it can otherwise
* conflict with other listener additions, since DocumentProvider is not
* thread-safe.
*
* @param editor the editor to get the display from
* @param provider the document provider to register as element state listener
*/
private void addElementStateListener(ITextEditor editor, final IDocumentProvider provider) {
// addElementStateListener adds at most once - no problem to call
provider.addElementStateListener(this);
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=66686 and
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=56871
// // repeatedly
// Runnable runnable= new Runnable() {
// public void run() {
// synchronized (fLock) {
// if (fDocumentProvider == provider)
// provider.addElementStateListener(LastSaveReferenceProvider.this);
// }
// }
// };
//
// Display display= null;
// if (editor != null) {
// IWorkbenchPartSite site= editor.getSite();
// if (site != null)
// site.getWorkbenchWindow().getShell().getDisplay();
// }
//
// if (display != null && !display.isDisposed())
// display.asyncExec(runnable);
// else
// runnable.run();
}
/**
* Gets the contents of <code>file</code> as an input stream.
*
* @param storage the <code>IStorage</code> which we want the content for
* @return an input stream for the file's content
*/
private static InputStream getFileContents(IStorage storage) {
InputStream stream= null;
try {
if (storage != null)
stream= storage.getContents();
} catch (CoreException e) {
// ignore
}
return stream;
}
/**
* Initializes the given document with the given stream using the given
* encoding.
*
* @param document the document to be initialized
* @param contentStream the stream which delivers the document content
* @param encoding the character encoding for reading the given stream
* @param monitor a progress monitor for cancellation, or <code>null</code>
* @param skipUTF8BOM whether to skip three bytes before reading the stream
* @exception IOException if the given stream can not be read
*/
private static void setDocumentContent(IDocument document, InputStream contentStream, String encoding, IProgressMonitor monitor, boolean skipUTF8BOM) throws IOException {
Reader in= null;
try {
if (skipUTF8BOM) {
for (int i= 0; i < 3; i++)
if (contentStream.read() == -1) {
throw new IOException(QuickDiffMessages.getString("LastSaveReferenceProvider.LastSaveReferenceProvider.error.notEnoughBytesForBOM")); //$NON-NLS-1$
}
}
final int DEFAULT_FILE_SIZE= 15 * 1024;
if (encoding == null)
in= new BufferedReader(new InputStreamReader(contentStream), DEFAULT_FILE_SIZE);
else
in= new BufferedReader(new InputStreamReader(contentStream, encoding), DEFAULT_FILE_SIZE);
StringBuffer buffer= new StringBuffer(DEFAULT_FILE_SIZE);
char[] readBuffer= new char[2048];
int n= in.read(readBuffer);
while (n > 0) {
if (monitor != null && monitor.isCanceled())
return;
buffer.append(readBuffer, 0, n);
n= in.read(readBuffer);
}
document.set(buffer.toString());
} finally {
if (in != null) {
try {
in.close();
} catch (IOException x) {
// ignore
}
}
}
}
/**
* Returns <code>true</code> if the <code>encoding</code> is UTF-8 and
* the file contains a BOM. Taken from ResourceTextFileBuffer.java.
*
* <p>
* XXX:
* This is a workaround for a corresponding bug in Java readers and writer,
* see: http://developer.java.sun.com/developer/bugParade/bugs/4508058.html
* </p>
* @param encoding the encoding
* @param storage the storage
* @return <code>true</code> if <code>storage</code> is a UTF-8-encoded file
* that has an UTF-8 BOM
* @throws CoreException if
* - reading of file's content description fails
* - byte order mark is not valid for UTF-8
*/
private static boolean isUTF8BOM(String encoding, IStorage storage) throws CoreException {
if (storage instanceof IFile && "UTF-8".equals(encoding)) { //$NON-NLS-1$
IFile file= (IFile) storage;
IContentDescription description= file.getContentDescription();
if (description != null) {
byte[] bom= (byte[]) description.getProperty(IContentDescription.BYTE_ORDER_MARK);
if (bom != null) {
if (bom != IContentDescription.BOM_UTF_8)
throw new CoreException(new Status(IStatus.ERROR, EditorsUI.PLUGIN_ID, IStatus.OK, QuickDiffMessages.getString("LastSaveReferenceProvider.LastSaveReferenceProvider.error.wrongByteOrderMark"), null)); //$NON-NLS-1$
return true;
}
}
}
return false;
}
/* IElementStateListener implementation */
/*
* @see org.eclipse.ui.texteditor.IElementStateListener#elementDirtyStateChanged(java.lang.Object, boolean)
*/
public void elementDirtyStateChanged(Object element, boolean isDirty) {
if (!isDirty && element == fEditorInput) {
// document has been saved or reverted - recreate reference
new ReadJob().schedule();
}
}
/*
* @see org.eclipse.ui.texteditor.IElementStateListener#elementContentAboutToBeReplaced(java.lang.Object)
*/
public void elementContentAboutToBeReplaced(Object element) {
}
/*
* @see org.eclipse.ui.texteditor.IElementStateListener#elementContentReplaced(java.lang.Object)
*/
public void elementContentReplaced(Object element) {
if (element == fEditorInput) {
// document has been reverted or replaced
new ReadJob().schedule();
}
}
/*
* @see org.eclipse.ui.texteditor.IElementStateListener#elementDeleted(java.lang.Object)
*/
public void elementDeleted(Object element) {
}
/*
* @see org.eclipse.ui.texteditor.IElementStateListener#elementMoved(java.lang.Object, java.lang.Object)
*/
public void elementMoved(Object originalElement, Object movedElement) {
}
}
| true | false | null | null |